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 |
---|---|---|---|---|---|---|---|---|---|---|
MCMDEV/chatchannels | src/main/java/dev/gamemode/chatchannels/ChatchannelsPlugin.java | [
{
"identifier": "ChatchannelsCommand",
"path": "src/main/java/dev/gamemode/chatchannels/command/ChatchannelsCommand.java",
"snippet": "public class ChatchannelsCommand extends BukkitCommand {\n\n private final ChannelProvider channelProvider;\n\n public ChatchannelsCommand(ChannelProvider channelProvider) {\n super(\"chatchannels\");\n this.channelProvider = channelProvider;\n\n setPermission(\"chatchannels\");\n }\n\n @Override\n public boolean execute(@NotNull CommandSender sender, @NotNull String label,\n @NotNull String[] args) {\n if (!(sender instanceof Player player)) {\n return true;\n }\n if (!testPermission(sender)) {\n return true;\n }\n\n channelProvider.getChannels().stream()\n .filter(channel -> channel.canSee(player))\n .forEach(channel -> {\n if (channel instanceof MembershipChannel membershipChannel) {\n player.sendMessage(getMembershipChannelComponent(membershipChannel));\n } else {\n player.sendMessage(getChannelComponent(channel));\n }\n });\n\n return true;\n }\n\n private Component getChannelComponent(Channel channel) {\n return Component.text()\n .append(channel.getDisplayName())\n .append(Component.text(\" - \", NamedTextColor.GRAY))\n .append(buildActive(channel))\n .build();\n }\n\n private Component getMembershipChannelComponent(MembershipChannel channel) {\n return Component.text()\n .append(channel.getDisplayName())\n .append(Component.text(\" - \", NamedTextColor.GRAY))\n .append(buildToggle(channel))\n .append(Component.space())\n .append(buildActive(channel))\n .build();\n }\n\n @NotNull\n private TextComponent buildToggle(MembershipChannel channel) {\n return Component.text(\"[Toggle]\", NamedTextColor.GOLD)\n .hoverEvent(HoverEvent.showText(Component.text(\"Click to toggle channel.\")))\n .clickEvent(ClickEvent.runCommand(\"/togglechannel \" + channel.getName()));\n }\n\n @NotNull\n private TextComponent buildActive(Channel channel) {\n return Component.text(\"[Switch]\", NamedTextColor.GOLD)\n .hoverEvent(HoverEvent.showText(Component.text(\"Click to switch channel.\")))\n .clickEvent(ClickEvent.runCommand(\"/switchchannel \" + channel.getName()));\n }\n}"
},
{
"identifier": "SendchannelCommand",
"path": "src/main/java/dev/gamemode/chatchannels/command/SendchannelCommand.java",
"snippet": "public class SendchannelCommand extends BukkitCommand {\n\n private final ChannelProvider channelProvider;\n\n public SendchannelCommand(ChannelProvider channelProvider) {\n super(\"sendchannel\");\n this.channelProvider = channelProvider;\n\n setPermission(\"chatchannels.sendchannel\");\n }\n\n @Override\n public boolean execute(@NotNull CommandSender sender, @NotNull String label,\n @NotNull String[] args) {\n if (!(sender instanceof Player player)) {\n return true;\n }\n if (!testPermission(sender)) {\n return true;\n }\n if (args.length < 2) {\n return false;\n }\n\n String channelName = args[0];\n\n channelProvider.getChannel(channelName).ifPresentOrElse(channel -> {\n if (!(channel instanceof MembershipChannel membershipChannel)) {\n player.sendMessage(\n Component.text(\"This channel cannot be joined.\", NamedTextColor.GOLD)\n );\n return;\n }\n\n String joined = String.join(\" \", Arrays.copyOfRange(args, 1, args.length));\n channel.getViewers().forEach(audience -> {\n audience.sendMessage(channel.getRenderer()\n .render(channel.getDisplayName(), player.displayName(), Component.text(joined)));\n });\n }, () -> {\n player.sendMessage(\n Component.text(\"Channel not found.\", NamedTextColor.GOLD)\n );\n });\n\n return true;\n }\n\n @Override\n public @NotNull List<String> tabComplete(@NotNull CommandSender sender, @NotNull String alias,\n @NotNull String[] args) throws IllegalArgumentException {\n if (!(sender instanceof Player player)) {\n return Collections.emptyList();\n }\n if (!testPermission(sender)) {\n return Collections.emptyList();\n }\n if (args.length > 1) {\n return Collections.emptyList();\n }\n\n return channelProvider.getChannels().stream()\n .filter(channel -> channel.canSee(player))\n .map(Channel::getName)\n .toList();\n }\n}"
},
{
"identifier": "SwitchchannelCommand",
"path": "src/main/java/dev/gamemode/chatchannels/command/SwitchchannelCommand.java",
"snippet": "public class SwitchchannelCommand extends BukkitCommand {\n\n private final ChannelProvider channelProvider;\n private final ActiveChannelStorage activeChannelStorage;\n\n public SwitchchannelCommand(ChannelProvider channelProvider,\n ActiveChannelStorage activeChannelStorage) {\n super(\"switchchannel\");\n this.channelProvider = channelProvider;\n this.activeChannelStorage = activeChannelStorage;\n\n setPermission(\"chatchannels.switchchannel\");\n }\n\n @Override\n public boolean execute(@NotNull CommandSender sender, @NotNull String label,\n @NotNull String[] args) {\n if (!(sender instanceof Player player)) {\n return true;\n }\n if (!testPermission(sender)) {\n return true;\n }\n if (args.length == 0) {\n activeChannelStorage.getActiveChannel(player.getUniqueId()).ifPresentOrElse(channel -> {\n activeChannelStorage.deactivate(player.getUniqueId());\n\n player.sendMessage(\n Component.text(\"You have left the channel.\", NamedTextColor.GOLD)\n );\n }, () -> player.sendMessage(\n Component.text(\"You are not in a channel.\", NamedTextColor.GOLD)\n ));\n return true;\n }\n\n String channelName = args[0];\n\n channelProvider.getChannel(channelName).ifPresentOrElse(channel -> {\n if (!(channel instanceof MembershipChannel membershipChannel)) {\n player.sendMessage(\n Component.text(\"This channel cannot be switched to.\", NamedTextColor.GOLD)\n );\n return;\n }\n if (!membershipChannel.canJoin(player)) {\n player.sendMessage(\n Component.text(\"You cannot switch to this channel.\", NamedTextColor.GOLD)\n );\n return;\n }\n\n activeChannelStorage.switchChannel(player.getUniqueId(), membershipChannel);\n player.sendMessage(\n Component.text(\"You have switched to the channel.\", NamedTextColor.GOLD)\n );\n }, () -> {\n player.sendMessage(\n Component.text(\"Channel not found.\", NamedTextColor.GOLD)\n );\n });\n\n return true;\n }\n\n @Override\n public @NotNull List<String> tabComplete(@NotNull CommandSender sender, @NotNull String alias,\n @NotNull String[] args) throws IllegalArgumentException {\n if (!(sender instanceof Player player)) {\n return Collections.emptyList();\n }\n if (!testPermission(sender)) {\n return Collections.emptyList();\n }\n\n return channelProvider.getChannels().stream()\n .filter(channel -> channel.canSee(player))\n .map(Channel::getName)\n .toList();\n }\n}"
},
{
"identifier": "TogglechannelCommand",
"path": "src/main/java/dev/gamemode/chatchannels/command/TogglechannelCommand.java",
"snippet": "public class TogglechannelCommand extends BukkitCommand {\n\n private final ChannelProvider channelProvider;\n\n public TogglechannelCommand(ChannelProvider channelProvider) {\n super(\"togglechannel\");\n this.channelProvider = channelProvider;\n\n setPermission(\"chatchannels.togglechannel\");\n }\n\n @Override\n public boolean execute(@NotNull CommandSender sender, @NotNull String label,\n @NotNull String[] args) {\n if (!(sender instanceof Player player)) {\n return true;\n }\n if (!testPermission(sender)) {\n return true;\n }\n\n if (args.length == 0) {\n return false;\n }\n\n String channelName = args[0];\n\n channelProvider.getChannel(channelName).ifPresentOrElse(channel -> {\n if (!(channel instanceof MembershipChannel membershipChannel)) {\n player.sendMessage(\n Component.text(\"This channel cannot be joined.\", NamedTextColor.GOLD)\n );\n return;\n }\n\n handleMembershipSwitch(player, membershipChannel);\n }, () -> {\n player.sendMessage(\n Component.text(\"Channel not found.\", NamedTextColor.GOLD)\n );\n });\n\n return true;\n }\n\n private void handleMembershipSwitch(Player player, MembershipChannel membershipChannel) {\n if (membershipChannel.isMember(player)) {\n membershipChannel.leave(player);\n player.sendMessage(\n Component.text(\"You have left the channel.\", NamedTextColor.GOLD)\n );\n } else {\n if (!membershipChannel.canJoin(player)) {\n player.sendMessage(\n Component.text(\"You cannot join this channel.\", NamedTextColor.GOLD)\n );\n return;\n }\n\n membershipChannel.join(player);\n player.sendMessage(\n Component.text(\"You have joined the channel.\", NamedTextColor.GOLD)\n );\n }\n }\n\n @Override\n public @NotNull List<String> tabComplete(@NotNull CommandSender sender, @NotNull String alias,\n @NotNull String[] args) throws IllegalArgumentException {\n if (!(sender instanceof Player player)) {\n return Collections.emptyList();\n }\n if (!testPermission(sender)) {\n return Collections.emptyList();\n }\n\n return channelProvider.getChannels().stream()\n .filter(channel -> channel.canSee(player))\n .map(Channel::getName)\n .toList();\n }\n}"
},
{
"identifier": "ConfigReader",
"path": "src/main/java/dev/gamemode/chatchannels/config/ConfigReader.java",
"snippet": "public class ConfigReader {\n\n private FileConfig fileConfig;\n\n public void load(File dataFolder) {\n if (!dataFolder.exists()) {\n dataFolder.mkdirs();\n }\n\n File filePath = new File(dataFolder, \"config.yml\");\n this.fileConfig = FileConfig.builder(filePath)\n .onFileNotFound(\n FileNotFoundAction.copyData(ConfigReader.class.getResourceAsStream(\"/config.yml\")))\n .charset(StandardCharsets.UTF_8)\n .build();\n this.fileConfig.load();\n }\n\n public ChannelProvider configureProvider() {\n String defaultRenderer = fileConfig.get(\"channel-renderer\");\n Config channelsConfig = fileConfig.get(\"channels\");\n\n return new MapChannelProvider(\n channelsConfig.entrySet().stream().map(entry -> {\n Config channelConfig = channelsConfig.get(entry.getKey());\n return configureChannel(entry.getKey(), channelConfig, defaultRenderer);\n }).collect(Collectors.toMap(Channel::getName, o -> o)\n ));\n }\n\n public Channel configureChannel(String key, Config config, String defaultRenderer) {\n Component displayName = MiniMessage.miniMessage().deserialize(config.get(\"display-name\"));\n ChannelRenderer channelRenderer =\n new ConfiguredRenderer(config.getOrElse(\"channel-renderer\", defaultRenderer));\n\n return new SetCollectionChannel(key, displayName, new HashSet<>(), channelRenderer);\n }\n\n}"
},
{
"identifier": "ChatListener",
"path": "src/main/java/dev/gamemode/chatchannels/listener/ChatListener.java",
"snippet": "@RequiredArgsConstructor\npublic class ChatListener implements Listener {\n\n private final ActiveChannelStorage activeChannelStorage;\n\n @EventHandler\n private void onChat(AsyncChatEvent event) {\n activeChannelStorage.getActiveChannel(event.getPlayer().getUniqueId()).ifPresent(channel -> {\n event.viewers().clear();\n event.viewers().addAll(channel.getViewers());\n\n event.renderer(ChatRenderer.viewerUnaware(\n (source, sourceDisplayName, message) -> channel.getRenderer()\n .render(channel.getDisplayName(), event.getPlayer().displayName(), event.message())));\n });\n }\n\n}"
},
{
"identifier": "ConnectionListener",
"path": "src/main/java/dev/gamemode/chatchannels/listener/ConnectionListener.java",
"snippet": "@RequiredArgsConstructor\npublic class ConnectionListener implements Listener {\n\n private final ChannelProvider channelProvider;\n\n @EventHandler\n private void onJoin(PlayerJoinEvent event) {\n channelProvider.getChannels()\n .stream()\n .filter(channel -> channel.canSee(event.getPlayer()))\n .filter(channel -> channel instanceof MembershipChannel)\n .map(channel -> (MembershipChannel) channel)\n .filter(membershipChannel -> membershipChannel.shouldAutojoin(event.getPlayer()))\n .forEach(channel -> channel.join(event.getPlayer()));\n }\n\n @EventHandler\n private void onQuit(PlayerQuitEvent event) {\n channelProvider.getChannels()\n .stream()\n .filter(channel -> channel instanceof MembershipChannel)\n .map(channel -> (MembershipChannel) channel)\n .filter(channel -> channel.isMember(event.getPlayer()))\n .forEach(channel -> channel.leave(event.getPlayer()));\n }\n\n}"
},
{
"identifier": "ActiveChannelStorage",
"path": "src/main/java/dev/gamemode/chatchannels/model/active/ActiveChannelStorage.java",
"snippet": "public interface ActiveChannelStorage {\n\n Optional<Channel> getActiveChannel(UUID uuid);\n\n void switchChannel(UUID uuid, Channel channel);\n\n void deactivate(UUID uniqueId);\n}"
},
{
"identifier": "MapActiveChannelStorage",
"path": "src/main/java/dev/gamemode/chatchannels/model/active/MapActiveChannelStorage.java",
"snippet": "public class MapActiveChannelStorage implements ActiveChannelStorage {\n\n private final Map<UUID, Channel> channels = new ConcurrentHashMap<>();\n\n @Override\n public Optional<Channel> getActiveChannel(UUID uuid) {\n return Optional.ofNullable(channels.get(uuid));\n }\n\n @Override\n public void switchChannel(UUID uuid, Channel channel) {\n channels.put(uuid, channel);\n }\n\n @Override\n public void deactivate(UUID uniqueId) {\n channels.remove(uniqueId);\n }\n}"
},
{
"identifier": "ChannelProvider",
"path": "src/main/java/dev/gamemode/chatchannels/model/provider/ChannelProvider.java",
"snippet": "public interface ChannelProvider {\n\n Optional<Channel> getChannel(String name);\n\n Collection<Channel> getChannels();\n}"
}
] | import dev.gamemode.chatchannels.command.ChatchannelsCommand;
import dev.gamemode.chatchannels.command.SendchannelCommand;
import dev.gamemode.chatchannels.command.SwitchchannelCommand;
import dev.gamemode.chatchannels.command.TogglechannelCommand;
import dev.gamemode.chatchannels.config.ConfigReader;
import dev.gamemode.chatchannels.listener.ChatListener;
import dev.gamemode.chatchannels.listener.ConnectionListener;
import dev.gamemode.chatchannels.model.active.ActiveChannelStorage;
import dev.gamemode.chatchannels.model.active.MapActiveChannelStorage;
import dev.gamemode.chatchannels.model.provider.ChannelProvider;
import org.bukkit.Bukkit;
import org.bukkit.plugin.java.JavaPlugin; | 3,339 | package dev.gamemode.chatchannels;
public class ChatchannelsPlugin extends JavaPlugin {
private ConfigReader configReader; | package dev.gamemode.chatchannels;
public class ChatchannelsPlugin extends JavaPlugin {
private ConfigReader configReader; | private ChannelProvider channelProvider; | 9 | 2023-11-07 20:33:27+00:00 | 4k |
firstdarkdev/modfusioner | src/main/java/com/hypherionmc/modfusioner/plugin/ModFusionerPlugin.java | [
{
"identifier": "Constants",
"path": "src/main/java/com/hypherionmc/modfusioner/Constants.java",
"snippet": "public class Constants {\n\n public static final String TASK_GROUP = \"modfusioner\";\n public static final String TASK_NAME = \"fusejars\";\n public static final String EXTENSION_NAME = \"fusioner\";\n public static final String MANIFEST_KEY = \"ModFusioner-Version\";\n\n public static Set<PosixFilePermission> filePerms = new HashSet<>();\n\n static {\n filePerms.add(PosixFilePermission.OTHERS_EXECUTE);\n filePerms.add(PosixFilePermission.OTHERS_WRITE);\n filePerms.add(PosixFilePermission.OTHERS_READ);\n filePerms.add(PosixFilePermission.OWNER_EXECUTE);\n filePerms.add(PosixFilePermission.OWNER_WRITE);\n filePerms.add(PosixFilePermission.OWNER_READ);\n filePerms.add(PosixFilePermission.GROUP_EXECUTE);\n filePerms.add(PosixFilePermission.GROUP_WRITE);\n filePerms.add(PosixFilePermission.GROUP_READ);\n }\n\n}"
},
{
"identifier": "JarFuseTask",
"path": "src/main/java/com/hypherionmc/modfusioner/task/JarFuseTask.java",
"snippet": "public class JarFuseTask extends Jar {\n\n // Fixed values\n private final File mergedJar;\n private static final AtomicBoolean hasRun = new AtomicBoolean(false);\n\n public JarFuseTask() {\n // Set task default values from extension\n getArchiveBaseName().set(modFusionerExtension.getMergedJarName());\n getArchiveVersion().set(modFusionerExtension.getJarVersion());\n getDestinationDirectory().set(getProject().file(modFusionerExtension.getOutputDirectory()));\n\n // We don't allow custom input files, when the user defines their own task\n getInputs().files();\n\n // Only allow the task to run once per cycle\n getOutputs().upToDateWhen(spec -> hasRun.get());\n\n // Set output file\n mergedJar = new File(getDestinationDirectory().get().getAsFile(), getArchiveFileName().get());\n getOutputs().file(mergedJar);\n }\n\n /**\n * Main task logic\n * @throws IOException - Thrown when an IO error occurs\n */\n void fuseJars() throws IOException {\n long time = System.currentTimeMillis();\n\n ModFusionerPlugin.logger.lifecycle(\"Start Fusing Jars\");\n\n // Get settings from extension\n FusionerExtension.ForgeConfiguration forgeConfiguration = modFusionerExtension.getForgeConfiguration();\n FusionerExtension.FabricConfiguration fabricConfiguration = modFusionerExtension.getFabricConfiguration();\n FusionerExtension.QuiltConfiguration quiltConfiguration = modFusionerExtension.getQuiltConfiguration();\n\n List<FusionerExtension.CustomConfiguration> customConfigurations = modFusionerExtension.getCustomConfigurations();\n\n // Try to resolve the projects specific in the extension config\n Project forgeProject = null;\n Project fabricProject = null;\n Project quiltProject = null;\n Map<Project, FusionerExtension.CustomConfiguration> customProjects = new HashMap<>();\n List<Boolean> validation = new ArrayList<>();\n\n if (forgeConfiguration != null) {\n try {\n forgeProject = rootProject.getAllprojects().stream().filter(p -> !p.getName().equals(rootProject.getName())).filter(p -> p.getName().equalsIgnoreCase(forgeConfiguration.getProjectName())).findFirst().get();\n validation.add(true);\n } catch (NoSuchElementException ignored) { }\n }\n\n if (fabricConfiguration != null) {\n try {\n fabricProject = rootProject.getAllprojects().stream().filter(p -> !p.getName().equals(rootProject.getName())).filter(p -> p.getName().equalsIgnoreCase(fabricConfiguration.getProjectName())).findFirst().get();\n validation.add(true);\n } catch (NoSuchElementException ignored) { }\n }\n\n if (quiltConfiguration != null) {\n try {\n quiltProject = rootProject.getAllprojects().stream().filter(p -> !p.getName().equals(rootProject.getName())).filter(p -> p.getName().equalsIgnoreCase(quiltConfiguration.getProjectName())).findFirst().get();\n validation.add(true);\n } catch (NoSuchElementException ignored) { }\n }\n\n if (customConfigurations != null) {\n for (FusionerExtension.CustomConfiguration customSettings : customConfigurations) {\n try {\n customProjects.put(rootProject.getAllprojects().stream().filter(p -> !p.getName().equals(rootProject.getName())).filter(p -> p.getName().equals(customSettings.getProjectName())).findFirst().get(), customSettings);\n validation.add(true);\n } catch (NoSuchElementException ignored) { }\n }\n }\n\n // Check that at least 2 projects are defined\n if (validation.size() < 2) {\n if (validation.size() == 1) ModFusionerPlugin.logger.error(\"Only one project was found. Skipping fusejars task.\");\n if (validation.size() == 0) ModFusionerPlugin.logger.error(\"No projects were found. Skipping fusejars task.\");\n return;\n }\n validation.clear();\n\n // Try to automatically determine the input jar from the projects\n File forgeJar = null;\n File fabricJar = null;\n File quiltJar = null;\n Map<FusionerExtension.CustomConfiguration, File> customJars = new HashMap<>();\n\n if (forgeProject != null && forgeConfiguration != null) {\n forgeJar = getInputFile(forgeConfiguration.getInputFile(), forgeConfiguration.getInputTaskName(), forgeProject);\n }\n\n if (fabricProject != null && fabricConfiguration != null) {\n fabricJar = getInputFile(fabricConfiguration.getInputFile(), fabricConfiguration.getInputTaskName(), fabricProject);\n }\n\n if (quiltProject != null && quiltConfiguration != null) {\n quiltJar = getInputFile(quiltConfiguration.getInputFile(), quiltConfiguration.getInputTaskName(), quiltProject);\n }\n\n for (Map.Entry<Project, FusionerExtension.CustomConfiguration> entry : customProjects.entrySet()) {\n File f = getInputFile(entry.getValue().getInputFile(), entry.getValue().getInputTaskName(), entry.getKey());\n if (f != null)\n customJars.put(entry.getValue(), f);\n }\n\n // Set up the final output jar\n if (mergedJar.exists()) FileUtils.forceDelete(mergedJar);\n if (!mergedJar.getParentFile().exists()) mergedJar.getParentFile().mkdirs();\n\n // Set up the jar merge action\n JarMergeAction mergeAction = JarMergeAction.of(\n customJars,\n modFusionerExtension.getDuplicateRelocations(),\n modFusionerExtension.getPackageGroup(),\n new File(rootProject.getRootDir(), \".gradle\" + File.separator + \"fusioner\"),\n getArchiveFileName().get()\n );\n\n // Forge\n mergeAction.setForgeInput(forgeJar);\n mergeAction.setForgeRelocations(forgeConfiguration == null ? new HashMap<>() : forgeConfiguration.getRelocations());\n mergeAction.setForgeMixins(forgeConfiguration == null ? new ArrayList<>() : forgeConfiguration.getMixins());\n\n // Fabric\n mergeAction.setFabricInput(fabricJar);\n mergeAction.setFabricRelocations(fabricConfiguration == null ? new HashMap<>() : fabricConfiguration.getRelocations());\n\n // Quilt\n mergeAction.setQuiltInput(quiltJar);\n mergeAction.setQuiltRelocations(quiltConfiguration == null ? new HashMap<>() : quiltConfiguration.getRelocations());\n\n // Merge them jars\n Path tempMergedJarPath = mergeAction.mergeJars(false).toPath();\n\n // Move the merged jar to the specified output directory\n Files.move(tempMergedJarPath, mergedJar.toPath(), StandardCopyOption.REPLACE_EXISTING);\n try {\n Files.setPosixFilePermissions(mergedJar.toPath(), Constants.filePerms);\n } catch (UnsupportedOperationException | IOException | SecurityException ignored) { }\n\n // Cleanup\n mergeAction.clean();\n\n ModFusionerPlugin.logger.lifecycle(\"Fused jar created in \" + (System.currentTimeMillis() - time) / 1000.0 + \" seconds.\");\n hasRun.set(true);\n }\n\n /**\n * Run the main task logic and copy the files to the correct locations\n * @return - Just returns true to say the task executed\n */\n @Override\n protected @NotNull CopyAction createCopyAction() {\n return copyActionProcessingStream -> {\n copyActionProcessingStream.process(fileCopyDetailsInternal -> {\n if (!hasRun.get())\n try {\n fuseJars();\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n });\n\n return WorkResults.didWork(true);\n };\n }\n\n /**\n * Try to determine the input jar of a project\n * @param jarLocation - The user defined jar location\n * @param inProject - The project the file should be for or from\n * @return - The jar file or null\n */\n @Nullable\n private File getInputFile(@Nullable String jarLocation, String inputTaskName, Project inProject) {\n if (jarLocation != null && !jarLocation.isEmpty()) {\n return new File(inProject.getProjectDir(), jarLocation);\n } else if (inputTaskName != null && !inputTaskName.isEmpty()) {\n return FileTools.resolveFile(inProject, inputTaskName);\n } else {\n int i = 0;\n for (File file : new File(inProject.getBuildDir(), \"libs\").listFiles()) {\n if (file.isDirectory()) continue;\n if (FileChecks.isZipFile(file)) {\n if (file.getName().length() < i || i == 0) {\n i = file.getName().length();\n return file;\n }\n }\n }\n }\n\n return null;\n }\n}"
}
] | import com.hypherionmc.modfusioner.Constants;
import com.hypherionmc.modfusioner.task.JarFuseTask;
import org.gradle.api.Plugin;
import org.gradle.api.Project;
import org.gradle.api.Task;
import org.gradle.api.logging.Logger;
import org.gradle.api.tasks.TaskProvider;
import org.gradle.api.tasks.bundling.AbstractArchiveTask; | 2,607 | /*
* This file is part of ModFusioner, licensed under the GNU Lesser General Public License v2.1.
*
* This project is based on, and contains code from https://github.com/PacifistMC/Forgix, licensed under the same license.
* See their license here: https://github.com/PacifistMC/Forgix/blob/main/LICENSE
*
* Copyright HypherionSA and Contributors
* Forgix Code Copyright by their contributors and Ran-Mewo
*/
package com.hypherionmc.modfusioner.plugin;
/**
* @author HypherionSA
* Main Gradle Plugin Class
*/
public class ModFusionerPlugin implements Plugin<Project> {
public static Project rootProject;
public static Logger logger;
public static FusionerExtension modFusionerExtension;
@Override
public void apply(Project project) {
// We only want to apply the project to the Root project
if (project != project.getRootProject())
return;
rootProject = project.getRootProject();
logger = project.getLogger();
// Register the extension
modFusionerExtension = rootProject.getExtensions().create(Constants.EXTENSION_NAME, FusionerExtension.class);
// Register the task | /*
* This file is part of ModFusioner, licensed under the GNU Lesser General Public License v2.1.
*
* This project is based on, and contains code from https://github.com/PacifistMC/Forgix, licensed under the same license.
* See their license here: https://github.com/PacifistMC/Forgix/blob/main/LICENSE
*
* Copyright HypherionSA and Contributors
* Forgix Code Copyright by their contributors and Ran-Mewo
*/
package com.hypherionmc.modfusioner.plugin;
/**
* @author HypherionSA
* Main Gradle Plugin Class
*/
public class ModFusionerPlugin implements Plugin<Project> {
public static Project rootProject;
public static Logger logger;
public static FusionerExtension modFusionerExtension;
@Override
public void apply(Project project) {
// We only want to apply the project to the Root project
if (project != project.getRootProject())
return;
rootProject = project.getRootProject();
logger = project.getLogger();
// Register the extension
modFusionerExtension = rootProject.getExtensions().create(Constants.EXTENSION_NAME, FusionerExtension.class);
// Register the task | TaskProvider<JarFuseTask> task = rootProject.getTasks().register(Constants.TASK_NAME, JarFuseTask.class); | 1 | 2023-11-03 23:19:08+00:00 | 4k |
data-harness-cloud/data_harness-be | application-webadmin/src/main/java/supie/webadmin/upms/model/SysRole.java | [
{
"identifier": "BaseModel",
"path": "common/common-core/src/main/java/supie/common/core/base/model/BaseModel.java",
"snippet": "@Data\npublic class BaseModel {\n\n /**\n * 创建者Id。\n */\n @TableField(value = \"create_user_id\")\n private Long createUserId;\n\n /**\n * 创建时间。\n */\n @TableField(value = \"create_time\")\n private Date createTime;\n\n /**\n * 更新者Id。\n */\n @TableField(value = \"update_user_id\")\n private Long updateUserId;\n\n /**\n * 更新时间。\n */\n @TableField(value = \"update_time\")\n private Date updateTime;\n}"
},
{
"identifier": "BaseModelMapper",
"path": "common/common-core/src/main/java/supie/common/core/base/mapper/BaseModelMapper.java",
"snippet": "public interface BaseModelMapper<D, M> {\n\n /**\n * 转换Model实体对象到Domain域对象。\n *\n * @param model Model实体对象。\n * @return Domain域对象。\n */\n D fromModel(M model);\n\n /**\n * 转换Model实体对象列表到Domain域对象列表。\n *\n * @param modelList Model实体对象列表。\n * @return Domain域对象列表。\n */\n List<D> fromModelList(List<M> modelList);\n\n /**\n * 转换Domain域对象到Model实体对象。\n *\n * @param domain Domain域对象。\n * @return Model实体对象。\n */\n M toModel(D domain);\n\n /**\n * 转换Domain域对象列表到Model实体对象列表。\n *\n * @param domainList Domain域对象列表。\n * @return Model实体对象列表。\n */\n List<M> toModelList(List<D> domainList);\n\n /**\n * 转换bean到map\n *\n * @param bean bean对象。\n * @param ignoreNullValue 值为null的字段是否转换到Map。\n * @param <T> bean类型。\n * @return 转换后的map对象。\n */\n default <T> Map<String, Object> beanToMap(T bean, boolean ignoreNullValue) {\n return BeanUtil.beanToMap(bean, false, ignoreNullValue);\n }\n\n /**\n * 转换bean集合到map集合\n *\n * @param dataList bean对象集合。\n * @param ignoreNullValue 值为null的字段是否转换到Map。\n * @param <T> bean类型。\n * @return 转换后的map对象集合。\n */\n default <T> List<Map<String, Object>> beanToMap(List<T> dataList, boolean ignoreNullValue) {\n if (CollUtil.isEmpty(dataList)) {\n return new LinkedList<>();\n }\n return dataList.stream()\n .map(o -> BeanUtil.beanToMap(o, false, ignoreNullValue))\n .collect(Collectors.toList());\n }\n\n /**\n * 转换map到bean。\n *\n * @param map map对象。\n * @param beanClazz bean的Class对象。\n * @param <T> bean类型。\n * @return 转换后的bean对象。\n */\n default <T> T mapToBean(Map<String, Object> map, Class<T> beanClazz) {\n return BeanUtil.toBeanIgnoreError(map, beanClazz);\n }\n\n /**\n * 转换map集合到bean集合。\n *\n * @param mapList map对象集合。\n * @param beanClazz bean的Class对象。\n * @param <T> bean类型。\n * @return 转换后的bean对象集合。\n */\n default <T> List<T> mapToBean(List<Map<String, Object>> mapList, Class<T> beanClazz) {\n if (CollUtil.isEmpty(mapList)) {\n return new LinkedList<>();\n }\n return mapList.stream()\n .map(m -> BeanUtil.toBeanIgnoreError(m, beanClazz))\n .collect(Collectors.toList());\n }\n\n /**\n * 对于Map字段到Map字段的映射场景,MapStruct会根据方法签名自动选择该函数\n * 作为对象copy的函数。由于该函数是直接返回的,因此没有对象copy,效率更高。\n * 如果没有该函数,MapStruct会生成如下代码:\n * Map<String, Object> map = courseDto.getTeacherIdDictMap();\n * if ( map != null ) {\n * course.setTeacherIdDictMap( new HashMap<String, Object>( map ) );\n * }\n *\n * @param map map对象。\n * @return 直接返回的map。\n */\n default Map<String, Object> mapToMap(Map<String, Object> map) {\n return map;\n }\n}"
},
{
"identifier": "SysRoleVo",
"path": "application-webadmin/src/main/java/supie/webadmin/upms/vo/SysRoleVo.java",
"snippet": "@ApiModel(\"角色VO\")\n@Data\n@EqualsAndHashCode(callSuper = true)\npublic class SysRoleVo extends BaseVo {\n\n /**\n * 角色Id。\n */\n @ApiModelProperty(value = \"角色Id\")\n private Long roleId;\n\n /**\n * 角色名称。\n */\n @ApiModelProperty(value = \"角色名称\")\n private String roleName;\n\n /**\n * 角色与菜单关联对象列表。\n */\n @ApiModelProperty(value = \"角色与菜单关联对象列表\")\n private List<Map<String, Object>> sysRoleMenuList;\n}"
}
] | import com.baomidou.mybatisplus.annotation.*;
import supie.common.core.annotation.RelationManyToMany;
import supie.common.core.base.model.BaseModel;
import supie.common.core.base.mapper.BaseModelMapper;
import supie.webadmin.upms.vo.SysRoleVo;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.factory.Mappers;
import java.util.*; | 1,680 | package supie.webadmin.upms.model;
/**
* 角色实体对象。
*
* @author rm -rf .bug
* @date 2020-11-12
*/
@Data
@EqualsAndHashCode(callSuper = true)
@TableName(value = "sdt_sys_role")
public class SysRole extends BaseModel {
/**
* 角色Id。
*/
@TableId(value = "role_id")
private Long roleId;
/**
* 角色名称。
*/
private String roleName;
/**
* 逻辑删除标记字段(1: 正常 -1: 已删除)。
*/
@TableLogic
private Integer deletedFlag;
@RelationManyToMany(
relationMasterIdField = "roleId",
relationModelClass = SysRoleMenu.class)
@TableField(exist = false)
private List<SysRoleMenu> sysRoleMenuList;
@Mapper | package supie.webadmin.upms.model;
/**
* 角色实体对象。
*
* @author rm -rf .bug
* @date 2020-11-12
*/
@Data
@EqualsAndHashCode(callSuper = true)
@TableName(value = "sdt_sys_role")
public class SysRole extends BaseModel {
/**
* 角色Id。
*/
@TableId(value = "role_id")
private Long roleId;
/**
* 角色名称。
*/
private String roleName;
/**
* 逻辑删除标记字段(1: 正常 -1: 已删除)。
*/
@TableLogic
private Integer deletedFlag;
@RelationManyToMany(
relationMasterIdField = "roleId",
relationModelClass = SysRoleMenu.class)
@TableField(exist = false)
private List<SysRoleMenu> sysRoleMenuList;
@Mapper | public interface SysRoleModelMapper extends BaseModelMapper<SysRoleVo, SysRole> { | 2 | 2023-11-04 12:36:44+00:00 | 4k |
FTC-ORBIT/14872-2024-CenterStage | TeamCode/src/main/java/org/firstinspires/ftc/teamcode/robotData/Constants.java | [
{
"identifier": "Angle",
"path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/OrbitUtils/Angle.java",
"snippet": "public final class Angle {\n\n public static final float halfPI = (float) Math.PI / 2;\n public static final float pi = (float) Math.PI;\n public static final float twoPI = (float) Math.PI * 2;\n\n public static float wrapAngle0_2PI(final float theta) {\n return (theta % twoPI + twoPI) % twoPI;\n }\n // convert 0-360 iRadians\n\n public static float wrapAnglePlusMinusPI(final float theta) {\n final float wrapped = theta % twoPI; // Getting the angle smallest form (not exceeding a\n // full turn).\n// convert -180-180 in Radians\n // Adding or subtracting two pi to fit the range of +/- pi.\n if (wrapped > pi) {\n return wrapped - twoPI;\n } else if (wrapped < -pi) {\n return wrapped + twoPI;\n } else {\n return wrapped;\n }\n }\n\n // Functions to convert between degrees and radians:\n public static float degToRad(final float theta) {\n return (float) Math.toRadians(theta);\n } //float\n\n public static float radToDeg(final float theta) {\n return (float) Math.toDegrees(theta);\n } //float\n\n public static float projectBetweenPlanes(final float theta, final float alpha) {\n if (alpha < 0) {\n return (float) Math.atan(Math.tan(theta) / Math.cos(alpha));\n } else {\n return (float) Math.atan(Math.tan(theta) * Math.cos(alpha));\n }\n }\n // alpha is the angle between the planes.\n // For more information check:\n // https://math.stackexchange.com/questions/2207665/projecting-an-angle-from-one-plane-to-another-plane\n}"
},
{
"identifier": "Vector",
"path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/OrbitUtils/Vector.java",
"snippet": "public final class Vector {\n\n public float x;\n public float y;\n\n public Vector(final float x, final float y) {\n this.x = x;\n this.y = y;\n }\n\n public static Vector zero() {\n return new Vector(0, 0);\n } // returns Vector zero\n\n public static Vector INF() {\n return new Vector(Constants.INF, Constants.INF);\n } // returns INF Vector\n\n public float norm() {\n return (float) Math.sqrt(x * x + y * y);\n }\n\n public float getAngle() {\n if (x == 0 && y == 0) {\n return 0;\n } else {\n return (float) Math.atan2(y, x);\n }\n }\n\n public Vector scale(final float scalingFactor) {\n return new Vector(x * scalingFactor, y * scalingFactor);\n }\n\n public Vector unit() {\n if (x == 0 && y == 0) {\n return this;\n } else {\n return scale(1 / norm());\n }\n }\n\n // returns maagal hyehida\n public static Vector unit(final float angle) {\n return new Vector((float) Math.cos(angle), (float) Math.sin(angle));\n }\n\n public static Vector fromAngleAndRadius(final float theta, final float radius) {\n final float vectorX = (float) Math.cos(theta) * radius;\n final float vectorY = (float) Math.sin(theta) * radius;\n return new Vector(vectorX, vectorY);\n }\n\n public float dotProduct(final Vector other) {\n return x * other.x + y * other.y;\n }\n\n public Vector rotate(final float theta) {\n final float sinTheta = (float) Math.sin(theta);\n final float cosTheta = (float) Math.cos(theta);\n\n final float newX = x * cosTheta - y * sinTheta;\n final float newY = x * sinTheta + y * cosTheta;\n\n return new Vector(newX, newY);\n }\n\n public Vector rotate90(final boolean rotateCounterClockwise) {\n if (!rotateCounterClockwise) {\n return new Vector(-y, x);\n } else {\n return new Vector(y, -x);\n }\n }\n\n public Vector abs() {\n return new Vector(Math.abs(x), Math.abs(y));\n }\n\n public Vector add(final Vector other) {\n return new Vector(x + other.x, y + other.y);\n }\n\n public Vector subtract(final Vector other) {\n return new Vector(x - other.x, y - other.y);\n }\n\n public float project(final float angle) {\n final Vector unitVector = unit(angle);\n return dotProduct(unitVector);\n }\n\n public float project(final Vector other) {\n final float otherNorm = other.norm();\n return otherNorm != 0 ? dotProduct(other) / otherNorm : this.norm();\n }\n\n public static Vector longest(final Vector a, final Vector b) {\n return a.norm() > b.norm() ? a : b;\n }\n\n public static Vector shortest(final Vector a, final Vector b) {\n return a.norm() < b.norm() ? a : b;\n }\n\n public static Vector max(final Vector a, final Vector b) {\n return new Vector(Math.max(a.x, b.x), Math.max(a.y, b.y));\n }\n\n public static Vector min(final Vector a, final Vector b) {\n return new Vector(Math.min(a.x, b.x), Math.min(a.y, b.y));\n }\n\n public static Vector sameXY(final float value) {\n return new Vector(value, value);\n }\n\n @Override\n public String toString() {\n return \"x: \" + x + \" y: \" + y;\n }\n\n public boolean equals(final Vector other) {\n return x == other.x && y == other.y;\n }\n\n public static float angleDifference(final Vector a, final Vector b) {\n final float normA = a.norm();\n final float normB = b.norm();\n\n if (normA == 0 || normB == 0)\n return 0;\n\n return (float) Math.acos(a.dotProduct(b) / (normA * normB));\n }\n}"
}
] | import org.firstinspires.ftc.teamcode.OrbitUtils.Angle;
import org.firstinspires.ftc.teamcode.OrbitUtils.Vector; | 1,921 | package org.firstinspires.ftc.teamcode.robotData;
//import org.firstinspires.ftc.teamcode.robotSubSystems.elevator.Elevator;
public class Constants {
public static final float teleopCycleTime = 0.02f; //TODO tune
public static final float INF = 1e5f;
public static final float epsilon = 1e-5f;
public static final float[] redCone = {115, 120, 75};
public static final float[] blueCone = {50, 103, 115};
public static final float colorRange = 25;
public static final float minRotationTranslationRatio = 0.2f;
public static final float robotRadius = 0.2f;
public static final float maxAcc = 1.2f;
public static final float maxVelocity = 1.5f;
private static final float autoDriveStartLinearAcc = 0.6f * maxAcc;
private static final float autoDriveEndLinearAcc = 0.6f * maxAcc;
public static final float maxAutoDriveVel = 0.85f * maxVelocity;
public static final float maxAccOmega = 1f; //TODO tune all maxes
public static final float minHeightToOpenFourbar =500;
private static final float autoDriveStartDOmega = 0.7f * maxAccOmega;
private static final float autoDriveEndDOmega = 0.1f * maxAccOmega; | package org.firstinspires.ftc.teamcode.robotData;
//import org.firstinspires.ftc.teamcode.robotSubSystems.elevator.Elevator;
public class Constants {
public static final float teleopCycleTime = 0.02f; //TODO tune
public static final float INF = 1e5f;
public static final float epsilon = 1e-5f;
public static final float[] redCone = {115, 120, 75};
public static final float[] blueCone = {50, 103, 115};
public static final float colorRange = 25;
public static final float minRotationTranslationRatio = 0.2f;
public static final float robotRadius = 0.2f;
public static final float maxAcc = 1.2f;
public static final float maxVelocity = 1.5f;
private static final float autoDriveStartLinearAcc = 0.6f * maxAcc;
private static final float autoDriveEndLinearAcc = 0.6f * maxAcc;
public static final float maxAutoDriveVel = 0.85f * maxVelocity;
public static final float maxAccOmega = 1f; //TODO tune all maxes
public static final float minHeightToOpenFourbar =500;
private static final float autoDriveStartDOmega = 0.7f * maxAccOmega;
private static final float autoDriveEndDOmega = 0.1f * maxAccOmega; | public static final Vector autoDriveLinearAccMaxPoint = new Vector(1, autoDriveStartLinearAcc); | 1 | 2023-11-03 13:32:48+00:00 | 4k |
beminder/BeautyMinder | java/src/test/java/app/beautyminder/service/cosmetic/CosmeticSearchServiceTest.java | [
{
"identifier": "Cosmetic",
"path": "java/src/main/java/app/beautyminder/domain/Cosmetic.java",
"snippet": "@Document(collection = \"cosmetics\") // mongodb\n@AllArgsConstructor\n@NoArgsConstructor(access = AccessLevel.PROTECTED)\n@Getter\n@Builder\npublic class Cosmetic {\n\n @Id\n private String id;\n\n private String name;\n private String brand;\n\n @Builder.Default\n @Setter\n private List<String> images = new ArrayList<>();\n\n @Setter\n private String thumbnailUrl; // one image\n\n private String glowpick_url;\n\n private LocalDate expirationDate;\n private LocalDateTime createdAt;\n private LocalDate purchasedDate;\n private String category;\n\n @Builder.Default\n private Double averageRating = 0.0; // ex) 3.14\n @Builder.Default\n private int reviewCount = 0;\n @Builder.Default\n private int totalRating = 0;\n @Builder.Default\n private int favCount = 0;\n\n @Builder.Default\n private List<String> keywords = new ArrayList<>();\n\n// @DBRef\n// private User user;\n\n @Builder\n public Cosmetic(String name, String brand, LocalDate expirationDate, LocalDate purchasedDate, String category) {\n this.name = name;\n this.brand = brand;\n this.expirationDate = expirationDate;\n this.purchasedDate = purchasedDate;\n this.category = category;\n this.createdAt = LocalDateTime.now();\n }\n\n public void increaseTotalCount() {\n this.reviewCount++;\n }\n\n public void updateAverageRating(int oldRating, int newRating) {\n this.totalRating = this.totalRating - oldRating + newRating;\n if (this.reviewCount == 0) {\n this.reviewCount = 1; // To handle the case of the first review\n }\n\n // Ensure floating-point division\n this.averageRating = (double) this.totalRating / this.reviewCount;\n this.averageRating = Math.round(this.averageRating * 100.0) / 100.0; // Round to 2 decimal places\n }\n\n\n public void removeRating(int ratingToRemove) {\n this.totalRating -= ratingToRemove;\n this.reviewCount--;\n\n if (this.reviewCount > 0) {\n // Ensure floating-point division\n this.averageRating = (double) this.totalRating / this.reviewCount;\n this.averageRating = Math.round(this.averageRating * 100.0) / 100.0; // Round to 2 decimal places\n } else {\n // Reset averageRating if there are no more reviews\n this.averageRating = 0.0;\n }\n }\n\n public void addImage(String url) {\n this.images.add(url);\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 Cosmetic cosmetic = (Cosmetic) o;\n return Objects.equals(id, cosmetic.id);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(id);\n }\n}"
},
{
"identifier": "Review",
"path": "java/src/main/java/app/beautyminder/domain/Review.java",
"snippet": "@Document(collection = \"reviews\")\n@NoArgsConstructor(access = AccessLevel.PROTECTED)\n@AllArgsConstructor\n@Builder\n@Getter\npublic class Review {\n\n @Id\n private String id;\n\n @Setter\n private String content;\n @Setter\n private Integer rating;\n\n @Builder.Default\n @Setter\n private List<String> images = new ArrayList<>();\n\n @DBRef\n @Indexed\n private User user;\n\n @DBRef\n @Indexed\n private Cosmetic cosmetic;\n\n @CreatedDate\n private LocalDateTime createdAt;\n\n @LastModifiedDate\n private LocalDateTime updatedAt;\n\n @Setter\n @Builder.Default\n// @JsonProperty(\"isFiltered\")\n private boolean isFiltered = false; // Field for offensive content flag, will become \"filtered\" in jsons\n\n // Field for NLP analysis results\n @Setter\n private NlpAnalysis nlpAnalysis;\n\n // Constructor using builder pattern for NlpAnalysis\n @Builder(builderMethodName = \"reviewBuilder\")\n public Review(String content, Integer rating, List<String> images, User user, Cosmetic cosmetic, boolean isFiltered, NlpAnalysis nlpAnalysis) {\n this.content = content;\n this.rating = rating;\n this.images = images;\n this.user = user;\n this.cosmetic = cosmetic;\n this.isFiltered = isFiltered;\n this.nlpAnalysis = nlpAnalysis;\n }\n\n @Builder\n public Review(String content, Integer rating) {\n this.content = content;\n this.rating = rating;\n this.isFiltered = false;\n }\n\n public void update(Review reviewDetails) {\n // Update the fields of this Review instance with the values from reviewDetails\n this.content = reviewDetails.getContent();\n this.rating = reviewDetails.getRating();\n\n // Optionally, might also want to update the images, user, and cosmetic fields\n // if they are part of what can be updated in a review.\n // For images, might want to clear the current list and add all images from reviewDetails,\n // or perhaps just append the new images to the current list.\n this.images.clear();\n this.images.addAll(reviewDetails.getImages());\n\n // For user and cosmetic, simply update the fields if the values in reviewDetails are non-null\n if (reviewDetails.getUser() != null) {\n this.user = reviewDetails.getUser();\n }\n if (reviewDetails.getCosmetic() != null) {\n this.cosmetic = reviewDetails.getCosmetic();\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 Review review = (Review) o;\n return Objects.equals(id, review.id);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(id);\n }\n\n // Inner class to hold NLP analysis results\n// @Getter\n// @Setter\n// @NoArgsConstructor(access = AccessLevel.PROTECTED)\n// @AllArgsConstructor\n// @Builder\n// public static class NlpAnalysis {\n// private double offensivenessProbability;\n//\n// // Change Map to List of Similarity objects\n// @Builder.Default\n// private List<Similarity> similarities = new ArrayList<>();\n//\n// @Getter\n// @Setter\n// @NoArgsConstructor(access = AccessLevel.PROTECTED)\n// @AllArgsConstructor\n// @Builder\n// public static class Similarity {\n// private String key;\n// private Double value;\n// }\n// }\n\n}"
},
{
"identifier": "User",
"path": "java/src/main/java/app/beautyminder/domain/User.java",
"snippet": "@Document(collection = \"users\")\n@NoArgsConstructor(access = AccessLevel.PROTECTED)\n@AllArgsConstructor\n@Getter\npublic class User implements UserDetails {\n\n public static final Integer MAX_HISTORY_SIZE = 10;\n\n @Id\n private String id;\n\n @Indexed(unique = true)\n private String email;\n private String password;\n\n @Setter\n private String nickname;\n @Setter\n private String profileImage;\n @Setter\n private String phoneNumber;\n\n @CreatedDate\n @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = \"yyyy-MM-dd'T'HH:mm:ss.SSS\")\n @JsonDeserialize(using = LocalDateTimeDeserializer.class)\n @JsonSerialize(using = LocalDateTimeSerializer.class)\n private LocalDateTime createdAt;\n\n @LastModifiedDate\n @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = \"yyyy-MM-dd'T'HH:mm:ss.SSS\")\n @JsonDeserialize(using = LocalDateTimeDeserializer.class)\n @JsonSerialize(using = LocalDateTimeSerializer.class)\n private LocalDateTime updatedAt;\n\n @Setter\n @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = \"yyyy-MM-dd'T'HH:mm:ss.SSS\")\n @JsonDeserialize(using = LocalDateTimeDeserializer.class)\n @JsonSerialize(using = LocalDateTimeSerializer.class)\n private LocalDateTime lastLogin;\n\n @JsonDeserialize(using = AuthoritiesDeserializer.class)\n private Set<String> authorities = new HashSet<>();\n\n @Setter\n @Getter\n private Set<String> cosmeticIds = new HashSet<>(); // favourites\n\n @Setter\n @Getter\n private Set<String> keywordHistory = new HashSet<>(); // search history with order\n\n @Indexed\n @Setter\n private String baumann;\n\n @Setter\n private Map<String, Double> baumannScores;\n\n @Builder\n public User(String email, String password, String nickname) {\n this.email = email;\n this.password = password;\n this.nickname = nickname;\n this.authorities = new HashSet<>(Collections.singletonList(\"ROLE_USER\"));\n }\n\n @Builder\n public User(String email, String password, String nickname, String profileImage) {\n this.email = email;\n this.password = password;\n this.nickname = nickname;\n this.profileImage = profileImage;\n this.authorities = new HashSet<>(Collections.singletonList(\"ROLE_USER\"));\n }\n\n @Builder\n public User(String email, String password, String nickname, Set<String> authorities) {\n this.email = email;\n this.password = password;\n this.nickname = nickname;\n this.authorities = authorities;\n }\n\n public User update(String nickname) {\n this.nickname = nickname;\n return this;\n }\n\n @Override\n public Collection<? extends GrantedAuthority> getAuthorities() {\n return authorities.stream()\n .map(SimpleGrantedAuthority::new)\n .collect(Collectors.toList());\n }\n\n public User addCosmetic(String cosmeticId) {\n this.cosmeticIds.add(cosmeticId);\n return this;\n }\n\n public User removeCosmetic(String cosmeticId) {\n this.cosmeticIds.remove(cosmeticId);\n return this;\n }\n\n public void addAuthority(String authority) {\n this.authorities.add(authority);\n }\n\n public void removeAuthority(String authority) {\n this.authorities.remove(authority);\n }\n\n @Override\n public String getUsername() {\n return email;\n }\n\n @Override\n public String getPassword() {\n return password;\n }\n\n public void setPassword(String newPassword) {\n this.password = newPassword;\n }\n\n @Override\n public boolean isAccountNonExpired() {\n return true;\n }\n\n @Override\n public boolean isAccountNonLocked() {\n return true;\n }\n\n @Override\n public boolean isCredentialsNonExpired() {\n return true;\n }\n\n @Override\n public boolean isEnabled() {\n return true;\n }\n\n public Set<Map.Entry<String, Double>> getBaumannScoreEntries() {\n return this.baumannScores != null ? this.baumannScores.entrySet() : Collections.emptySet();\n }\n}"
},
{
"identifier": "CosmeticRepository",
"path": "java/src/main/java/app/beautyminder/repository/CosmeticRepository.java",
"snippet": "public interface CosmeticRepository extends MongoRepository<Cosmetic, String> {\n\n List<Cosmetic> findByCategory(String category);\n\n @Query(\"{'expirationDate': {'$lte': ?0}}\")\n List<Cosmetic> findExpiringSoon(LocalDate date);\n\n List<Cosmetic> findByPurchasedDate(LocalDate purchasedDate);\n\n List<Cosmetic> findByExpirationDate(LocalDate expirationDate);\n\n @NotNull Page<Cosmetic> findAll(@NotNull Pageable pageable);\n}"
},
{
"identifier": "EsCosmeticRepository",
"path": "java/src/main/java/app/beautyminder/repository/elastic/EsCosmeticRepository.java",
"snippet": "@Repository\npublic interface EsCosmeticRepository extends ElasticsearchRepository<EsCosmetic, String> {\n\n List<EsCosmetic> findByNameContaining(String name);\n\n List<EsCosmetic> findByCategory(String category, Pageable pageable);\n\n List<EsCosmetic> findByKeywordsContains(String keyword, Pageable pageable);\n}"
}
] | import app.beautyminder.domain.Cosmetic;
import app.beautyminder.domain.Review;
import app.beautyminder.domain.User;
import app.beautyminder.repository.CosmeticRepository;
import app.beautyminder.repository.elastic.EsCosmeticRepository;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.StatusLine;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.opensearch.client.Request;
import org.opensearch.client.Response;
import org.opensearch.client.RestClient;
import org.opensearch.client.RestHighLevelClient;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyList;
import static org.mockito.Mockito.*; | 3,287 | package app.beautyminder.service.cosmetic;
@Slf4j
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
@ExtendWith(MockitoExtension.class)
public class CosmeticSearchServiceTest {
@Mock
private CosmeticRepository cosmeticRepository;
@Mock
private EsCosmeticRepository esCosmeticRepository;
@Mock
private RestHighLevelClient opensearchClient;
private ObjectMapper objectMapper;
@InjectMocks
private CosmeticSearchService cosmeticSearchService;
| package app.beautyminder.service.cosmetic;
@Slf4j
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
@ExtendWith(MockitoExtension.class)
public class CosmeticSearchServiceTest {
@Mock
private CosmeticRepository cosmeticRepository;
@Mock
private EsCosmeticRepository esCosmeticRepository;
@Mock
private RestHighLevelClient opensearchClient;
private ObjectMapper objectMapper;
@InjectMocks
private CosmeticSearchService cosmeticSearchService;
| private User createUser() { | 2 | 2023-11-01 12:37:16+00:00 | 4k |
hacks1ash/keycloak-spring-boot-adapter | src/main/java/io/github/hacks1ash/keycloak/adapter/KeycloakJWTDecoder.java | [
{
"identifier": "KeycloakUrlHelper",
"path": "src/main/java/io/github/hacks1ash/keycloak/adapter/utils/KeycloakUrlHelper.java",
"snippet": "public class KeycloakUrlHelper {\n\n /**\n * Constructs the URL for a given realm on a Keycloak server.\n *\n * @param serverUrl Base URL of the Keycloak server.\n * @param realm The name of the realm.\n * @return A String representing the URL to the specified realm on the Keycloak server.\n */\n public static String getRealmUrl(String serverUrl, String realm) {\n if (serverUrl.strip().endsWith(\"/\")) return serverUrl + \"realms/\" + realm;\n return serverUrl + \"/realms/\" + realm;\n }\n\n /**\n * Constructs the URL for the certificate endpoint of a given realm on a Keycloak server.\n *\n * @param serverUrl Base URL of the Keycloak server.\n * @param realm The name of the realm.\n * @return A String representing the URL to the certificate endpoint of the specified realm.\n */\n public static String getCertificateUrl(String serverUrl, String realm) {\n return getRealmUrl(serverUrl, realm) + \"/protocol/openid-connect/certs\";\n }\n\n private KeycloakUrlHelper() {\n throw new IllegalStateException(\"KeycloakUrlHelper class\");\n }\n}"
},
{
"identifier": "OAuthUtils",
"path": "src/main/java/io/github/hacks1ash/keycloak/adapter/utils/OAuthUtils.java",
"snippet": "public class OAuthUtils {\n\n private static final Logger log = LoggerFactory.getLogger(OAuthUtils.class);\n\n /**\n * Creates a new {@link OAuth2Error} instance based on the provided reason. This method\n * standardizes the creation of OAuth2 errors for use across the application.\n *\n * @param reason A string describing the reason for the error.\n * @return An {@link OAuth2Error} instance encapsulating the provided reason.\n */\n public static OAuth2Error createOAuth2Error(String reason) {\n log.debug(reason);\n return new OAuth2Error(\n OAuth2ErrorCodes.INVALID_TOKEN, reason, \"https://tools.ietf.org/html/rfc6750#section-3.1\");\n }\n\n private OAuthUtils() {\n throw new IllegalStateException(\"OAuthUtils class\");\n }\n}"
},
{
"identifier": "RemotePublicKeyLocator",
"path": "src/main/java/io/github/hacks1ash/keycloak/adapter/utils/RemotePublicKeyLocator.java",
"snippet": "public class RemotePublicKeyLocator {\n\n private static final Logger log = LoggerFactory.getLogger(RemotePublicKeyLocator.class);\n\n private static final int PUBLIC_KEY_CACHE_TTL = 86400; // 1 Day\n private static final int MIN_TIME_BETWEEN_REQUESTS = 10; // 10 Seconds\n\n private final KeycloakProperties keycloakProperties;\n\n private final RestTemplate restTemplate;\n\n private final Map<String, PublicKey> currentKeys = new ConcurrentHashMap<>();\n\n private volatile int lastRequestTime = 0;\n\n /**\n * Constructs a new instance of RemotePublicKeyLocator.\n *\n * @param keycloakProperties Configuration properties for Keycloak.\n * @param restTemplate RestTemplate for HTTP requests.\n */\n public RemotePublicKeyLocator(KeycloakProperties keycloakProperties, RestTemplate restTemplate) {\n this.keycloakProperties = keycloakProperties;\n this.restTemplate = restTemplate;\n }\n\n /**\n * Retrieves the public key for a given key ID (KID). If the key is not available in the cache, it\n * triggers a request to the Keycloak server to fetch the latest public keys and updates the\n * cache.\n *\n * @param kid Key ID for which the public key is required.\n * @return PublicKey associated with the given KID, or null if not found.\n */\n public PublicKey getPublicKey(String kid) {\n int currentTime = Time.currentTime();\n\n // Check if key is in cache.\n PublicKey publicKey = lookupCachedKey(PUBLIC_KEY_CACHE_TTL, currentTime, kid);\n if (publicKey != null) {\n return publicKey;\n }\n\n // Check if we are allowed to send request\n synchronized (this) {\n currentTime = Time.currentTime();\n if (currentTime > lastRequestTime + MIN_TIME_BETWEEN_REQUESTS) {\n sendRequest();\n lastRequestTime = currentTime;\n } else {\n log.debug(\n String.format(\n \"Won't send request to realm jwks url. Last request time was %d. Current time is %d.\",\n lastRequestTime, currentTime));\n }\n\n return lookupCachedKey(PUBLIC_KEY_CACHE_TTL, currentTime, kid);\n }\n }\n\n /**\n * Resets the cached keys by fetching the latest set from the Keycloak server. This method is\n * useful when there's a need to manually refresh the public keys cache.\n */\n public void reset() {\n synchronized (this) {\n sendRequest();\n lastRequestTime = Time.currentTime();\n log.debug(String.format(\"Reset time offset to %d.\", lastRequestTime));\n }\n }\n\n private PublicKey lookupCachedKey(int publicKeyCacheTtl, int currentTime, String kid) {\n if (lastRequestTime + publicKeyCacheTtl > currentTime && kid != null) {\n return currentKeys.get(kid);\n } else {\n return null;\n }\n }\n\n private void sendRequest() {\n if (log.isTraceEnabled()) {\n log.trace(\n String.format(\n \"Sending request to retrieve realm public keys for client %s\",\n keycloakProperties.getClientId()));\n }\n\n try {\n ResponseEntity<JSONWebKeySet> responseEntity =\n restTemplate.getForEntity(\n KeycloakUrlHelper.getCertificateUrl(\n keycloakProperties.getServerUrl(), keycloakProperties.getRealm()),\n JSONWebKeySet.class);\n JSONWebKeySet jwks = responseEntity.getBody();\n\n if (jwks == null) {\n log.debug(String.format(\"Realm public keys not found %s\", keycloakProperties.getRealm()));\n return;\n }\n\n Map<String, PublicKey> publicKeys =\n JWKSUtils.getKeyWrappersForUse(jwks, JWK.Use.SIG).getKeys().stream()\n .collect(\n Collectors.toMap(\n KeyWrapper::getKid, keyWrapper -> (PublicKey) keyWrapper.getPublicKey()));\n\n if (log.isDebugEnabled()) {\n log.debug(\n String.format(\n \"Realm public keys successfully retrieved for client %s. New kids: %s\",\n keycloakProperties.getClientId(), publicKeys.keySet()));\n }\n\n // Update current keys\n currentKeys.clear();\n currentKeys.putAll(publicKeys);\n\n } catch (RestClientException e) {\n log.error(\"Error when sending request to retrieve realm keys\", e);\n }\n }\n}"
}
] | import static org.keycloak.TokenVerifier.IS_ACTIVE;
import static org.keycloak.TokenVerifier.SUBJECT_EXISTS_CHECK;
import io.github.hacks1ash.keycloak.adapter.utils.KeycloakUrlHelper;
import io.github.hacks1ash.keycloak.adapter.utils.OAuthUtils;
import io.github.hacks1ash.keycloak.adapter.utils.RemotePublicKeyLocator;
import java.security.PublicKey;
import java.time.Instant;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.keycloak.TokenVerifier;
import org.keycloak.common.VerificationException;
import org.keycloak.representations.JsonWebToken;
import org.keycloak.util.TokenUtil;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.jwt.JwtDecoder;
import org.springframework.security.oauth2.jwt.JwtException;
import org.springframework.security.oauth2.jwt.JwtValidationException; | 2,095 | package io.github.hacks1ash.keycloak.adapter;
/**
* A custom implementation of {@link JwtDecoder} for decoding and verifying JWT tokens issued by
* Keycloak.
*/
public class KeycloakJWTDecoder implements JwtDecoder {
private final RemotePublicKeyLocator remotePublicKeyLocator;
private final KeycloakProperties keycloakProperties;
/**
* Constructs a KeycloakJWTDecoder with specified remote public key locator and Keycloak
* properties.
*
* @param remotePublicKeyLocator Locator for public keys.
* @param keycloakProperties Properties configuration for Keycloak.
*/
public KeycloakJWTDecoder(
RemotePublicKeyLocator remotePublicKeyLocator, KeycloakProperties keycloakProperties) {
this.remotePublicKeyLocator = remotePublicKeyLocator;
this.keycloakProperties = keycloakProperties;
}
/**
* Decodes a JWT token to a {@link Jwt} object.
*
* @param token the JWT token string.
* @return a decoded {@link Jwt} object.
* @throws JwtException if the token cannot be decoded or if it's invalid.
*/
@Override
public Jwt decode(String token) throws JwtException {
try {
TokenVerifier<JsonWebToken> tokenVerifier = TokenVerifier.create(token, JsonWebToken.class);
PublicKey publicKey =
remotePublicKeyLocator.getPublicKey(tokenVerifier.getHeader().getKeyId());
tokenVerifier.withChecks(
SUBJECT_EXISTS_CHECK,
new TokenVerifier.TokenTypeCheck(TokenUtil.TOKEN_TYPE_BEARER),
IS_ACTIVE,
new TokenVerifier.RealmUrlCheck( | package io.github.hacks1ash.keycloak.adapter;
/**
* A custom implementation of {@link JwtDecoder} for decoding and verifying JWT tokens issued by
* Keycloak.
*/
public class KeycloakJWTDecoder implements JwtDecoder {
private final RemotePublicKeyLocator remotePublicKeyLocator;
private final KeycloakProperties keycloakProperties;
/**
* Constructs a KeycloakJWTDecoder with specified remote public key locator and Keycloak
* properties.
*
* @param remotePublicKeyLocator Locator for public keys.
* @param keycloakProperties Properties configuration for Keycloak.
*/
public KeycloakJWTDecoder(
RemotePublicKeyLocator remotePublicKeyLocator, KeycloakProperties keycloakProperties) {
this.remotePublicKeyLocator = remotePublicKeyLocator;
this.keycloakProperties = keycloakProperties;
}
/**
* Decodes a JWT token to a {@link Jwt} object.
*
* @param token the JWT token string.
* @return a decoded {@link Jwt} object.
* @throws JwtException if the token cannot be decoded or if it's invalid.
*/
@Override
public Jwt decode(String token) throws JwtException {
try {
TokenVerifier<JsonWebToken> tokenVerifier = TokenVerifier.create(token, JsonWebToken.class);
PublicKey publicKey =
remotePublicKeyLocator.getPublicKey(tokenVerifier.getHeader().getKeyId());
tokenVerifier.withChecks(
SUBJECT_EXISTS_CHECK,
new TokenVerifier.TokenTypeCheck(TokenUtil.TOKEN_TYPE_BEARER),
IS_ACTIVE,
new TokenVerifier.RealmUrlCheck( | KeycloakUrlHelper.getRealmUrl( | 0 | 2023-11-09 09:18:02+00:00 | 4k |
Xrayya/java-cli-pbpu | src/main/java/com/Model/Manager.java | [
{
"identifier": "CashierMachine",
"path": "src/main/java/com/CashierAppUtil/CashierMachine.java",
"snippet": "public class CashierMachine {\n\n private List<Order> orders;\n protected List<Menu> menus;\n\n public CashierMachine() {\n this.menus = new ArrayList<>();\n this.synchronizeMenu();\n this.orders = new ArrayList<>();\n }\n\n /**\n * Print all menu in the record\n */\n public void printMenu() {\n for (Menu menu : this.menus) {\n System.out.println(\"-\".repeat(50));\n System.out.println(menu.toString());\n }\n System.out.println(\"-\".repeat(50));\n }\n\n public List<Menu> getAllMenu() {\n return this.menus;\n }\n\n /**\n * Add new order\n * \n * @param order new order to be added\n */\n public boolean addOrder(Order order) {\n if (checkNull(order)) {\n return false;\n }\n this.orders.add(order);\n return true;\n }\n\n private boolean checkNull(Object o) {\n return o == null;\n }\n\n /**\n * Remove one order\n * \n * @param order order to be removed from the list of orders\n */\n public boolean removeOrder(UUID orderId) {\n if (checkNull(orderId)) {\n return false;\n }\n int findOrder = findOrder(orderId);\n if (findOrder == -1) {\n return false;\n }\n this.orders.remove(findOrder);\n return true;\n }\n\n /**\n * Edit existing order\n * \n * @param orderId orderId from the order that to be edited\n * @param order edited order\n */\n public boolean editOrder(UUID orderId, Order order) {\n int indexFound = findOrder(orderId);\n if (indexFound == -1) {\n return false;\n }\n this.orders.set(indexFound, order);\n return true;\n }\n\n public int findOrder(UUID orderId) {\n for (int i = 0; i < this.orders.size(); i++) {\n if (this.orders.get(i).getOrderId().equals(orderId)) {\n return i;\n }\n }\n return -1;\n }\n\n public List<Order> getUnfinishedOrders() {\n List<Order> orders = new ArrayList<>();\n for (Order order : this.orders) {\n if (!order.isDone()) {\n orders.add(order);\n }\n }\n\n return orders;\n }\n\n public List<Order> getFinishedOrders() {\n List<Order> orders = new ArrayList<>();\n for (Order order : this.orders) {\n if (order.isDone()) {\n orders.add(order);\n }\n }\n\n return orders;\n }\n\n public List<Order> getOrders() {\n return this.orders;\n }\n\n /**\n * Print struct of order\n * \n * @param order order to be printed in struct\n */\n public void printStruct(Order order) {\n // checkNull(order);\n // System.out.printf(\"%-20s %-20s %s\\n\", \"ORDER ID\", \"TABLE NUMBER\", \"TOTAL PRICE\");\n // System.out.printf(\"%-20s %-20s %s\\n\", order.getOrderID(), order.getTableNumber(), order.getTotalPrice());\n // System.out.println(\"====================== ORDERS =======================\");\n // System.out.printf(\"%-20s %-20s %-20s %s\\n\", \"MENU NAME\", \"PRICE\", \"QUANTITY\", \"TOTAL PRICE\");\n // for (MenuOrder mo : order.getMenuOrders()) {\n // System.out.printf(\"%-20s %-20s %s\\n\", mo.getMenu().getMenuName(), mo.getMenu().getPrice(), mo.getQuantity(),\n // mo.getTotalPrice());\n // }\n System.out.println(order.toString());\n }\n\n /**\n * Save the current order list to the record file\n */\n public boolean saveToRecord() {\n Log<Order> orderLog = new Log<>(\"orders\", Order[].class);\n return orderLog.appendRecord(this.orders);\n }\n\n public void synchronizeMenu() {\n this.menus.addAll(new Record<Menu>(\"menus\", Menu[].class).readRecordFile());\n }\n}"
},
{
"identifier": "ManagerMachine",
"path": "src/main/java/com/CashierAppUtil/ManagerMachine.java",
"snippet": "public class ManagerMachine extends CashierMachine {\n\n public List<Order> getOrderRecord() {\n List<Order> orderRecord = new ArrayList<>();\n orderRecord.addAll(new Record<Order>(\"orders\", Order[].class).readRecordFile());\n return orderRecord;\n }\n\n /**\n * Add menu to menu list\n * \n * @param menu menu to be added\n * @return `true` if menu succesfully added or `false` if not\n */\n public boolean addMenu(Menu menu) {\n new Log<Menu>(\"menus\", Menu[].class).appendRecord(menu);\n return this.menus.add(menu);\n }\n\n /**\n * Remove menu from menu list\n * \n * @param menu menu to be removed from the list\n * @return `true` if the specified menu found or `false` if not found\n */\n public boolean removeMenu(String menuShortName) {\n for (Menu menu : menus) {\n if (menu.getMenuShortName().equals(menuShortName)) {\n this.menus.remove(menu);\n new Log<Menu>(\"menus\", Menu[].class).rewriteRecord(this.menus);\n return true;\n }\n }\n\n return false;\n }\n\n /**\n * Edit menu in the menu list\n * \n * @param menuShortName menuId from menu that to be edited\n * @param menu edited menu\n * @return `true` if edit the specified menuId found or `false` if not found\n */\n public boolean editMenu(String menuShortName, Menu menu) {\n for (int i = 0; i < this.menus.size(); i++) {\n if (menuShortName == this.menus.get(i).getMenuShortName()) {\n this.menus.set(i, menu);\n new Log<Menu>(\"menus\", Menu[].class).rewriteRecord(this.menus);\n return true;\n }\n }\n\n return false;\n }\n}"
}
] | import java.util.UUID;
import com.CashierAppUtil.CashierMachine;
import com.CashierAppUtil.ManagerMachine; | 1,623 | package com.Model;
public class Manager extends Employee {
public Manager(UUID employeeID, String name, String username, String password) {
super(employeeID, name, username, password);
}
public Manager(Employee employee) {
super(employee);
}
@Override
public CashierMachine getMachine() { | package com.Model;
public class Manager extends Employee {
public Manager(UUID employeeID, String name, String username, String password) {
super(employeeID, name, username, password);
}
public Manager(Employee employee) {
super(employee);
}
@Override
public CashierMachine getMachine() { | return new ManagerMachine(); | 1 | 2023-11-09 05:26:20+00:00 | 4k |
FallenDeity/GameEngine2DJava | src/main/java/engine/ruby/ImGuiLayer.java | [
{
"identifier": "Picker",
"path": "src/main/java/engine/renderer/Picker.java",
"snippet": "public class Picker {\n\tprivate final int pickFBO;\n\n\tpublic Picker(int w, int h) {\n\t\tpickFBO = glGenFramebuffers();\n\t\tglBindFramebuffer(GL_FRAMEBUFFER, pickFBO);\n\t\tint pickTexID = glGenTextures();\n\t\tglBindTexture(GL_TEXTURE_2D, pickTexID);\n\t\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);\n\t\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);\n\t\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);\n\t\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);\n\t\tglTexImage2D(GL_TEXTURE_2D, 0, GL_RGB32F, w, h, 0, GL_RGB, GL_FLOAT, 0);\n\t\tglFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, pickTexID, 0);\n\t\tglEnable(GL_TEXTURE_2D);\n\t\tint depthTexID = glGenTextures();\n\t\tglBindTexture(GL_TEXTURE_2D, depthTexID);\n\t\tglTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, w, h, 0, GL_DEPTH_COMPONENT, GL_FLOAT, 0);\n\t\tglFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, depthTexID, 0);\n\t\tglReadBuffer(GL_NONE);\n\t\tglDrawBuffer(GL_COLOR_ATTACHMENT0);\n\t\tif (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) {\n\t\t\tassert false : \"ERROR::FRAMEBUFFER:: Framebuffer is not complete!\";\n\t\t\tSystem.err.println(\"ERROR::FRAMEBUFFER:: Framebuffer is not complete!\");\n\t\t} else {\n\t\t\tglBindTexture(GL_TEXTURE_2D, 0);\n\t\t\tglBindFramebuffer(GL_FRAMEBUFFER, 0);\n\t\t}\n\t}\n\n\tpublic void bind() {\n\t\tglBindFramebuffer(GL_FRAMEBUFFER, pickFBO);\n\t}\n\n\tpublic void unbind() {\n\t\tglBindFramebuffer(GL_FRAMEBUFFER, 0);\n\t}\n\n\tpublic int readPixel(int x, int y) {\n\t\tglBindFramebuffer(GL_READ_FRAMEBUFFER, pickFBO);\n\t\tglReadBuffer(GL_COLOR_ATTACHMENT0);\n\t\tfloat[] pixel = new float[3];\n\t\tglReadPixels(x, y, 1, 1, GL_RGB, GL_FLOAT, pixel);\n\t\tglBindFramebuffer(GL_READ_FRAMEBUFFER, 0);\n\t\treturn (int) pixel[0] - 1;\n\t}\n\n\tpublic float[] readPixels(Vector2i start, Vector2i end) {\n\t\tglBindFramebuffer(GL_READ_FRAMEBUFFER, pickFBO);\n\t\tglReadBuffer(GL_COLOR_ATTACHMENT0);\n\t\tVector2i size = new Vector2i(end).sub(start).absolute();\n\t\tfloat[] pixels = new float[size.x * size.y * 3];\n\t\tglReadPixels(start.x, start.y, size.x, size.y, GL_RGB, GL_FLOAT, pixels);\n\t\tglBindFramebuffer(GL_READ_FRAMEBUFFER, 0);\n\t\tfor (int i = 0; i < pixels.length; i++) {\n\t\t\tpixels[i] -= 1;\n\t\t}\n\t\treturn pixels;\n\t}\n}"
},
{
"identifier": "Scene",
"path": "src/main/java/engine/scenes/Scene.java",
"snippet": "public abstract class Scene {\n\tprotected final Renderer renderer = new Renderer();\n\tprotected final List<GameObject> gameObjects = new ArrayList<>();\n\tprotected final Physics2D physics2D;\n\tprotected final Camera camera;\n\tprivate final List<GameObject> pendingGameObjects = new ArrayList<>();\n\tprivate final String storePath = \"%s/scenes\".formatted(CONSTANTS.RESOURCE_PATH.getValue());\n\tprivate boolean isRunning = false;\n\n\tprotected Scene() {\n\t\tload();\n\t\tfor (GameObject g : gameObjects) {\n\t\t\tif (g.getComponent(SpriteRenderer.class) != null) {\n\t\t\t\tSprite sp = g.getComponent(SpriteRenderer.class).getSprite();\n\t\t\t\tif (sp.getTexture() != null) {\n\t\t\t\t\tsp.setTexture(AssetPool.getTexture(sp.getTexture().getFilePath()));\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (g.getComponent(StateMachine.class) != null) {\n\t\t\t\tStateMachine sm = g.getComponent(StateMachine.class);\n\t\t\t\tsm.refresh();\n\t\t\t}\n\t\t}\n\t\tcamera = new Camera(new Vector2f());\n\t\tphysics2D = new Physics2D();\n\t}\n\n\tpublic static GameObject createGameObject(String name) {\n\t\tGameObject gameObject = new GameObject(name);\n\t\tgameObject.addComponent(new Transform());\n\t\tgameObject.transform = gameObject.getComponent(Transform.class);\n\t\treturn gameObject;\n\t}\n\n\tpublic final void start() {\n\t\tif (isRunning) return;\n\t\tisRunning = true;\n\t\tfor (GameObject gameObject : gameObjects) {\n\t\t\tgameObject.start();\n\t\t\trenderer.add(gameObject);\n\t\t\tphysics2D.add(gameObject);\n\t\t}\n\t}\n\n\tpublic final void addGameObjectToScene(GameObject gameObject) {\n\t\tif (isRunning) {\n\t\t\tpendingGameObjects.add(gameObject);\n\t\t} else {\n\t\t\tgameObjects.add(gameObject);\n\t\t}\n\t}\n\n\tpublic final void destroy() {\n\t\tgameObjects.forEach(GameObject::destroy);\n\t}\tprivate String defaultScene = Window.getScene() == null ? \"default\" : Window.getScene().getDefaultScene();\n\n\tpublic void update(float dt) {\n\t\tcamera.adjustProjectionMatrix();\n\t\tphysics2D.update(dt);\n\t\tfor (int i = 0; i < gameObjects.size(); i++) {\n\t\t\tGameObject go = gameObjects.get(i);\n\t\t\tgo.update(dt);\n\t\t\tif (go.isDestroyed()) {\n\t\t\t\tgameObjects.remove(i);\n\t\t\t\trenderer.destroyGameObject(go);\n\t\t\t\tphysics2D.destroyGameObject(go);\n\t\t\t\ti--;\n\t\t\t}\n\t\t}\n\t\tfor (GameObject gameObject : pendingGameObjects) {\n\t\t\tgameObjects.add(gameObject);\n\t\t\tgameObject.start();\n\t\t\trenderer.add(gameObject);\n\t\t\tphysics2D.add(gameObject);\n\t\t}\n\t\tpendingGameObjects.clear();\n\t}\n\n\tpublic void editorUpdate(float dt) {\n\t\tcamera.adjustProjectionMatrix();\n\t\tfor (int i = 0; i < gameObjects.size(); i++) {\n\t\t\tGameObject go = gameObjects.get(i);\n\t\t\tgo.editorUpdate(dt);\n\t\t\tif (go.isDestroyed()) {\n\t\t\t\tgameObjects.remove(i);\n\t\t\t\trenderer.destroyGameObject(go);\n\t\t\t\tphysics2D.destroyGameObject(go);\n\t\t\t\ti--;\n\t\t\t}\n\t\t}\n\t\tfor (GameObject gameObject : pendingGameObjects) {\n\t\t\tgameObjects.add(gameObject);\n\t\t\tgameObject.start();\n\t\t\trenderer.add(gameObject);\n\t\t\tphysics2D.add(gameObject);\n\t\t}\n\t\tpendingGameObjects.clear();\n\t}\n\n\tpublic void render() {\n\t\trenderer.render();\n\t}\n\n\tpublic final Camera getCamera() {\n\t\treturn camera;\n\t}\n\n\tpublic void imGui() {\n\t}\n\n\tpublic GameObject getGameObject(int uid) {\n\t\treturn gameObjects.stream().filter(gameObject -> gameObject.getUid() == uid).findFirst().orElse(null);\n\t}\n\n\tpublic GameObject getGameObject(String name) {\n\t\treturn gameObjects.stream().filter(gameObject -> gameObject.getName().equals(name)).findFirst().orElse(null);\n\t}\n\n\tpublic <T extends Component> GameObject getGameObject(Class<T> componentClass) {\n\t\treturn gameObjects.stream().filter(gameObject -> gameObject.getComponent(componentClass) != null).findFirst().orElse(null);\n\t}\n\n\tpublic List<GameObject> getGameObjects() {\n\t\treturn gameObjects;\n\t}\n\n\tpublic Physics2D getPhysics2D() {\n\t\treturn physics2D;\n\t}\n\n\tpublic String getDefaultScene() {\n\t\treturn defaultScene;\n\t}\n\n\tpublic void setDefaultScene(String defaultScene) {\n\t\tthis.defaultScene = defaultScene;\n\t}\n\n\tpublic final void export() {\n\t\tGsonBuilder gsonb = new GsonBuilder();\n\t\tgsonb.registerTypeAdapter(Component.class, new ComponentDeserializer());\n\t\tgsonb.registerTypeAdapter(GameObject.class, new GameObjectDeserializer());\n\t\tgsonb.enableComplexMapKeySerialization();\n\t\tGson gson = gsonb.setPrettyPrinting().create();\n\t\ttry {\n\t\t\tFiles.createDirectories(Path.of(storePath));\n\t\t\tString path = \"%s/%s.json\".formatted(storePath, defaultScene);\n\t\t\tFileWriter writer = new FileWriter(path);\n\t\t\twriter.write(gson.toJson(gameObjects.stream().filter(GameObject::isSerializable).toArray()));\n\t\t\twriter.close();\n\t\t\tSystem.out.println(\"Exported scene to: \" + path);\n\t\t} catch (IOException e) {\n\t\t\tLogger logger = Logger.getLogger(getClass().getSimpleName());\n\t\t\tlogger.severe(e.getMessage());\n\t\t}\n\t}\n\n\tpublic final void load() {\n\t\tGsonBuilder gsonb = new GsonBuilder();\n\t\tgsonb.registerTypeAdapter(Component.class, new ComponentDeserializer());\n\t\tgsonb.registerTypeAdapter(GameObject.class, new GameObjectDeserializer());\n\t\tgsonb.enableComplexMapKeySerialization();\n\t\tGson gson = gsonb.create();\n\t\ttry {\n\t\t\tString path = \"%s/%s.json\".formatted(storePath, defaultScene);\n\t\t\tString json = Objects.requireNonNull(Files.readString(Path.of(path)));\n\t\t\tint gId = -1, cId = -1;\n\t\t\tGameObject[] gameObjects = gson.fromJson(json, GameObject[].class);\n\t\t\tgId = Stream.of(gameObjects).mapToInt(GameObject::getUid).max().orElse(gId);\n\t\t\tfor (GameObject gameObject : gameObjects) {\n\t\t\t\taddGameObjectToScene(gameObject);\n\t\t\t\tcId = gameObject.getComponents().stream().mapToInt(Component::getUid).max().orElse(cId);\n\t\t\t}\n\t\t\tGameObject.setIdCounter(++gId);\n\t\t\tComponent.setIdCounter(++cId);\n\t\t\tSystem.out.println(\"Loaded scene from: \" + path);\n\t\t} catch (Exception e) {\n\t\t\tLogger logger = Logger.getLogger(getClass().getSimpleName());\n\t\t\tlogger.severe(e.getMessage());\n\t\t}\n\t}\n\n\n\n\n}"
},
{
"identifier": "CONSTANTS",
"path": "src/main/java/engine/util/CONSTANTS.java",
"snippet": "public enum CONSTANTS {\n\tDEBUG(0),\n\tGRID_WIDTH(0.25f),\n\tGRID_HEIGHT(0.25f),\n\tIMGUI_PATH(\"bin/imgui/\"),\n\tRESOURCE_PATH(\"bin/savefiles/\"),\n\tLOGO_PATH(\"assets/images/logo.png\"),\n\tGIZMOS_PATH(\"assets/images/gizmos.png\"),\n\tGAME_FONT_PATH(\"assets/textures/fonts/mario.ttf\"),\n\tFONT_PATH(\"assets/textures/fonts/segoeui.ttf\"),\n\tSOUNDS_PATH(\"assets/sounds/\"),\n\tTURTLE_SHEET_PATH(\"assets/textures/sprites/turtle.png\"),\n\tPIPES_SHEET_PATH(\"assets/textures/sprites/pipes.png\"),\n\tPOWER_SHEET_PATH(\"assets/textures/sprites/power_sprites.png\"),\n\tITEM_SHEET_PATH(\"assets/textures/sprites/items.png\"),\n\tBLOCK_SHEET_PATH(\"assets/textures/sprites/blocks.png\"),\n\tSPRITE_SHEET_PATH(\"assets/textures/sprites/spritesheet.png\"),\n\tFONT_SHADER_PATH(\"assets/shaders/font.glsl\"),\n\tPICKER_SHADER_PATH(\"assets/shaders/picker.glsl\"),\n\tDEFAULT_SHADER_PATH(\"assets/shaders/default.glsl\"),\n\tLINE2D_SHADER_PATH(\"assets/shaders/line2d.glsl\");\n\n\tprivate final String value;\n\tprivate final float intValue;\n\n\tCONSTANTS(float intValue) {\n\t\tthis.intValue = intValue;\n\t\tthis.value = String.valueOf(intValue);\n\t}\n\n\tCONSTANTS(String value) {\n\t\tthis.value = value;\n\t\tthis.intValue = 0;\n\t}\n\n\tpublic String getValue() {\n\t\treturn value;\n\t}\n\n\tpublic float getIntValue() {\n\t\treturn intValue;\n\t}\n}"
}
] | import engine.editor.*;
import engine.renderer.Picker;
import engine.scenes.Scene;
import engine.util.CONSTANTS;
import imgui.*;
import imgui.callback.ImStrConsumer;
import imgui.callback.ImStrSupplier;
import imgui.flag.*;
import imgui.gl3.ImGuiImplGl3;
import imgui.glfw.ImGuiImplGlfw;
import imgui.type.ImBoolean;
import org.lwjgl.glfw.GLFWErrorCallback;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import static org.lwjgl.glfw.GLFW.*;
import static org.lwjgl.opengl.GL11.*;
import static org.lwjgl.opengl.GL30.GL_FRAMEBUFFER;
import static org.lwjgl.opengl.GL30C.glBindFramebuffer; | 2,923 | package engine.ruby;
public class ImGuiLayer {
private final static GameViewWindow gameViewWindow = new GameViewWindow();
private final long windowId;
private final ImGuiImplGl3 imGuiGl3 = new ImGuiImplGl3();
private final ImGuiImplGlfw imGuiGlfw = new ImGuiImplGlfw();
private final PropertiesWindow propertiesWindow;
| package engine.ruby;
public class ImGuiLayer {
private final static GameViewWindow gameViewWindow = new GameViewWindow();
private final long windowId;
private final ImGuiImplGl3 imGuiGl3 = new ImGuiImplGl3();
private final ImGuiImplGlfw imGuiGlfw = new ImGuiImplGlfw();
private final PropertiesWindow propertiesWindow;
| public ImGuiLayer(long windowId, Picker picker) { | 0 | 2023-11-04 13:19:21+00:00 | 4k |
RezaGooner/University-food-ordering | Frames/Admin/FoodManagment/OrderCounter.java | [
{
"identifier": "CustomRendererOrderCount",
"path": "Classes/Theme/CustomRendererOrderCount.java",
"snippet": "public class CustomRendererOrderCount extends DefaultTableCellRenderer {\r\n private static final long serialVersionUID = 1L;\r\n\r\n @Override\r\n public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {\r\n Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);\r\n\r\n Object columnValue = table.getValueAt(row, 1);\r\n\r\n if (columnValue != null && columnValue.equals(\"مجموع\")) {\r\n c.setBackground(Color.darkGray);\r\n c.setForeground(Color.white);\r\n } else {\r\n c.setBackground(Color.white);\r\n c.setForeground(Color.BLACK);\r\n }\r\n\r\n return c;\r\n }\r\n}"
},
{
"identifier": "OrdersPath",
"path": "Classes/Pathes/FilesPath.java",
"snippet": "public static String OrdersPath = \"orders.txt\";\r"
},
{
"identifier": "icon",
"path": "Classes/Pathes/FilesPath.java",
"snippet": "public static ImageIcon icon = new ImageIcon(\"Source/icon.png\");\r"
}
] | import Classes.Theme.CustomRendererOrderCount;
import java.awt.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;
import javax.swing.*;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import static Classes.Pathes.FilesPath.OrdersPath;
import static Classes.Pathes.FilesPath.icon;
| 1,668 | package Frames.Admin.FoodManagment;
/*
این کد یک پنجره برای نمایش آمار سفارشات غذا به صورت روزانه دارد.
در این پنجره، کاربر میتواند برای هر روز مجموع تعداد سفارشات ناهار و شام را مشاهده کند.
این پنجره شامل دو تب "ناهار" و "شام" است که هر تب یک جدول دارد که شامل نام غذا و تعداد سفارشات آن است.
در پایین هر جدول، یک JComboBox برای انتخاب تاریخ مورد نظر کاربر قرار دارد.
همچنین، برای هر جدول یک دکمه "شمارش" وجود دارد که با فشردن آن،
تعداد سفارشات آن روز محاسبه میشود و در جدول نمایش داده میشود.
`````````````````````````````````````````````````````
This code defines an `OrderCounter` class that extends `JFrame` and is used to create a GUI application for
counting food orders. Here's a breakdown of the code:
- The `OrderCounter` constructor sets up the main components of the GUI. It sets the title and icon of the application
window, sets the size and location, and makes the window non-resizable.
- Two tabbed panels, one for lunch orders and one for dinner orders, are created using `JPanel` with a `BorderLayout`.
- Buttons for counting lunch and dinner orders are created and registered with action listeners to handle button click
events. When clicked, these buttons invoke the `countLunch` and `countDinner` methods, respectively.
- The lunch and dinner tables are created using `JTable` and `DefaultTableModel`.
The table models are used to manage the data in the tables.
- Two combo boxes, `lunchComboBox` and `dinnerComboBox`, are created to display the available dates for lunch and
dinner orders.
- The `populateComboBoxes` method reads the orders file and populates the combo boxes with unique dates.
- The `countLunch` and `countDinner` methods read the orders file, count the number of orders for each food item on
the selected date, and update the lunch and dinner tables accordingly. They also calculate the total number of
orders and display it in a separate row at the bottom of each table.
- The `highlightSum` method is used to highlight the total row in the tables by setting a different background color.
- The `setVisible(true)` method is called to display the GUI.
note that there are some dependencies in the code, such as `Classes.Theme.CustomRendererOrderCount`, `Classes.Pathes.
FilesPath.OrdersPath`, and `Classes.Pathes.FilesPath.icon`.
You need to ensure that these dependencies are properly resolved and that the necessary files exist for the code to work
correctly.
*/
public class OrderCounter extends JFrame {
private HashMap<String, Integer> lunchCounts = new HashMap<>();
private HashMap<String, Integer> dinnerCounts = new HashMap<>();
private DefaultTableModel lunchTableModel = new DefaultTableModel();
private DefaultTableModel dinnerTableModel = new DefaultTableModel();
private JTable lunchTable = new JTable(lunchTableModel);
private JTable dinnerTable = new JTable(dinnerTableModel);
private JComboBox<String> lunchComboBox = new JComboBox<>();
private JComboBox<String> dinnerComboBox = new JComboBox<>();
private DefaultTableCellRenderer totalRenderer = new DefaultTableCellRenderer();
public OrderCounter() {
setTitle("آمار سفارشات");
setIconImage(icon.getImage());
setSize(600, 400);
setLocationRelativeTo(null);
setResizable(false);
JTabbedPane tabbedPane = new JTabbedPane();
JPanel lunchPanel = new JPanel(new BorderLayout());
JPanel dinnerPanel = new JPanel(new BorderLayout());
JButton lunchButton = new JButton("شمارش ناهار");
lunchButton.addActionListener(e -> {
try {
countLunch();
} catch (FileNotFoundException ex) {
}
});
lunchPanel.add(lunchButton, BorderLayout.NORTH);
lunchTableModel.addColumn("غذا");
lunchTableModel.addColumn("تعداد");
lunchPanel.add(new JScrollPane(lunchTable), BorderLayout.CENTER);
JButton dinnerButton = new JButton("شمارش شام");
dinnerButton.addActionListener(e -> {
try {
countDinner();
} catch (FileNotFoundException ex) {
}
});
dinnerPanel.add(dinnerButton, BorderLayout.NORTH);
dinnerTableModel.addColumn("غذا");
dinnerTableModel.addColumn("تعداد");
dinnerPanel.add(new JScrollPane(dinnerTable), BorderLayout.CENTER);
try {
populateComboBoxes();
} catch (FileNotFoundException ex) {
}
// اضافه کردن دو JComboBox به UI
JPanel lunchDatePanel = new JPanel(new GridLayout(2, 2));
lunchDatePanel.add(new JLabel("تاریخ"));
lunchDatePanel.add(lunchComboBox);
lunchPanel.add(lunchDatePanel, BorderLayout.SOUTH);
JPanel dinnerDatePanel = new JPanel(new GridLayout(2, 2));
dinnerDatePanel.add(new JLabel("تاریخ"));
dinnerDatePanel.add(dinnerComboBox);
dinnerPanel.add(dinnerDatePanel, BorderLayout.SOUTH);
tabbedPane.addTab("ناهار", lunchPanel);
tabbedPane.addTab("شام", dinnerPanel);
add(tabbedPane);
setVisible(true);
}
private void countLunch() throws FileNotFoundException {
lunchTable.setDefaultRenderer(Object.class, new CustomRendererOrderCount());
String selectedDate = (String) lunchComboBox.getSelectedItem();
lunchCounts.clear();
| package Frames.Admin.FoodManagment;
/*
این کد یک پنجره برای نمایش آمار سفارشات غذا به صورت روزانه دارد.
در این پنجره، کاربر میتواند برای هر روز مجموع تعداد سفارشات ناهار و شام را مشاهده کند.
این پنجره شامل دو تب "ناهار" و "شام" است که هر تب یک جدول دارد که شامل نام غذا و تعداد سفارشات آن است.
در پایین هر جدول، یک JComboBox برای انتخاب تاریخ مورد نظر کاربر قرار دارد.
همچنین، برای هر جدول یک دکمه "شمارش" وجود دارد که با فشردن آن،
تعداد سفارشات آن روز محاسبه میشود و در جدول نمایش داده میشود.
`````````````````````````````````````````````````````
This code defines an `OrderCounter` class that extends `JFrame` and is used to create a GUI application for
counting food orders. Here's a breakdown of the code:
- The `OrderCounter` constructor sets up the main components of the GUI. It sets the title and icon of the application
window, sets the size and location, and makes the window non-resizable.
- Two tabbed panels, one for lunch orders and one for dinner orders, are created using `JPanel` with a `BorderLayout`.
- Buttons for counting lunch and dinner orders are created and registered with action listeners to handle button click
events. When clicked, these buttons invoke the `countLunch` and `countDinner` methods, respectively.
- The lunch and dinner tables are created using `JTable` and `DefaultTableModel`.
The table models are used to manage the data in the tables.
- Two combo boxes, `lunchComboBox` and `dinnerComboBox`, are created to display the available dates for lunch and
dinner orders.
- The `populateComboBoxes` method reads the orders file and populates the combo boxes with unique dates.
- The `countLunch` and `countDinner` methods read the orders file, count the number of orders for each food item on
the selected date, and update the lunch and dinner tables accordingly. They also calculate the total number of
orders and display it in a separate row at the bottom of each table.
- The `highlightSum` method is used to highlight the total row in the tables by setting a different background color.
- The `setVisible(true)` method is called to display the GUI.
note that there are some dependencies in the code, such as `Classes.Theme.CustomRendererOrderCount`, `Classes.Pathes.
FilesPath.OrdersPath`, and `Classes.Pathes.FilesPath.icon`.
You need to ensure that these dependencies are properly resolved and that the necessary files exist for the code to work
correctly.
*/
public class OrderCounter extends JFrame {
private HashMap<String, Integer> lunchCounts = new HashMap<>();
private HashMap<String, Integer> dinnerCounts = new HashMap<>();
private DefaultTableModel lunchTableModel = new DefaultTableModel();
private DefaultTableModel dinnerTableModel = new DefaultTableModel();
private JTable lunchTable = new JTable(lunchTableModel);
private JTable dinnerTable = new JTable(dinnerTableModel);
private JComboBox<String> lunchComboBox = new JComboBox<>();
private JComboBox<String> dinnerComboBox = new JComboBox<>();
private DefaultTableCellRenderer totalRenderer = new DefaultTableCellRenderer();
public OrderCounter() {
setTitle("آمار سفارشات");
setIconImage(icon.getImage());
setSize(600, 400);
setLocationRelativeTo(null);
setResizable(false);
JTabbedPane tabbedPane = new JTabbedPane();
JPanel lunchPanel = new JPanel(new BorderLayout());
JPanel dinnerPanel = new JPanel(new BorderLayout());
JButton lunchButton = new JButton("شمارش ناهار");
lunchButton.addActionListener(e -> {
try {
countLunch();
} catch (FileNotFoundException ex) {
}
});
lunchPanel.add(lunchButton, BorderLayout.NORTH);
lunchTableModel.addColumn("غذا");
lunchTableModel.addColumn("تعداد");
lunchPanel.add(new JScrollPane(lunchTable), BorderLayout.CENTER);
JButton dinnerButton = new JButton("شمارش شام");
dinnerButton.addActionListener(e -> {
try {
countDinner();
} catch (FileNotFoundException ex) {
}
});
dinnerPanel.add(dinnerButton, BorderLayout.NORTH);
dinnerTableModel.addColumn("غذا");
dinnerTableModel.addColumn("تعداد");
dinnerPanel.add(new JScrollPane(dinnerTable), BorderLayout.CENTER);
try {
populateComboBoxes();
} catch (FileNotFoundException ex) {
}
// اضافه کردن دو JComboBox به UI
JPanel lunchDatePanel = new JPanel(new GridLayout(2, 2));
lunchDatePanel.add(new JLabel("تاریخ"));
lunchDatePanel.add(lunchComboBox);
lunchPanel.add(lunchDatePanel, BorderLayout.SOUTH);
JPanel dinnerDatePanel = new JPanel(new GridLayout(2, 2));
dinnerDatePanel.add(new JLabel("تاریخ"));
dinnerDatePanel.add(dinnerComboBox);
dinnerPanel.add(dinnerDatePanel, BorderLayout.SOUTH);
tabbedPane.addTab("ناهار", lunchPanel);
tabbedPane.addTab("شام", dinnerPanel);
add(tabbedPane);
setVisible(true);
}
private void countLunch() throws FileNotFoundException {
lunchTable.setDefaultRenderer(Object.class, new CustomRendererOrderCount());
String selectedDate = (String) lunchComboBox.getSelectedItem();
lunchCounts.clear();
| File ordersFile = new File(OrdersPath);
| 1 | 2023-11-03 08:35:22+00:00 | 4k |
Celant/PlaytimeSchedule | src/main/java/uk/co/celant/playtimeschedule/PlaytimeSchedule.java | [
{
"identifier": "IPlaytimeCapability",
"path": "src/main/java/uk/co/celant/playtimeschedule/capabilities/IPlaytimeCapability.java",
"snippet": "public interface IPlaytimeCapability extends INBTSerializable<CompoundTag> {\r\n int getPlaytime();\r\n int getPlaytimeLeft();\r\n String getPlaytimeLeftString();\r\n void incrementPlaytime(boolean save);\r\n void resetPlaytime();\r\n boolean dayHasChanged();\r\n boolean getInFreePlay();\r\n void setInFreePlay(boolean value);\r\n void copy(IPlaytimeCapability playtimeCapability);\r\n}\r"
},
{
"identifier": "PlaytimeCapability",
"path": "src/main/java/uk/co/celant/playtimeschedule/capabilities/PlaytimeCapability.java",
"snippet": "public class PlaytimeCapability implements IPlaytimeCapability {\r\n private int curPlaytime = 0;\r\n private long dayMillis = System.currentTimeMillis();\r\n private long lastCheckMillis = System.currentTimeMillis();\r\n private boolean inFreePlay = false;\r\n\r\n @Override\r\n public int getPlaytime() {\r\n return this.curPlaytime;\r\n }\r\n\r\n @Override\r\n public int getPlaytimeLeft() {\r\n if (PlaytimeSchedule.CONFIG.dailyPlaytimeLimit.get() == -1) return -1;\r\n return Math.max(PlaytimeSchedule.CONFIG.dailyPlaytimeLimit.get() - getPlaytime(), 0);\r\n }\r\n\r\n @Override\r\n public String getPlaytimeLeftString() {\r\n int left = this.getPlaytimeLeft();\r\n\r\n String seconds = new DecimalFormat(\"00\").format(Duration.ofSeconds(left).toSecondsPart());\r\n String minutes = new DecimalFormat(\"00\").format(Duration.ofSeconds(left).toMinutesPart());\r\n String hours = new DecimalFormat(\"00\").format(Duration.ofSeconds(left).toHoursPart());\r\n return ChatFormatting.GREEN + \"You have \"\r\n + ChatFormatting.RED + hours + ChatFormatting.GREEN + \" hours, \"\r\n + ChatFormatting.RED + minutes + ChatFormatting.GREEN + \" minutes and \"\r\n + ChatFormatting.RED + seconds + ChatFormatting.GREEN + \" seconds left\";\r\n }\r\n\r\n @Override\r\n public void incrementPlaytime(boolean save) {\r\n if (save) {\r\n this.curPlaytime = this.curPlaytime + deltaTime();\r\n }\r\n this.lastCheckMillis = System.currentTimeMillis();\r\n }\r\n\r\n @Override\r\n public void resetPlaytime() {\r\n this.dayMillis = System.currentTimeMillis();\r\n this.curPlaytime = 0;\r\n }\r\n\r\n @Override\r\n public boolean dayHasChanged() {\r\n long newDayMillis = System.currentTimeMillis();\r\n\r\n Calendar cal = Calendar.getInstance();\r\n cal.setTimeInMillis(this.dayMillis);\r\n int oldDay = cal.get(Calendar.DAY_OF_MONTH);\r\n\r\n cal.setTimeInMillis(newDayMillis);\r\n int newDay = cal.get(Calendar.DAY_OF_MONTH);\r\n\r\n return oldDay != newDay;\r\n }\r\n\r\n @Override\r\n public boolean getInFreePlay() {\r\n return this.inFreePlay;\r\n }\r\n\r\n @Override\r\n public void setInFreePlay(boolean value) {\r\n this.inFreePlay = value;\r\n }\r\n\r\n @Override\r\n public void copy(IPlaytimeCapability playtimeCapability) {\r\n this.curPlaytime = playtimeCapability.getPlaytime();\r\n this.inFreePlay = playtimeCapability.getInFreePlay();\r\n }\r\n\r\n private int deltaTime() {\r\n long newCheckMillis = System.currentTimeMillis();\r\n long diff = newCheckMillis - this.lastCheckMillis;\r\n return Math.round(diff / 1000f);\r\n }\r\n\r\n @Override\r\n public CompoundTag serializeNBT() {\r\n final CompoundTag tag = new CompoundTag();\r\n tag.putInt(\"curPlaytime\", this.curPlaytime);\r\n tag.putLong(\"dayMillis\", this.dayMillis);\r\n return tag;\r\n }\r\n\r\n @Override\r\n public void deserializeNBT(CompoundTag nbt) {\r\n\r\n this.curPlaytime = nbt.getInt(\"curPlaytime\");\r\n this.dayMillis = nbt.getLong(\"dayMillis\");\r\n }\r\n}\r"
},
{
"identifier": "PlaytimeCapabilityProvider",
"path": "src/main/java/uk/co/celant/playtimeschedule/capabilities/PlaytimeCapabilityProvider.java",
"snippet": "public class PlaytimeCapabilityProvider implements ICapabilitySerializable<CompoundTag> {\r\n public static final ResourceLocation IDENTIFIER = new ResourceLocation(PlaytimeSchedule.MODID, \"playtime_capability\");\r\n\r\n private final IPlaytimeCapability backend = new PlaytimeCapability();\r\n private final LazyOptional<IPlaytimeCapability> playtimeCapabilityLazyOptional = LazyOptional.of(() -> backend);\r\n\r\n @Override\r\n public <T> @NotNull LazyOptional<T> getCapability(@NotNull Capability<T> cap, @Nullable Direction side) {\r\n return PlaytimeSchedule.PLAYTIME.orEmpty(cap, this.playtimeCapabilityLazyOptional);\r\n }\r\n\r\n void invalidate() {\r\n this.playtimeCapabilityLazyOptional.invalidate();\r\n }\r\n\r\n @Override\r\n public CompoundTag serializeNBT() {\r\n return backend.serializeNBT();\r\n }\r\n\r\n @Override\r\n public void deserializeNBT(CompoundTag nbt) {\r\n backend.deserializeNBT(nbt);\r\n }\r\n}\r"
},
{
"identifier": "PlaytimeScheduleConfig",
"path": "src/main/java/uk/co/celant/playtimeschedule/config/PlaytimeScheduleConfig.java",
"snippet": "public class PlaytimeScheduleConfig extends ConfigBase {\r\n protected ForgeConfigSpec configSpec;\r\n\r\n public final ForgeConfigSpec.IntValue dailyPlaytimeLimit;\r\n public final ForgeConfigSpec.BooleanValue freePlayOpBypass;\r\n public final ForgeConfigSpec.BooleanValue freePlayCreativeBypass;\r\n public final Map<Integer, List<Schedule>> freePlaySchedules = new HashMap<>();\r\n\r\n private final Map<Integer, ForgeConfigSpec.ConfigValue<List<? extends String>>> freePlayScheduleStrings = new HashMap<>();\r\n\r\n private static final Splitter DOT_SPLITTER = Splitter.on(\".\");\r\n private static final Logger LOGGER = LogUtils.getLogger();\r\n\r\n public PlaytimeScheduleConfig(ForgeConfigSpec.Builder builder) {\r\n super(builder);\r\n\r\n dailyPlaytimeLimit = builder\r\n .comment(\"The time (in seconds) per day that a player can play (-1 = unlimited).\")\r\n .defineInRange(\"playtime.limit.daily\", 2 * 60 * 60, -1, Integer.MAX_VALUE);\r\n\r\n freePlayOpBypass = builder\r\n .comment(\"Whether ops should always be in free play mode.\")\r\n .define(\"playtime.freeplay.opBypass\", false);\r\n freePlayCreativeBypass = builder\r\n .comment(\"Whether players in Creative Mode should always be in free play mode.\")\r\n .define(\"playtime.freeplay.creativeBypass\", true);\r\n\r\n builder.comment(\r\n \"Allows you to define 'free play' schedules, during which playtime limits are paused.\",\r\n \"Schedules must be formatted as pairs of ISO8601 times separated by '-'.\",\r\n \"Multiple schedules can be defined per day, but 'start' cannot be after 'end'.\",\r\n \"\",\r\n \"For example:\",\r\n \"[\\\"00:00:00-01:00:00\\\",\\\"17:00:00-23:59:59\\\"]\"\r\n ).push(\"playtime.schedule\");\r\n\r\n freePlayScheduleStrings.put(Calendar.MONDAY, builder\r\n .defineListAllowEmpty(\r\n split(\"monday\"),\r\n ArrayList::new,\r\n validSchedule()\r\n ));\r\n freePlayScheduleStrings.put(Calendar.TUESDAY, builder\r\n .defineListAllowEmpty(\r\n split(\"tuesday\"),\r\n ArrayList::new,\r\n validSchedule()\r\n ));\r\n freePlayScheduleStrings.put(Calendar.WEDNESDAY, builder\r\n .defineListAllowEmpty(\r\n split(\"wednesday\"),\r\n ArrayList::new,\r\n validSchedule()\r\n ));\r\n freePlayScheduleStrings.put(Calendar.THURSDAY, builder\r\n .defineListAllowEmpty(\r\n split(\"thursday\"),\r\n ArrayList::new,\r\n validSchedule()\r\n ));\r\n freePlayScheduleStrings.put(Calendar.FRIDAY, builder\r\n .defineListAllowEmpty(\r\n split(\"friday\"),\r\n ArrayList::new,\r\n validSchedule()\r\n ));\r\n freePlayScheduleStrings.put(Calendar.SATURDAY, builder\r\n .defineListAllowEmpty(\r\n split(\"saturday\"),\r\n ArrayList::new,\r\n validSchedule()\r\n ));\r\n freePlayScheduleStrings.put(Calendar.SUNDAY, builder\r\n .defineListAllowEmpty(\r\n split(\"sunday\"),\r\n ArrayList::new,\r\n validSchedule()\r\n ));\r\n }\r\n\r\n @Override\r\n public void onReload(ModConfigEvent event) {\r\n super.onReload(event);\r\n\r\n Map<Integer, List<Schedule>> newMap = new HashMap<>();\r\n freePlayScheduleStrings.forEach((day, list) -> {\r\n List<Schedule> newList = new ArrayList<>();\r\n list.get().forEach((string) -> {\r\n try {\r\n newList.add(new Schedule(string));\r\n } catch (ScheduleParseException e) {\r\n throw new RuntimeException(e);\r\n }\r\n });\r\n newMap.put(day, newList);\r\n });\r\n freePlaySchedules.putAll(newMap);\r\n }\r\n\r\n private Predicate<Object> validSchedule() {\r\n return s -> {\r\n try {\r\n new Schedule(s.toString());\r\n return true;\r\n } catch (ScheduleParseException e) {\r\n throw new RuntimeException(e);\r\n }\r\n };\r\n }\r\n private static List<String> split(String path)\r\n {\r\n return Lists.newArrayList(DOT_SPLITTER.split(path));\r\n }\r\n}\r"
}
] | import com.mojang.logging.LogUtils;
import net.minecraft.network.chat.Component;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.player.Player;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.capabilities.CapabilityManager;
import net.minecraftforge.common.capabilities.CapabilityToken;
import net.minecraftforge.common.capabilities.RegisterCapabilitiesEvent;
import net.minecraftforge.common.util.LazyOptional;
import net.minecraftforge.event.AttachCapabilitiesEvent;
import net.minecraftforge.event.entity.player.PlayerEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.config.ModConfig;
import net.minecraftforge.server.permission.PermissionAPI;
import org.slf4j.Logger;
import uk.co.celant.playtimeschedule.capabilities.IPlaytimeCapability;
import uk.co.celant.playtimeschedule.capabilities.PlaytimeCapability;
import uk.co.celant.playtimeschedule.capabilities.PlaytimeCapabilityProvider;
import uk.co.celant.playtimeschedule.config.PlaytimeScheduleConfig; | 2,508 | package uk.co.celant.playtimeschedule;
// The value here should match an entry in the META-INF/mods.toml file
@Mod(PlaytimeSchedule.MODID)
public class PlaytimeSchedule
{
// Define mod id in a common place for everything to reference
public static final String MODID = "playtimeschedule";
public static final Capability<IPlaytimeCapability> PLAYTIME = CapabilityManager.get(new CapabilityToken<>(){});
// Directly reference a slf4j logger
private static final Logger LOGGER = LogUtils.getLogger();
private static final Events EVENTS = new Events();
| package uk.co.celant.playtimeschedule;
// The value here should match an entry in the META-INF/mods.toml file
@Mod(PlaytimeSchedule.MODID)
public class PlaytimeSchedule
{
// Define mod id in a common place for everything to reference
public static final String MODID = "playtimeschedule";
public static final Capability<IPlaytimeCapability> PLAYTIME = CapabilityManager.get(new CapabilityToken<>(){});
// Directly reference a slf4j logger
private static final Logger LOGGER = LogUtils.getLogger();
private static final Events EVENTS = new Events();
| public static PlaytimeScheduleConfig CONFIG; | 3 | 2023-11-02 12:52:02+00:00 | 4k |
EaindrayFromEarth/Collaborative_Blog_Version_Control_Management-System | java/com/we_write/service/UserService.java | [
{
"identifier": "User",
"path": "java/com/we_write/entity/User.java",
"snippet": "@Entity\r\n@Getter\r\n@Setter\r\n@NoArgsConstructor\r\n@AllArgsConstructor\r\npublic class User implements UserDetails {\r\n\r\n /**\r\n\t * \r\n\t */\r\n\tprivate static final long serialVersionUID = 1L;\r\n\r\n\t@Id\r\n @GeneratedValue(strategy = GenerationType.IDENTITY)\r\n private Long id;\r\n\r\n private String username;\r\n private String password;\r\n private String email;\r\n private boolean accountNonExpired;\r\n private boolean accountNonLocked;\r\n private boolean credentialsNonExpired;\r\n private boolean enabled;\r\n\r\n// // Define user roles/authorities here\r\n// @ManyToMany(fetch = FetchType.EAGER)\r\n// @JoinTable(\r\n// name = \"user_roles\",\r\n// joinColumns = @JoinColumn(name = \"user_id\"),\r\n// inverseJoinColumns = @JoinColumn(name = \"role_id\")\r\n// )\r\n// private Collection<Role> roles;\r\n//\r\n// @ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)\r\n// @JoinTable(name = \"users_roles\",\r\n// joinColumns = @JoinColumn(name = \"user_id\", referencedColumnName = \"id\"),\r\n// inverseJoinColumns = @JoinColumn(name = \"role_id\", referencedColumnName = \"id\")\r\n// )\r\n// private Set<Role> role;\r\n\r\n // Constructors, getters, and setters\r\n\r\n @ManyToMany(fetch = FetchType.EAGER)\r\n @JoinTable(\r\n name = \"user_roles\",\r\n joinColumns = @JoinColumn(name = \"user_id\"),\r\n inverseJoinColumns = @JoinColumn(name = \"role_id\")\r\n )\r\n private Set<Role> roles = new HashSet<>();\r\n\r\n \r\n @Override\r\n public Collection<? extends GrantedAuthority> getAuthorities() {\r\n // Return a collection of user roles/authorities\r\n Collection<GrantedAuthority> authorities = new HashSet<>();\r\n for (Role role : roles) {\r\n authorities.add(new SimpleGrantedAuthority(role.getName()));\r\n }\r\n return authorities;\r\n }\r\n \r\n public Long getId() {\r\n \treturn id;\r\n }\r\n \r\n @Override\r\n public String getPassword() {\r\n // Return the user's password\r\n return password;\r\n }\r\n \r\n\r\n @Override\r\n public String getUsername() {\r\n // Return the user's username\r\n return username;\r\n }\r\n\r\n @Override\r\n public boolean isAccountNonExpired() {\r\n // Implement account expiration logic\r\n return accountNonExpired;\r\n }\r\n\r\n @Override\r\n public boolean isAccountNonLocked() {\r\n // Implement account locking logic\r\n return accountNonLocked;\r\n }\r\n\r\n @Override\r\n public boolean isCredentialsNonExpired() {\r\n // Implement credentials expiration logic\r\n return credentialsNonExpired;\r\n }\r\n\r\n @Override\r\n public boolean isEnabled() {\r\n // Implement user activation status\r\n return enabled;\r\n }\r\n\r\n\r\n\r\n\r\n @OneToMany(mappedBy = \"createdBy\", cascade = CascadeType.ALL, orphanRemoval = true)\r\n private List<Blog> blogs = new ArrayList<>();\r\n\r\n}"
},
{
"identifier": "EmailAlreadyExistsException",
"path": "java/com/we_write/exception/EmailAlreadyExistsException.java",
"snippet": "public class EmailAlreadyExistsException extends RuntimeException {\r\n /**\r\n\t * \r\n\t */\r\n\tprivate static final long serialVersionUID = 1L;\r\n\r\n\tpublic EmailAlreadyExistsException(String message) {\r\n super(message);\r\n }\r\n}\r"
},
{
"identifier": "ResourceNotFoundException",
"path": "java/com/we_write/exception/ResourceNotFoundException.java",
"snippet": "public class ResourceNotFoundException extends RuntimeException {\r\n\r\n /**\r\n\t * \r\n\t */\r\n\tprivate static final long serialVersionUID = 1L;\r\n\r\n\tpublic ResourceNotFoundException(String message) {\r\n super(message);\r\n }\r\n\r\n public ResourceNotFoundException(String message, Throwable cause) {\r\n super(message, cause);\r\n }\r\n}\r"
},
{
"identifier": "UsernameAlreadyExistsException",
"path": "java/com/we_write/exception/UsernameAlreadyExistsException.java",
"snippet": "public class UsernameAlreadyExistsException extends RuntimeException {\r\n /**\r\n\t * \r\n\t */\r\n\tprivate static final long serialVersionUID = 1L;\r\n\r\n\tpublic UsernameAlreadyExistsException(String message) {\r\n super(message);\r\n }\r\n}"
},
{
"identifier": "JWTAuthResponseDto",
"path": "java/com/we_write/payload/JWTAuthResponseDto.java",
"snippet": "@Setter\r\n@Getter\r\n@NoArgsConstructor\r\n@AllArgsConstructor\r\npublic class JWTAuthResponseDto {\r\n private String accessToken;\r\n private String tokenType = \"Bearer\";\r\n \r\n public JWTAuthResponseDto(String accessToken) {\r\n this.accessToken = accessToken;\r\n }\r\n}"
},
{
"identifier": "UserDto",
"path": "java/com/we_write/payload/UserDto.java",
"snippet": "@Data\r\n@Table(name = \"users\")\r\n@Schema(\r\n description = \"User Information Dto\"\r\n)\r\npublic class UserDto {\r\n @NotEmpty(message = \"Username is required\")\r\n @Size(min = 3, max = 50, message = \"Username must be between 3 and 50 characters\")\r\n private String username;\r\n\r\n @NotEmpty(message = \"Email is required\")\r\n @Email(message = \"Invalid email format\")\r\n private String email;\r\n\r\n @NotEmpty(message = \"Password is required\")\r\n @Size(min = 6, message = \"Password must be at least 6 characters\")\r\n private String password;\r\n\r\n\r\n}\r"
},
{
"identifier": "RoleRepository",
"path": "java/com/we_write/repository/RoleRepository.java",
"snippet": "public interface RoleRepository extends JpaRepository<Role, Long> {\r\n Optional<Role> findByName(String name);\r\n}"
},
{
"identifier": "UserRepository",
"path": "java/com/we_write/repository/UserRepository.java",
"snippet": "@Repository\r\npublic interface UserRepository extends JpaRepository<User, Long> {\r\n\r\n Optional<User> findByEmail(String email);\r\n\r\n Optional<User> findByUsernameOrEmail(String username, String email);\r\n\r\n Optional<User> findByUsername(User createdBy);\r\n\r\n Boolean existsByUsername(String username);\r\n\r\n Boolean existsByEmail(String email);\r\n\r\n\tOptional<User> findByUsername(String createdBy);\r\n}"
},
{
"identifier": "JwtTokenProvider",
"path": "java/com/we_write/security/JwtTokenProvider.java",
"snippet": "@Component\r\npublic class JwtTokenProvider {\r\n\r\n @Value(\"${app.jwt-secret}\")\r\n private String jwtSecret;\r\n\r\n @Value(\"${app-jwt-expiration-milliseconds}\")\r\n private long jwtExpirationDate;\r\n\r\n // generate JWT token\r\n public String generateToken(Authentication authentication){\r\n String username = authentication.getName();\r\n\r\n Date currentDate = new Date();\r\n\r\n Date expireDate = new Date(currentDate.getTime() + jwtExpirationDate);\r\n\r\n String token = Jwts.builder()\r\n .setSubject(username)\r\n .setIssuedAt(new Date())\r\n .setExpiration(expireDate)\r\n .signWith(key())\r\n .compact();\r\n return token;\r\n }\r\n\r\n private Key key(){\r\n return Keys.hmacShaKeyFor(\r\n Decoders.BASE64.decode(jwtSecret)\r\n );\r\n }\r\n\r\n // get username from Jwt token\r\n public String getUsername(String token){\r\n Claims claims = Jwts.parserBuilder()\r\n .setSigningKey(key())\r\n .build()\r\n .parseClaimsJws(token)\r\n .getBody();\r\n String username = claims.getSubject();\r\n return username;\r\n }\r\n\r\n // validate Jwt token\r\n public boolean validateToken(String token){\r\n try{\r\n Jwts.parserBuilder()\r\n .setSigningKey(key())\r\n .build()\r\n .parse(token);\r\n return true;\r\n } catch (MalformedJwtException ex) {\r\n throw new BlogAPIException(HttpStatus.BAD_REQUEST, \"Invalid JWT token\");\r\n } catch (ExpiredJwtException ex) {\r\n throw new BlogAPIException(HttpStatus.BAD_REQUEST, \"Expired JWT token\");\r\n } catch (UnsupportedJwtException ex) {\r\n throw new BlogAPIException(HttpStatus.BAD_REQUEST, \"Unsupported JWT token\");\r\n } catch (IllegalArgumentException ex) {\r\n throw new BlogAPIException(HttpStatus.BAD_REQUEST, \"JWT claims string is empty.\");\r\n }\r\n }\r\n\r\n\r\n}"
}
] | import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import com.we_write.entity.User;
import com.we_write.exception.EmailAlreadyExistsException;
import com.we_write.exception.ResourceNotFoundException;
import com.we_write.exception.UsernameAlreadyExistsException;
import com.we_write.payload.JWTAuthResponseDto;
import com.we_write.payload.UserDto;
import com.we_write.repository.RoleRepository;
import com.we_write.repository.UserRepository;
import com.we_write.security.JwtTokenProvider;
| 2,521 | package com.we_write.service;
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
private RoleRepository roleRepository;
@Autowired
private PasswordEncoder passwordEncoder;
@Autowired
private JwtTokenProvider jwtTokenProvider;
public User registerUser(UserDto userDto) {
// Check if the username or email already exists
if (userRepository.existsByUsername(userDto.getUsername())) {
throw new UsernameAlreadyExistsException("Username is already taken!");
}
if (userRepository.existsByEmail(userDto.getEmail())) {
throw new EmailAlreadyExistsException("Email is already registered!");
}
// Create a new user entity and set properties
User user = new User();
user.setUsername(userDto.getUsername());
user.setEmail(userDto.getEmail());
user.setPassword(userDto.getPassword());
// Set user roles/authorities as needed
// Save the user entity to the database
return userRepository.save(user);
}
public String loginUser(UserDto loginRequest) {
// Authenticate the user using Spring Security
Authentication authentication = authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword())
);
// If authentication is successful, generate a JWT token
SecurityContextHolder.getContext().setAuthentication(authentication);
return jwtTokenProvider.generateToken(authentication);
}
// Update loginUser to return JWTAuthResponseDto
public JWTAuthResponseDto authenticateUser(UserDto loginRequest) {
// Authenticate the user using Spring Security
Authentication authentication = authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword())
);
// If authentication is successful, generate a JWT token
SecurityContextHolder.getContext().setAuthentication(authentication);
String token = jwtTokenProvider.generateToken(authentication);
// Return JWTAuthResponseDto
return new JWTAuthResponseDto(token);
}
public User getUserByUsername(User createdBy) {
// Use the UserRepository to find a user by their username
User user = userRepository.findByUsername(createdBy)
.orElseThrow(() -> new UsernameNotFoundException("User not found with username: " + createdBy));
return user;
}
public User getUserByUsername(String createdBy) {
// Use the UserRepository to find a user by their username
User user = userRepository.findByUsername(createdBy)
.orElseThrow(() -> new UsernameNotFoundException("User not found with username: " + createdBy));
return user;
}
public List<User> getAllUsers() {
return userRepository.findAll();
}
public User getUserById(Long id) {
return userRepository.findById(id)
| package com.we_write.service;
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
private RoleRepository roleRepository;
@Autowired
private PasswordEncoder passwordEncoder;
@Autowired
private JwtTokenProvider jwtTokenProvider;
public User registerUser(UserDto userDto) {
// Check if the username or email already exists
if (userRepository.existsByUsername(userDto.getUsername())) {
throw new UsernameAlreadyExistsException("Username is already taken!");
}
if (userRepository.existsByEmail(userDto.getEmail())) {
throw new EmailAlreadyExistsException("Email is already registered!");
}
// Create a new user entity and set properties
User user = new User();
user.setUsername(userDto.getUsername());
user.setEmail(userDto.getEmail());
user.setPassword(userDto.getPassword());
// Set user roles/authorities as needed
// Save the user entity to the database
return userRepository.save(user);
}
public String loginUser(UserDto loginRequest) {
// Authenticate the user using Spring Security
Authentication authentication = authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword())
);
// If authentication is successful, generate a JWT token
SecurityContextHolder.getContext().setAuthentication(authentication);
return jwtTokenProvider.generateToken(authentication);
}
// Update loginUser to return JWTAuthResponseDto
public JWTAuthResponseDto authenticateUser(UserDto loginRequest) {
// Authenticate the user using Spring Security
Authentication authentication = authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword())
);
// If authentication is successful, generate a JWT token
SecurityContextHolder.getContext().setAuthentication(authentication);
String token = jwtTokenProvider.generateToken(authentication);
// Return JWTAuthResponseDto
return new JWTAuthResponseDto(token);
}
public User getUserByUsername(User createdBy) {
// Use the UserRepository to find a user by their username
User user = userRepository.findByUsername(createdBy)
.orElseThrow(() -> new UsernameNotFoundException("User not found with username: " + createdBy));
return user;
}
public User getUserByUsername(String createdBy) {
// Use the UserRepository to find a user by their username
User user = userRepository.findByUsername(createdBy)
.orElseThrow(() -> new UsernameNotFoundException("User not found with username: " + createdBy));
return user;
}
public List<User> getAllUsers() {
return userRepository.findAll();
}
public User getUserById(Long id) {
return userRepository.findById(id)
| .orElseThrow(() -> new ResourceNotFoundException("User not found with ID: " + id));
| 2 | 2023-11-05 05:44:23+00:00 | 4k |
antoKeinanen/Serverselector | src/main/java/dev/antok/serverselector/inventory/JoinInventory.java | [
{
"identifier": "Serverselector",
"path": "src/main/java/dev/antok/serverselector/Serverselector.java",
"snippet": "public final class Serverselector extends JavaPlugin {\n public HashMap<Player, Integer> joiningPlayers = new HashMap<>();\n\n @Override\n public void onEnable() {\n Logger logger = getLogger();\n\n final Serverselector instance = this;\n\n Config.ConfigFile configFile = new ConfigManager(this).configFile;\n MiniMessage mm = MiniMessage.miniMessage();\n\n final ServerStarter serverStarter = new ServerStarter(logger, configFile);\n final JoinInventory joinInventory = new JoinInventory(logger, serverStarter, this, configFile);\n\n this.getServer().getPluginManager().registerEvents(joinInventory, this);\n this.getCommand(\"join\").setExecutor(new JoinCommand(logger, joinInventory, configFile));\n this.getServer().getMessenger().registerOutgoingPluginChannel(this, \"BungeeCord\");\n\n Bukkit.getScheduler().scheduleSyncRepeatingTask(this, () -> {\n HashMap<Integer, Boolean> statusCache = new HashMap<>();\n for (Player player : joiningPlayers.keySet()) {\n final Integer serverId = joiningPlayers.get(player);\n\n Config.Item server = configFile.server.stream().filter(item -> item.serverId == serverId).findFirst().orElse(null);\n if (server == null) {\n player.sendMessage(configFile.messages.noSuchServer);\n logger.severe(String.format(\"No server with id %d found\", serverId));\n joiningPlayers.remove(player);\n continue;\n }\n\n if (statusCache.containsKey(serverId)) {\n if (statusCache.get(serverId)) {\n joiningPlayers.remove(player);\n SendPlayerToServer.sendPlayerToServer(player, server.serverName, instance);\n } else {\n player.sendMessage(configFile.messages.waitingForServer);\n continue;\n }\n }\n\n try {\n boolean status = serverStarter.getServerStatus(serverId);\n statusCache.put(serverId, status);\n\n if (status) {\n joiningPlayers.remove(player);\n if (server.serverName == null) {\n player.sendMessage(configFile.messages.noSuchServer);\n continue;\n }\n SendPlayerToServer.sendPlayerToServer(player, server.serverName, instance);\n } else {\n player.sendMessage(configFile.messages.waitingForServer);\n }\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n\n\n }\n }, configFile.pingTime, configFile.pingTime);\n }\n\n @Override\n public void onDisable() {\n // Plugin shutdown logic\n }\n}"
},
{
"identifier": "Config",
"path": "src/main/java/dev/antok/serverselector/config/Config.java",
"snippet": "public class Config {\n public Item createItem(String name, int slot, String material, List<String> lore, int serverId, String serverName) {\n return new Item(name, slot, material, lore, serverId, serverName);\n }\n\n public Messages createMessages(String notAPlayer, String noSuchServer, String sendingToServer,\n String startingServer, String waitingForServer, String serverStartError) {\n return new Messages(notAPlayer, noSuchServer, sendingToServer, startingServer, waitingForServer,\n serverStartError);\n }\n\n public ConfigFile createConfigFile(int inventorySize, String inventoryName, String panelUrl, int pingTime,\n String username, String password, List<Item> servers, Messages messages) {\n return new ConfigFile(inventorySize, inventoryName, panelUrl, pingTime, username, password, servers, messages);\n }\n\n public class ConfigFile {\n public int inventorySize;\n public String inventoryName;\n public String panelUrl;\n public int pingTime;\n public String username;\n public String password;\n public List<Item> server;\n public Messages messages;\n\n\n public ConfigFile(int inventorySize, String inventoryName, String panelUrl, int pingTime, String username,\n String password, List<Item> server, Messages messages) {\n this.inventorySize = inventorySize;\n this.inventoryName = inventoryName;\n this.panelUrl = panelUrl;\n this.pingTime = pingTime;\n this.username = username;\n this.password = password;\n this.server = server;\n this.messages = messages;\n }\n\n public boolean isValid() throws IllegalAccessException {\n if (this.inventoryName == null || this.panelUrl == null || this.username == null || this.password == null || this.server == null || this.messages == null)\n return false;\n return this.inventorySize % 9 == 0 && this.inventorySize < 57 && (this.panelUrl.startsWith(\"http://\") || this.panelUrl.startsWith(\"https://\")) && !this.panelUrl.endsWith(\"/\");\n }\n\n }\n\n public class Item {\n public String name;\n public int slot;\n public String material;\n public List<String> lore;\n public int serverId;\n public String serverName;\n\n public Item(String name, int slot, String material, List<String> lore, int serverId, String serverName) {\n this.name = name;\n this.slot = slot;\n this.material = material;\n this.lore = lore;\n this.serverId = serverId;\n this.serverName = serverName;\n }\n\n boolean isValid() throws IllegalAccessException {\n if (this.slot > 55) return false;\n return this.name != null && this.material != null && this.lore != null && this.serverName != null;\n }\n }\n\n public class Messages {\n public String notAPlayer;\n public String noSuchServer;\n public String sendingToServer;\n public String startingServer;\n public String waitingForServer;\n public String serverStartError;\n\n public Messages(String notAPlayer, String noSuchServer, String sendingToServer, String startingServer,\n String waitingForServer, String serverStartError) {\n this.notAPlayer = notAPlayer;\n this.noSuchServer = noSuchServer;\n this.sendingToServer = sendingToServer;\n this.startingServer = startingServer;\n this.waitingForServer = waitingForServer;\n this.serverStartError = serverStartError;\n }\n\n boolean isValid() throws IllegalAccessException {\n return (this.notAPlayer != null || this.noSuchServer != null || this.sendingToServer != null || this.startingServer != null || this.waitingForServer != null || this.serverStartError != null);\n }\n }\n}"
},
{
"identifier": "SendPlayerToServer",
"path": "src/main/java/dev/antok/serverselector/util/SendPlayerToServer.java",
"snippet": "public class SendPlayerToServer {\n public static void sendPlayerToServer(Player player, String server, Serverselector instance) {\n ByteArrayOutputStream b = new ByteArrayOutputStream();\n DataOutputStream out = new DataOutputStream(b);\n\n try {\n out.writeUTF(\"Connect\");\n out.writeUTF(server);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n\n player.sendPluginMessage(instance, \"BungeeCord\", b.toByteArray());\n }\n}"
},
{
"identifier": "ServerStarter",
"path": "src/main/java/dev/antok/serverselector/util/ServerStarter.java",
"snippet": "public class ServerStarter {\n private static final TrustManager MOCK_TRUST_MANAGER = new X509TrustManager() {\n @Override\n public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {\n }\n\n @Override\n public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {\n }\n\n @Override\n public X509Certificate[] getAcceptedIssuers() {\n return new X509Certificate[0];\n }\n };\n\n final Logger logger;\n Config.ConfigFile configFile;\n private String token;\n\n\n public ServerStarter(Logger logger, Config.ConfigFile configFile) {\n this.logger = logger;\n this.configFile = configFile;\n\n try {\n authenticate();\n } catch (ExecutionException | InterruptedException | NoSuchAlgorithmException | KeyManagementException |\n ParseException e) {\n logger.severe(e.getMessage());\n }\n }\n\n private void authenticate() throws ExecutionException, InterruptedException, NoSuchAlgorithmException, KeyManagementException, ParseException {\n SSLContext sslContext = SSLContext.getInstance(\"SSL\");\n sslContext.init(null, new TrustManager[]{MOCK_TRUST_MANAGER}, new SecureRandom());\n HttpClient client = HttpClient.newBuilder().sslContext(sslContext).build();\n\n JSONObject requestBody = new JSONObject();\n requestBody.put(\"username\", configFile.username);\n requestBody.put(\"password\", configFile.password);\n\n HttpRequest request = HttpRequest.newBuilder().uri(URI.create(configFile.panelUrl + \"/api/v2/auth/login\")).POST(HttpRequest.BodyPublishers.ofString(requestBody.toJSONString())).build();\n\n CompletableFuture<HttpResponse<String>> futureResponse = client.sendAsync(request, HttpResponse.BodyHandlers.ofString());\n HttpResponse<String> response = futureResponse.get();\n\n\n if (response.statusCode() != 200) {\n logger.severe(\"Failed to authenticate: \");\n logger.severe(response.toString());\n logger.severe(response.body());\n return;\n }\n\n JSONObject responseObject = (JSONObject) new JSONParser().parse(response.body());\n JSONObject responseData = (JSONObject) responseObject.get(\"data\");\n String token = (String) responseData.get(\"token\");\n\n if (token == null) {\n logger.severe(\"Failed to get token\");\n } else {\n this.token = token;\n }\n }\n\n public void requestServerStart(int serverId) throws NoSuchAlgorithmException, KeyManagementException, ExecutionException, InterruptedException {\n SSLContext sslContext = SSLContext.getInstance(\"SSL\");\n sslContext.init(null, new TrustManager[]{MOCK_TRUST_MANAGER}, new SecureRandom());\n HttpClient client = HttpClient.newBuilder().sslContext(sslContext).build();\n\n HttpRequest request = HttpRequest.newBuilder().uri(URI.create(String.format(configFile.panelUrl + \"/api/v2/servers/%d/action/start_server\", serverId))).header(\"Authorization\", \"Bearer \" + this.token).POST(HttpRequest.BodyPublishers.noBody()).build();\n\n CompletableFuture<HttpResponse<String>> futureResponse = client.sendAsync(request, HttpResponse.BodyHandlers.ofString());\n HttpResponse<String> response = futureResponse.get();\n\n\n if (response.statusCode() != 200) {\n logger.severe(\"Failed to request server start: \");\n logger.severe(response.toString());\n return;\n }\n\n logger.info(\"Ok \" + response.body());\n }\n\n public boolean getServerStatus(int serverID) throws Exception {\n SSLContext sslContext = SSLContext.getInstance(\"SSL\");\n sslContext.init(null, new TrustManager[]{MOCK_TRUST_MANAGER}, new SecureRandom());\n HttpClient client = HttpClient.newBuilder().sslContext(sslContext).build();\n\n HttpRequest request = HttpRequest.newBuilder().uri(URI.create(configFile.panelUrl + \"/api/v2/servers/\" + serverID + \"/stats\")).header(\"Authorization\", \"Bearer \" + this.token).GET().build();\n\n CompletableFuture<HttpResponse<String>> futureResponse = client.sendAsync(request, HttpResponse.BodyHandlers.ofString());\n HttpResponse<String> response = futureResponse.get();\n\n\n if (response.statusCode() != 200) {\n throw new Exception(String.format(\"Failed to get status of server '%d' error code '%d'\", serverID, response.statusCode()));\n }\n\n JSONObject responseObject = (JSONObject) new JSONParser().parse(response.body());\n JSONObject responseData = (JSONObject) responseObject.get(\"data\");\n return !responseData.get(\"players\").equals(\"False\");\n }\n}"
}
] | import dev.antok.serverselector.Serverselector;
import dev.antok.serverselector.config.Config;
import dev.antok.serverselector.util.SendPlayerToServer;
import dev.antok.serverselector.util.ServerStarter;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.minimessage.MiniMessage;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.entity.HumanEntity;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.inventory.InventoryDragEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.json.simple.parser.ParseException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.logging.Logger;
import java.util.stream.Stream; | 2,915 | package dev.antok.serverselector.inventory;
public class JoinInventory implements Listener {
private final Inventory inventory;
private final Logger logger;
private final ServerStarter serverStarter; | package dev.antok.serverselector.inventory;
public class JoinInventory implements Listener {
private final Inventory inventory;
private final Logger logger;
private final ServerStarter serverStarter; | private final Serverselector main; | 0 | 2023-11-09 14:38:55+00:00 | 4k |
af19git5/EasyImage | src/main/java/io/github/af19git5/entity/Image.java | [
{
"identifier": "ImageException",
"path": "src/main/java/io/github/af19git5/exception/ImageException.java",
"snippet": "public class ImageException extends Exception {\n\n public ImageException(String message) {\n super(message);\n }\n\n public ImageException(Exception e) {\n super(e);\n }\n}"
},
{
"identifier": "PositionX",
"path": "src/main/java/io/github/af19git5/type/PositionX.java",
"snippet": "@Getter\npublic enum PositionX {\n\n /** 無指定位置 */\n NONE,\n\n /** 置左 */\n LEFT,\n\n /** 置中 */\n MIDDLE,\n\n /** 置右 */\n RIGHT\n}"
},
{
"identifier": "PositionY",
"path": "src/main/java/io/github/af19git5/type/PositionY.java",
"snippet": "@Getter\npublic enum PositionY {\n\n /** 無指定位置 */\n NONE,\n\n /** 置頂 */\n TOP,\n\n /** 置中 */\n MIDDLE,\n\n /** 置底 */\n BOTTOM\n}"
}
] | import io.github.af19git5.exception.ImageException;
import io.github.af19git5.type.PositionX;
import io.github.af19git5.type.PositionY;
import lombok.Getter;
import lombok.NonNull;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import javax.imageio.ImageIO; | 2,583 | @NonNull PositionX positionX,
int y,
@NonNull File file,
int overrideWidth,
int overrideHeight)
throws ImageException {
if (overrideWidth <= 0 || overrideHeight <= 0) {
throw new ImageException(
"overrideWidth and overrideHeight cannot be less than or equal to 0");
}
this.setPositionX(positionX);
this.setY(y);
this.overrideWidth = overrideWidth;
this.overrideHeight = overrideHeight;
try {
bufferedImage = ImageIO.read(file);
} catch (IOException e) {
throw new ImageException(e);
}
}
/**
* @param positionX 放置x軸位置
* @param y 放置y軸位置
* @param path 圖片檔案路徑
* @throws ImageException 圖檔讀取錯誤
*/
public Image(@NonNull PositionX positionX, int y, @NonNull String path) throws ImageException {
this.setPositionX(positionX);
this.setY(y);
try {
bufferedImage = ImageIO.read(new File(path));
} catch (IOException e) {
throw new ImageException(e);
}
}
/**
* @param positionX 放置x軸位置
* @param y 放置y軸位置
* @param path 圖片檔案路徑
* @param overrideWidth 覆寫寬度
* @param overrideHeight 覆寫高度
* @throws ImageException 圖檔讀取錯誤
*/
public Image(
@NonNull PositionX positionX,
int y,
@NonNull String path,
int overrideWidth,
int overrideHeight)
throws ImageException {
if (overrideWidth <= 0 || overrideHeight <= 0) {
throw new ImageException(
"overrideWidth and overrideHeight cannot be less than or equal to 0");
}
this.setPositionX(positionX);
this.setY(y);
this.overrideWidth = overrideWidth;
this.overrideHeight = overrideHeight;
try {
bufferedImage = ImageIO.read(new File(path));
} catch (IOException e) {
throw new ImageException(e);
}
}
/**
* @param positionX 放置x軸位置
* @param y 放置y軸位置
* @param inputStream 資料流
* @throws ImageException 圖檔讀取錯誤
*/
public Image(@NonNull PositionX positionX, int y, @NonNull InputStream inputStream)
throws ImageException {
this.setPositionX(positionX);
this.setY(y);
try {
bufferedImage = ImageIO.read(inputStream);
} catch (IOException e) {
throw new ImageException(e);
}
}
/**
* @param positionX 放置x軸位置
* @param y 放置y軸位置
* @param inputStream 資料流
* @param overrideWidth 覆寫寬度
* @param overrideHeight 覆寫高度
* @throws ImageException 圖檔讀取錯誤
*/
public Image(
@NonNull PositionX positionX,
int y,
@NonNull InputStream inputStream,
int overrideWidth,
int overrideHeight)
throws ImageException {
if (overrideWidth <= 0 || overrideHeight <= 0) {
throw new ImageException(
"overrideWidth and overrideHeight cannot be less than or equal to 0");
}
this.setPositionX(positionX);
this.setY(y);
this.overrideWidth = overrideWidth;
this.overrideHeight = overrideHeight;
try {
bufferedImage = ImageIO.read(inputStream);
} catch (IOException e) {
throw new ImageException(e);
}
}
/**
* @param x 放置x軸位置
* @param positionY 放置y軸位置
* @param file 圖片檔案
* @throws ImageException 圖檔讀取錯誤
*/ | package io.github.af19git5.entity;
/**
* 插入圖片物件
*
* @author Jimmy Kang
*/
@Getter
public class Image extends Item {
private final BufferedImage bufferedImage;
private int overrideWidth = -1;
private int overrideHeight = -1;
/**
* @param x 放置x軸位置
* @param y 放置y軸位置
* @param file 圖片檔案
* @throws ImageException 圖檔讀取錯誤
*/
public Image(int x, int y, @NonNull File file) throws ImageException {
this.setX(x);
this.setY(y);
try {
bufferedImage = ImageIO.read(file);
} catch (IOException e) {
throw new ImageException(e);
}
}
/**
* @param x 放置x軸位置
* @param y 放置y軸位置
* @param file 圖片檔案
* @param overrideWidth 覆寫寬度
* @param overrideHeight 覆寫高度
* @throws ImageException 圖檔讀取錯誤
*/
public Image(int x, int y, @NonNull File file, int overrideWidth, int overrideHeight)
throws ImageException {
if (overrideWidth <= 0 || overrideHeight <= 0) {
throw new ImageException(
"overrideWidth and overrideHeight cannot be less than or equal to 0");
}
this.setX(x);
this.setY(y);
this.overrideWidth = overrideWidth;
this.overrideHeight = overrideHeight;
try {
bufferedImage = ImageIO.read(file);
} catch (IOException e) {
throw new ImageException(e);
}
}
/**
* @param x 放置x軸位置
* @param y 放置y軸位置
* @param path 圖片檔案路徑
* @throws ImageException 圖檔讀取錯誤
*/
public Image(int x, int y, @NonNull String path) throws ImageException {
this.setX(x);
this.setY(y);
try {
bufferedImage = ImageIO.read(new File(path));
} catch (IOException e) {
throw new ImageException(e);
}
}
/**
* @param x 放置x軸位置
* @param y 放置y軸位置
* @param path 圖片檔案路徑
* @param overrideWidth 覆寫寬度
* @param overrideHeight 覆寫高度
* @throws ImageException 圖檔讀取錯誤
*/
public Image(int x, int y, @NonNull String path, int overrideWidth, int overrideHeight)
throws ImageException {
if (overrideWidth <= 0 || overrideHeight <= 0) {
throw new ImageException(
"overrideWidth and overrideHeight cannot be less than or equal to 0");
}
this.setX(x);
this.setY(y);
this.overrideWidth = overrideWidth;
this.overrideHeight = overrideHeight;
try {
bufferedImage = ImageIO.read(new File(path));
} catch (IOException e) {
throw new ImageException(e);
}
}
/**
* @param x 放置x軸位置
* @param y 放置y軸位置
* @param inputStream 資料流
* @throws ImageException 圖檔讀取錯誤
*/
public Image(int x, int y, @NonNull InputStream inputStream) throws ImageException {
this.setX(x);
this.setY(y);
try {
bufferedImage = ImageIO.read(inputStream);
} catch (IOException e) {
throw new ImageException(e);
}
}
/**
* @param x 放置x軸位置
* @param y 放置y軸位置
* @param inputStream 資料流
* @param overrideWidth 覆寫寬度
* @param overrideHeight 覆寫高度
* @throws ImageException 圖檔讀取錯誤
*/
public Image(
int x, int y, @NonNull InputStream inputStream, int overrideWidth, int overrideHeight)
throws ImageException {
if (overrideWidth <= 0 || overrideHeight <= 0) {
throw new ImageException(
"overrideWidth and overrideHeight cannot be less than or equal to 0");
}
this.setX(x);
this.setY(y);
this.overrideWidth = overrideWidth;
this.overrideHeight = overrideHeight;
try {
bufferedImage = ImageIO.read(inputStream);
} catch (IOException e) {
throw new ImageException(e);
}
}
/**
* @param positionX 放置x軸位置
* @param y 放置y軸位置
* @param file 圖片檔案
* @throws ImageException 圖檔讀取錯誤
*/
public Image(@NonNull PositionX positionX, int y, @NonNull File file) throws ImageException {
this.setPositionX(positionX);
this.setY(y);
try {
bufferedImage = ImageIO.read(file);
} catch (IOException e) {
throw new ImageException(e);
}
}
/**
* @param positionX 放置x軸位置
* @param y 放置y軸位置
* @param file 圖片檔案
* @param overrideWidth 覆寫寬度
* @param overrideHeight 覆寫高度
* @throws ImageException 圖檔讀取錯誤
*/
public Image(
@NonNull PositionX positionX,
int y,
@NonNull File file,
int overrideWidth,
int overrideHeight)
throws ImageException {
if (overrideWidth <= 0 || overrideHeight <= 0) {
throw new ImageException(
"overrideWidth and overrideHeight cannot be less than or equal to 0");
}
this.setPositionX(positionX);
this.setY(y);
this.overrideWidth = overrideWidth;
this.overrideHeight = overrideHeight;
try {
bufferedImage = ImageIO.read(file);
} catch (IOException e) {
throw new ImageException(e);
}
}
/**
* @param positionX 放置x軸位置
* @param y 放置y軸位置
* @param path 圖片檔案路徑
* @throws ImageException 圖檔讀取錯誤
*/
public Image(@NonNull PositionX positionX, int y, @NonNull String path) throws ImageException {
this.setPositionX(positionX);
this.setY(y);
try {
bufferedImage = ImageIO.read(new File(path));
} catch (IOException e) {
throw new ImageException(e);
}
}
/**
* @param positionX 放置x軸位置
* @param y 放置y軸位置
* @param path 圖片檔案路徑
* @param overrideWidth 覆寫寬度
* @param overrideHeight 覆寫高度
* @throws ImageException 圖檔讀取錯誤
*/
public Image(
@NonNull PositionX positionX,
int y,
@NonNull String path,
int overrideWidth,
int overrideHeight)
throws ImageException {
if (overrideWidth <= 0 || overrideHeight <= 0) {
throw new ImageException(
"overrideWidth and overrideHeight cannot be less than or equal to 0");
}
this.setPositionX(positionX);
this.setY(y);
this.overrideWidth = overrideWidth;
this.overrideHeight = overrideHeight;
try {
bufferedImage = ImageIO.read(new File(path));
} catch (IOException e) {
throw new ImageException(e);
}
}
/**
* @param positionX 放置x軸位置
* @param y 放置y軸位置
* @param inputStream 資料流
* @throws ImageException 圖檔讀取錯誤
*/
public Image(@NonNull PositionX positionX, int y, @NonNull InputStream inputStream)
throws ImageException {
this.setPositionX(positionX);
this.setY(y);
try {
bufferedImage = ImageIO.read(inputStream);
} catch (IOException e) {
throw new ImageException(e);
}
}
/**
* @param positionX 放置x軸位置
* @param y 放置y軸位置
* @param inputStream 資料流
* @param overrideWidth 覆寫寬度
* @param overrideHeight 覆寫高度
* @throws ImageException 圖檔讀取錯誤
*/
public Image(
@NonNull PositionX positionX,
int y,
@NonNull InputStream inputStream,
int overrideWidth,
int overrideHeight)
throws ImageException {
if (overrideWidth <= 0 || overrideHeight <= 0) {
throw new ImageException(
"overrideWidth and overrideHeight cannot be less than or equal to 0");
}
this.setPositionX(positionX);
this.setY(y);
this.overrideWidth = overrideWidth;
this.overrideHeight = overrideHeight;
try {
bufferedImage = ImageIO.read(inputStream);
} catch (IOException e) {
throw new ImageException(e);
}
}
/**
* @param x 放置x軸位置
* @param positionY 放置y軸位置
* @param file 圖片檔案
* @throws ImageException 圖檔讀取錯誤
*/ | public Image(int x, @NonNull PositionY positionY, @NonNull File file) throws ImageException { | 2 | 2023-11-01 03:55:06+00:00 | 4k |
schadfield/shogi-explorer | src/main/java/com/chadfield/shogiexplorer/main/ConfigurationManager.java | [
{
"identifier": "ConfigurationItem",
"path": "src/main/java/com/chadfield/shogiexplorer/objects/ConfigurationItem.java",
"snippet": "public class ConfigurationItem {\n\n private String optionName;\n private EngineOption engineOption;\n private JCheckBox checkBox;\n private JTextField textField;\n private JSpinner spinField;\n private JComboBox<String> comboBox;\n\n public ConfigurationItem(String optionName) {\n this.optionName = optionName;\n }\n\n /**\n * @return the optionName\n */\n public String getOptionName() {\n return optionName;\n }\n\n /**\n * @param optionName the optionName to set\n */\n public void setOptionName(String optionName) {\n this.optionName = optionName;\n }\n\n /**\n * @return the checkBox\n */\n public JCheckBox getCheckBox() {\n return checkBox;\n }\n\n /**\n * @param checkBox the checkBox to set\n */\n public void setCheckBox(JCheckBox checkBox) {\n this.checkBox = checkBox;\n }\n\n /**\n * @return the engineOption\n */\n public EngineOption getEngineOption() {\n return engineOption;\n }\n\n /**\n * @param engineOption the engineOption to set\n */\n public void setEngineOption(EngineOption engineOption) {\n this.engineOption = engineOption;\n }\n\n /**\n * @return the textField\n */\n public JTextField getTextField() {\n return textField;\n }\n\n /**\n * @param textField the textField to set\n */\n public void setTextField(JTextField textField) {\n this.textField = textField;\n }\n\n /**\n * @return the spinField\n */\n public JSpinner getSpinField() {\n return spinField;\n }\n\n /**\n * @param spinField the spinField to set\n */\n public void setSpinField(JSpinner spinField) {\n this.spinField = spinField;\n }\n\n /**\n * @return the comboBox\n */\n public JComboBox<String> getComboBox() {\n return comboBox;\n }\n\n /**\n * @param comboBox the comboBox to set\n */\n public void setComboBox(JComboBox<String> comboBox) {\n this.comboBox = comboBox;\n }\n\n}"
},
{
"identifier": "Engine",
"path": "src/main/java/com/chadfield/shogiexplorer/objects/Engine.java",
"snippet": "public class Engine {\n\n private String name;\n private String path;\n private List<EngineOption> engineOptionList;\n\n public Engine(String name, String path) {\n this.name = name;\n this.path = path;\n }\n\n /**\n * @return the name\n */\n public String getName() {\n return name;\n }\n\n /**\n * @param name the name to set\n */\n public void setName(String name) {\n this.name = name;\n }\n\n /**\n * @return the path\n */\n public String getPath() {\n return path;\n }\n\n /**\n * @param path the path to set\n */\n public void setPath(String path) {\n this.path = path;\n }\n\n /**\n * @return the engineOptionList\n */\n public List<EngineOption> getEngineOptionList() {\n return engineOptionList;\n }\n\n /**\n * @param engineOptionList the engineOptionList to set\n */\n public void setEngineOptionList(List<EngineOption> engineOptionList) {\n this.engineOptionList = engineOptionList;\n }\n\n}"
},
{
"identifier": "EngineOption",
"path": "src/main/java/com/chadfield/shogiexplorer/objects/EngineOption.java",
"snippet": "public class EngineOption {\n\n public enum Type {\n CHECK, SPIN, COMBO, STRING, FILENAME\n }\n\n private String name;\n private Type type;\n private String def;\n private String min;\n private String max;\n private List<String> varList;\n private String value;\n\n /**\n * @return the name\n */\n public String getName() {\n return name;\n }\n\n /**\n * @param name the name to set\n */\n public void setName(String name) {\n this.name = name;\n }\n\n /**\n * @return the def\n */\n public String getDef() {\n return def;\n }\n\n /**\n * @param def the def to set\n */\n public void setDef(String def) {\n this.def = def;\n }\n\n /**\n * @return the min\n */\n public String getMin() {\n return min;\n }\n\n /**\n * @param min the min to set\n */\n public void setMin(String min) {\n this.min = min;\n }\n\n /**\n * @return the max\n */\n public String getMax() {\n return max;\n }\n\n /**\n * @param max the max to set\n */\n public void setMax(String max) {\n this.max = max;\n }\n\n /**\n * @return the varList\n */\n public List<String> getVarList() {\n return varList;\n }\n\n /**\n * @param varList the varList to set\n */\n public void setVarList(List<String> varList) {\n this.varList = varList;\n }\n\n /**\n * @return the type\n */\n public Type getType() {\n return type;\n }\n\n /**\n * @param type the type to set\n */\n public void setType(Type type) {\n this.type = type;\n }\n\n /**\n * @return the value\n */\n public String getValue() {\n return value;\n }\n\n /**\n * @param value the value to set\n */\n public void setValue(String value) {\n this.value = value;\n }\n}"
}
] | import com.chadfield.shogiexplorer.objects.ConfigurationItem;
import com.chadfield.shogiexplorer.objects.Engine;
import com.chadfield.shogiexplorer.objects.EngineOption;
import java.awt.Dimension;
import java.io.File;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.JTextField;
import javax.swing.SpinnerNumberModel; | 1,880 | /*
Copyright © 2021, 2022 Stephen R Chadfield.
This file is part of Shogi Explorer.
Shogi Explorer is free software: you can redistribute it and/or modify it under the terms of the
GNU General Public License as published by the Free Software Foundation, either version 3
of the License, or (at your option) any later version.
Shogi Explorer is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with Shogi Explorer.
If not, see <https://www.gnu.org/licenses/>.
*/
package com.chadfield.shogiexplorer.main;
public class ConfigurationManager {
private ConfigurationManager() {
throw new IllegalStateException("Utility class");
}
public static void configureEngine(List<Engine> engineList, Engine engine, JDialog engineConfDialog, JDialog jEngineManagerDialog, JPanel jEngineConfPanel) { | /*
Copyright © 2021, 2022 Stephen R Chadfield.
This file is part of Shogi Explorer.
Shogi Explorer is free software: you can redistribute it and/or modify it under the terms of the
GNU General Public License as published by the Free Software Foundation, either version 3
of the License, or (at your option) any later version.
Shogi Explorer is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with Shogi Explorer.
If not, see <https://www.gnu.org/licenses/>.
*/
package com.chadfield.shogiexplorer.main;
public class ConfigurationManager {
private ConfigurationManager() {
throw new IllegalStateException("Utility class");
}
public static void configureEngine(List<Engine> engineList, Engine engine, JDialog engineConfDialog, JDialog jEngineManagerDialog, JPanel jEngineConfPanel) { | List<ConfigurationItem> configurationItemList = new ArrayList<>(); | 0 | 2023-11-08 09:24:57+00:00 | 4k |
Akshayp02/Enlight21 | app/src/main/java/com/example/enlight21/fragments/HomeFragment.java | [
{
"identifier": "FOLLOW",
"path": "app/src/main/java/com/example/enlight21/Utils/Constant.java",
"snippet": "public static final String FOLLOW = \"Follow\";"
},
{
"identifier": "POST",
"path": "app/src/main/java/com/example/enlight21/Utils/Constant.java",
"snippet": "public static final String POST = \"Post\";"
},
{
"identifier": "USER_NODE",
"path": "app/src/main/java/com/example/enlight21/Utils/Constant.java",
"snippet": "public static final String USER_NODE = \"users\";"
},
{
"identifier": "FollowrvAdapter",
"path": "app/src/main/java/com/example/enlight21/Adapters/FollowrvAdapter.java",
"snippet": "public class FollowrvAdapter extends RecyclerView.Adapter<FollowrvAdapter.ViewHolder> {\n\n ArrayList<User> followlist = new ArrayList<>();\n\n FollowRvBinding binding;\n\n public FollowrvAdapter(Context context, ArrayList<User> followlist) {\n this.followlist = followlist;\n\n }\n\n @NonNull\n @Override\n public FollowrvAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {\n binding = FollowRvBinding.inflate(LayoutInflater.from(parent.getContext()), parent, false);\n\n\n return new ViewHolder(binding);\n\n\n }\n\n @Override\n public void onBindViewHolder(@NonNull FollowrvAdapter.ViewHolder holder, int position) {\n if (followlist != null && position < followlist.size()-1) {\n // Your existing code here\n Glide.with(holder.itemView.getContext()).load(followlist.get(position).image)\n .placeholder(R.drawable.user).into(holder.binding.storyicon);\n holder.binding.followername.setText(followlist.get(position).username);\n }\n }\n\n\n @Override\n public int getItemCount() {\n return followlist.size();\n }\n\n public class ViewHolder extends RecyclerView.ViewHolder {\n FollowRvBinding binding;\n\n public ViewHolder(@NonNull FollowRvBinding binding) {\n super(binding.getRoot());\n this.binding = binding;\n\n }\n }\n}"
},
{
"identifier": "PostAdapter",
"path": "app/src/main/java/com/example/enlight21/Adapters/PostAdapter.java",
"snippet": "public class PostAdapter extends RecyclerView.Adapter<PostAdapter.ViewHolder> {\n\n public ArrayList<Post> postlist;\n FirebaseFirestore db = FirebaseFirestore.getInstance();\n int coutn = 0;\n FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();\n FirebaseFirestore dbs = FirebaseFirestore.getInstance();\n\n public PostAdapter(Context context, ArrayList<Post> postlist) {\n this.postlist = postlist;\n }\n\n public PostAdapter() {\n }\n\n @NonNull\n @Override\n public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {\n PostHomeFeedBinding binding = PostHomeFeedBinding.inflate(\n LayoutInflater.from(parent.getContext()),\n parent,\n false\n );\n\n return new ViewHolder(binding);\n\n }\n\n @Override\n public void onBindViewHolder(@NonNull ViewHolder holder, int position) {\n\n dbs.collection(USER_NODE).document(user.getUid()).get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {\n @Override\n public void onSuccess(DocumentSnapshot documentSnapshot) {\n\n User user1 = documentSnapshot.toObject(User.class);\n\n if(user1.image != null){\n // to load user image to the user profile in the post\n Picasso.get().load(user1.image).into(holder.binding.postcuretnuser);\n }\n }\n });\n /// set all deta to the image view in home feed\n\n try { // USER_NODE\n db.collection(POST).document(postlist.get(position).getUsername()).get().addOnSuccessListener(documentSnapshot -> {\n\n // holder.binding.usernaMe.setText(documentSnapshot.getString(\"username\"));\n holder.binding.usernaMe.setText(postlist.get(position).getUsername());\n holder.binding.technology.setText(postlist.get(position).getTechnology());\n holder.binding.imgeCaption.setText(postlist.get(position).getCaption());\n\n\n\n Glide.with(holder.binding.getRoot().getContext()).load(postlist.get(position).getPostUrl()).placeholder(R.drawable.user);\n\n\n });\n } catch (Exception e) {\n e.printStackTrace();\n }\n\n\n Glide.with(holder.binding.getRoot().getContext()).load(postlist.get(position).getPostUrl()).placeholder(R.drawable.loading);\n // Glide.with(holder.binding.getRoot().getContext()).load(postlist.get(position).getPostUrl()).placeholder(R.drawable.user).into(holder.binding.postcuretnuser);\n Glide.with(holder.binding.getRoot().getContext()).load(postlist.get(position).getPostUrl()).placeholder(R.drawable.loading).into(holder.binding.postimg);\n\n\n // Toast.makeText(holder.binding.getRoot().getContext(), \"username \"+coutn, Toast.LENGTH_SHORT).show();\n\n\n holder.binding.like.setOnClickListener(v -> {\n holder.binding.like.setImageResource(R.drawable.love);\n // coutn++;\n });\n\n\n\n\n }\n\n\n @Override\n public int getItemCount() {\n\n return postlist.size();\n }\n\n // ViewHolder class\n\n public class ViewHolder extends RecyclerView.ViewHolder {\n\n PostHomeFeedBinding binding;\n\n public ViewHolder(@NonNull PostHomeFeedBinding binding) {\n super(binding.getRoot());\n this.binding = binding;\n }\n\n }\n\n\n}"
},
{
"identifier": "Post",
"path": "app/src/main/java/com/example/enlight21/Models/Post.java",
"snippet": "public class Post {\n private String postUrl;\n private String caption;\n private String username;\n private String Technology;\n\n public Post() {}\n\n public Post(String postUrl, String caption) {\n this.postUrl = postUrl;\n this.caption = caption;\n }\n\n public Post(String postUrl, String caption , String username , String Technology) {\n this.postUrl = postUrl;\n this.caption = caption;\n this.username = username;\n this.Technology = Technology;\n }\n\n // Getters and setters (optional)\n public String getPostUrl() {\n return postUrl;\n }\n\n public void setPostUrl(String postUrl) {\n this.postUrl = postUrl;\n }\n\n public String getCaption() {\n return caption;\n }\n\n public void setCaption(String caption) {\n this.caption = caption;\n }\n\n public String getUsername() {\n return username;\n }\n\n public void setUsername(String username) {\n this.username = username;\n }\n\n public void setTechnology(String Technology) {\n this.Technology = Technology;\n }\n\n public String getTechnology() {\n return Technology;\n }\n\n\n}"
},
{
"identifier": "User",
"path": "app/src/main/java/com/example/enlight21/Models/User.java",
"snippet": "public class User {\n public String username;\n public String password;\n public String email;\n public String image;\n public String description;\n private boolean following = true;\n\n public User() {\n // Default constructor required for Firebase\n }\n\n public User(String username, String password, String email) {\n this.username = username;\n this.password = password;\n this.email = email;\n }\n\n public User(String username, String password, String email, String image, String description) {\n this.username = username;\n this.password = password;\n this.email = email;\n this.image = image;\n this.description = description;\n }\n\n public User(String username, String description) {\n this.username = username;\n this.description = description;\n }\n\n public User(String username, String password, String email, String image) {\n this.username = username;\n this.password = password;\n this.email = email;\n this.image = image;\n }\n\n public String getEmail() {\n return email;\n }\n\n public String getImage() {\n return image;\n }\n\n public String getName() {\n return username;\n }\n\n public String getDescription() {\n return description;\n }\n\n public void setName(String name) {\n this.username = name;\n }\n\n public void setDescription(String description) {\n this.description = description;\n }\n\n public void setImage(String image) {\n this.image = image;\n }\n\n\n\n // Getter and setter for following\n public boolean isFollowing() {\n return following;\n }\n\n public void setFollowing(boolean following) {\n this.following = following;\n }\n\n public void setEmail(String email) {\n this.email =email;\n }\n}"
},
{
"identifier": "SearchActivity",
"path": "app/src/main/java/com/example/enlight21/Post/SearchActivity.java",
"snippet": "public class SearchActivity extends AppCompatActivity {\n\n private ActivitySearchBinding binding;\n FirebaseFirestore db = FirebaseFirestore.getInstance();\n\n SearchAdapter adapter;\n ArrayList<User> userlist = new ArrayList<>();\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n binding = ActivitySearchBinding.inflate(getLayoutInflater());\n setContentView(binding.getRoot());\n\n binding.searchRecyclerView.setLayoutManager(new LinearLayoutManager(this));\n adapter = new SearchAdapter(this, userlist);\n binding.searchRecyclerView.setAdapter(adapter);\n\n\n // initial get all data of user\n\n FirebaseFirestore.getInstance().collection(USER_NODE).get().addOnSuccessListener(queryDocumentSnapshots -> {\n ArrayList<User> tempList = new ArrayList<>();\n for (QueryDocumentSnapshot documentSnapshot : queryDocumentSnapshots) {\n\n if (!documentSnapshot.getId().toString().equals(FirebaseAuth.getInstance().getCurrentUser().getUid().toString())) {\n User user = documentSnapshot.toObject(User.class);\n tempList.add(user);\n }\n\n }\n\n userlist.clear();\n userlist.addAll(tempList);\n\n adapter.notifyDataSetChanged();\n\n }).addOnFailureListener(e -> {\n // Handle failures here\n e.printStackTrace();\n });\n\n\n binding.searchbtn.setOnClickListener(view -> {\n String search = binding.searchfeld.getText().toString().trim();\n\n db.collection(USER_NODE).whereEqualTo(\"username\", search).get().addOnSuccessListener(queryDocumentSnapshots -> {\n ArrayList<User> tempList = new ArrayList<>();\n for (QueryDocumentSnapshot documentSnapshot : queryDocumentSnapshots) {\n\n // if input is not empty, get all data of user\n if (!search.isEmpty()) {\n User user = documentSnapshot.toObject(User.class);\n tempList.add(user);\n }\n }\n userlist.clear();\n userlist.addAll(tempList);\n\n adapter.notifyDataSetChanged();\n\n }).addOnFailureListener(e -> {\n // Handle failures here\n e.printStackTrace();\n }\n );\n });\n\n\n\n\n }\n}"
}
] | import static com.example.enlight21.Utils.Constant.FOLLOW;
import static com.example.enlight21.Utils.Constant.POST;
import static com.example.enlight21.Utils.Constant.USER_NODE;
import static com.example.enlight21.databinding.FragmentHomeBinding.inflate;
import android.content.Intent;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import com.example.enlight21.Adapters.FollowrvAdapter;
import com.example.enlight21.Adapters.PostAdapter;
import com.example.enlight21.Models.Post;
import com.example.enlight21.Models.User;
import com.example.enlight21.Post.SearchActivity;
import com.example.enlight21.databinding.FragmentHomeBinding;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.firestore.FirebaseFirestore;
import com.squareup.picasso.Picasso;
import java.util.ArrayList; | 2,724 | package com.example.enlight21.fragments;
public class HomeFragment extends Fragment {
private FragmentHomeBinding binding;
private ArrayList<Post> postlist = new ArrayList<>();
private ArrayList<User> followlist = new ArrayList<>(); | package com.example.enlight21.fragments;
public class HomeFragment extends Fragment {
private FragmentHomeBinding binding;
private ArrayList<Post> postlist = new ArrayList<>();
private ArrayList<User> followlist = new ArrayList<>(); | private PostAdapter adapter; | 4 | 2023-11-04 08:22:36+00:00 | 4k |
cyljx9999/talktime-Java | talktime-client/src/main/java/com/qingmeng/event/listener/SysOperateLogListener.java | [
{
"identifier": "SysOperateLogDao",
"path": "talktime-framework/talktime-dao/src/main/java/com/qingmeng/dao/SysOperateLogDao.java",
"snippet": "@Service\npublic class SysOperateLogDao extends ServiceImpl<SysOperateLogMapper, SysOperateLog> {\n\n}"
},
{
"identifier": "SysOperateLog",
"path": "talktime-framework/talktime-dao/src/main/java/com/qingmeng/entity/SysOperateLog.java",
"snippet": "@Data\n@TableName(\"sys_operate_log\")\npublic class SysOperateLog implements Serializable {\n\n private static final long serialVersionUID = -7506546756202779017L;\n /**\n * 日志主键\n */\n @TableId(value = \"id\", type = IdType.AUTO)\n private Long id;\n\n /**\n * 模块标题\n */\n private String title;\n\n /**\n * 日志内容\n */\n private String content;\n\n /**\n * 方法名称\n */\n private String method;\n\n /**\n * 请求方式\n */\n private String requestMethod;\n\n /**\n * 操作人员\n */\n private String operateName;\n\n /**\n * 请求URL\n */\n private String requestUrl;\n\n /**\n * 请求IP地址\n */\n private String ip;\n\n /**\n * IP归属地\n */\n private String ipLocation;\n\n /**\n * 请求参数\n */\n private String requestParam;\n\n /**\n * 方法响应参数\n */\n private String responseResult;\n\n /**\n * 操作状态(0正常 1异常)\n * @see OperateEnum\n */\n private Integer status;\n\n /**\n * 错误消息\n */\n private String errorMsg;\n\n /**\n * 操作时间\n */\n @TableField(fill = FieldFill.INSERT_UPDATE)\n private Date createTime;\n\n /**\n * 方法执行耗时(单位:毫秒)\n */\n private Long takeTime;\n}"
},
{
"identifier": "SysOperateLogEvent",
"path": "talktime-client/src/main/java/com/qingmeng/event/SysOperateLogEvent.java",
"snippet": "@Getter\npublic class SysOperateLogEvent extends ApplicationEvent {\n private static final long serialVersionUID = -928790594761412161L;\n private final SysOperateLog sysOperateLog;\n private final HttpServletRequest request;\n\n public SysOperateLogEvent(Object source, SysOperateLog sysOperateLog,HttpServletRequest request){\n super(source);\n this.sysOperateLog = sysOperateLog;\n this.request = request;\n }\n}"
},
{
"identifier": "SysOperateLogService",
"path": "talktime-framework/talktime-service/src/main/java/com/qingmeng/service/SysOperateLogService.java",
"snippet": "public interface SysOperateLogService{\n}"
},
{
"identifier": "IpUtils",
"path": "talktime-common/src/main/java/com/qingmeng/utils/IpUtils.java",
"snippet": "@Slf4j\npublic class IpUtils {\n private static final String IP_UTILS_FLAG = \",\";\n private static final String UNKNOWN = \"unknown\";\n private static final String LOCALHOST_IP = \"0:0:0:0:0:0:0:1\";\n private static final String LOCALHOST_IP1 = \"127.0.0.1\";\n\n /**\n * 获取IP公网地址\n * 使用Nginx等反向代理软件, 则不能通过request.getRemoteAddr()获取IP地址\n * 如果使用了多级反向代理的话,X-Forwarded-For的值并不止一个,\n * 而是一串IP地址,X-Forwarded-For中第一个非unknown的有效IP字符串,则为真实IP地址\n */\n public static String getIpAddr(HttpServletRequest request) {\n String ip = null;\n try {\n //以下两个获取在k8s中,将真实的客户端IP,放到了x-Original-Forwarded-For。而将WAF的回源地址放到了 x-Forwarded-For了。\n ip = request.getHeader(\"X-Original-Forwarded-For\");\n if (StrUtil.isEmpty(ip) || UNKNOWN.equalsIgnoreCase(ip)) {\n ip = request.getHeader(\"X-Forwarded-For\");\n }\n //获取nginx等代理的ip\n if (StrUtil.isEmpty(ip) || UNKNOWN.equalsIgnoreCase(ip)) {\n ip = request.getHeader(\"x-forwarded-for\");\n }\n if (StrUtil.isEmpty(ip) || UNKNOWN.equalsIgnoreCase(ip)) {\n ip = request.getHeader(\"Proxy-Client-IP\");\n }\n if (StrUtil.isEmpty(ip) || ip.isEmpty() || UNKNOWN.equalsIgnoreCase(ip)) {\n ip = request.getHeader(\"WL-Proxy-Client-IP\");\n }\n if (StrUtil.isEmpty(ip) || UNKNOWN.equalsIgnoreCase(ip)) {\n ip = request.getHeader(\"HTTP_CLIENT_IP\");\n }\n if (StrUtil.isEmpty(ip) || UNKNOWN.equalsIgnoreCase(ip)) {\n ip = request.getHeader(\"HTTP_X_FORWARDED_FOR\");\n }\n //兼容k8s集群获取ip\n if (StrUtil.isEmpty(ip) || UNKNOWN.equalsIgnoreCase(ip)) {\n ip = request.getRemoteAddr();\n if (LOCALHOST_IP1.equalsIgnoreCase(ip) || LOCALHOST_IP.equalsIgnoreCase(ip)) {\n //根据网卡取本机配置的IP\n InetAddress iNet = null;\n try {\n iNet = InetAddress.getLocalHost();\n } catch (UnknownHostException e) {\n log.error(\"getClientIp error: {}\", e.getMessage());\n }\n assert iNet != null;\n ip = iNet.getHostAddress();\n }\n }\n } catch (Exception e) {\n log.error(\"IPUtils ERROR \", e);\n }\n //使用代理,则获取第一个IP地址\n if (!StrUtil.isEmpty(ip) && ip.indexOf(IP_UTILS_FLAG) > 0) {\n ip = ip.substring(0, ip.indexOf(IP_UTILS_FLAG));\n }\n return ip;\n }\n\n /**\n * 获取ip归属地\n *\n * @param request request\n * @return {@link String }\n * @author qingmeng\n * @createTime: 2023/11/10 21:36:52\n */\n public static String getIpHomeLocal(HttpServletRequest request){\n String ip = getIpAddr(request);\n if (SystemConstant.LOCAL_IP.equals(ip)){\n return \"内网ip\";\n }\n String result= HttpUtil.get(\"https://api.vore.top/api/IPdata?ip=\"+ip);\n JSONObject object = JSONUtil.parseObj(result);\n Map entity = (Map) object.get(\"adcode\");\n return entity.get(\"n\").toString();\n }\n\n /**\n * 获取ip归属地\n *\n * @param ip ip地址\n * @return {@link String }\n * @author qingmeng\n * @createTime: 2023/11/23 16:09:41\n */\n public static String getIpHomeLocal(String ip){\n if (SystemConstant.LOCAL_IP.equals(ip)){\n return \"内网ip\";\n }\n String result= HttpUtil.get(\"https://api.vore.top/api/IPdata?ip=\"+ip);\n JSONObject object = JSONUtil.parseObj(result);\n Map entity = (Map) object.get(\"adcode\");\n return entity.get(\"n\").toString();\n }\n}"
}
] | import com.qingmeng.dao.SysOperateLogDao;
import com.qingmeng.entity.SysOperateLog;
import com.qingmeng.event.SysOperateLogEvent;
import com.qingmeng.service.SysOperateLogService;
import com.qingmeng.utils.IpUtils;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest; | 2,020 | package com.qingmeng.event.listener;
/**
* @author 清梦
* @version 1.0.0
* @Description 日志异步记录监听器
* @createTime 2023年11月10日 15:16:00
*/
@Component
public class SysOperateLogListener {
@Resource
private SysOperateLogDao sysOperateLogDao;
@Async("visibleTaskExecutor")
@EventListener(classes = SysOperateLogEvent.class)
public void saveLog(SysOperateLogEvent event) {
SysOperateLog sysOperateLog = event.getSysOperateLog();
HttpServletRequest request = event.getRequest();
// IP地址 | package com.qingmeng.event.listener;
/**
* @author 清梦
* @version 1.0.0
* @Description 日志异步记录监听器
* @createTime 2023年11月10日 15:16:00
*/
@Component
public class SysOperateLogListener {
@Resource
private SysOperateLogDao sysOperateLogDao;
@Async("visibleTaskExecutor")
@EventListener(classes = SysOperateLogEvent.class)
public void saveLog(SysOperateLogEvent event) {
SysOperateLog sysOperateLog = event.getSysOperateLog();
HttpServletRequest request = event.getRequest();
// IP地址 | sysOperateLog.setIp(IpUtils.getIpAddr(request)); | 4 | 2023-11-07 16:04:55+00:00 | 4k |
TianqiCS/AIChatLib-Fabric | src/main/java/com/citrusmc/aichatlib/ChatGPTUtil.java | [
{
"identifier": "ChatGroup",
"path": "src/main/java/com/citrusmc/aichatlib/client/ChatGroup.java",
"snippet": "public class ChatGroup {\n private static final Config CONFIG = ClientConfig.getInstance();\n private static final Logger LOGGER = LoggerFactory.getLogger(\"ChatBot-ChatGroup\");\n private static final String DEFAULT_MODEL = (String) CONFIG.get(\"Model.openai-engine\");\n private static final String DEFAULT_MAX_TOKENS = CONFIG.get(\"Model.max-tokens\").toString();\n private static final String DEFAULT_TEMPERATURE = CONFIG.get(\"Model.temperature\").toString();\n private static final String DEFAULT_TOP_P = CONFIG.get(\"Model.top-p\").toString();\n private static final String DEFAULT_FREQUENCY_PENALTY = CONFIG.get(\"Model.frequency-penalty\").toString();\n private static final String DEFAULT_PRESENCE_PENALTY = CONFIG.get(\"Model.presence-penalty\").toString();\n\n /**\n * The name of the chat group\n */\n public String name;\n\n /**\n * The regex pattern to match the sender\n */\n public String sender;\n /**\n * The regex pattern to match the message\n */\n public String message;\n /**\n * The list of blacklisted words in sender and message\n */\n public ArrayList<String> blacklist;\n\n /**\n * The list of triggers so that the bot will only respond to messages that contain one of the triggers\n */\n public ArrayList<String> triggers;\n\n public String model;\n public String maxTokens;\n public String prompt;\n public double temperature;\n public double topP;\n public double frequencyPenalty;\n public double presencePenalty;\n\n /**\n * Whether to include the sender's name in the message\n * Potentially useful for group chats\n */\n public boolean includeNames;\n\n /**\n * The number of messages allowed in the chat history\n * 0 means no chat history\n */\n public int chatHistorySize;\n\n /**\n * The list of stop sequences\n * OpenAI: Up to 4 sequences where the API will stop generating further tokens.\n * No checks are made for the number of sequences.\n */\n public ArrayList<String> stop;\n\n // vanilla chat group\n public ChatGroup() {\n this.name = \"vanilla\";\n this.sender = \"^<([^> ]+)> .*$\";\n this.message = \"^<[^> ]+> (.*)$\";\n\n if (CONFIG.get(\"VanillaChatGroup.triggers\") != null)\n this.triggers = (ArrayList<String>) CONFIG.get(\"VanillaChatGroup.triggers\");\n if (CONFIG.get(\"VanillaChatGroup.blacklist\") != null)\n this.blacklist = (ArrayList<String>) CONFIG.get(\"VanillaChatGroup.blacklist\");\n if (CONFIG.get(\"VanillaChatGroup.stop-sequences\")!= null)\n this.stop = (ArrayList<String>) CONFIG.get(\"VanillaChatGroup.stop-sequences\");\n\n if (CONFIG.get(\"VanillaChatGroup.prompt\")!= null)\n this.prompt = (String) CONFIG.get(\"VanillaChatGroup.prompt\");\n\n if (CONFIG.get(\"VanillaChatGroup.model\") != null)\n this.model = (String) CONFIG.get(\"VanillaChatGroup.model\");\n else this.model = DEFAULT_MODEL;\n if (CONFIG.get(\"VanillaChatGroup.max-tokens\") != null)\n this.maxTokens = (String) CONFIG.get(\"VanillaChatGroup.max-tokens\");\n else this.maxTokens = DEFAULT_MAX_TOKENS;\n if (CONFIG.get(\"VanillaChatGroup.temperature\") != null)\n this.temperature = (double) CONFIG.get(\"VanillaChatGroup.temperature\");\n else this.temperature = Float.parseFloat(DEFAULT_TEMPERATURE);\n if (CONFIG.get(\"VanillaChatGroup.top-p\") != null)\n this.topP = (double) CONFIG.get(\"VanillaChatGroup.top-p\");\n else this.topP = Float.parseFloat(DEFAULT_TOP_P);\n if (CONFIG.get(\"VanillaChatGroup.frequency-penalty\") != null)\n this.frequencyPenalty = (double) CONFIG.get(\"VanillaChatGroup.frequency-penalty\");\n else this.frequencyPenalty = Float.parseFloat(DEFAULT_FREQUENCY_PENALTY);\n if (CONFIG.get(\"VanillaChatGroup.presence-penalty\") != null)\n this.presencePenalty = (double) CONFIG.get(\"VanillaChatGroup.presence-penalty\");\n else this.presencePenalty = Float.parseFloat(DEFAULT_PRESENCE_PENALTY);\n if (CONFIG.get(\"VanillaChatGroup.chat-history-size\") != null)\n this.chatHistorySize = (int) CONFIG.get(\"VanillaChatGroup.chat-history-size\");\n else this.chatHistorySize = 0;\n if (CONFIG.get(\"VanillaChatGroup.include-names\") != null)\n this.includeNames = (boolean) CONFIG.get(\"VanillaChatGroup.include-names\");\n else this.includeNames = false;\n }\n\n public ChatGroup(String name, Map<String, Object> chatGroup) {\n this.name = name;\n this.sender = (String) chatGroup.get(\"sender\");\n this.message = (String) chatGroup.get(\"message\");\n\n if (chatGroup.get(\"blacklist\") != null)\n this.blacklist = (ArrayList<String>) chatGroup.get(\"blacklist\");\n if (chatGroup.get(\"triggers\") != null)\n this.triggers = (ArrayList<String>) chatGroup.get(\"triggers\");\n if (chatGroup.get(\"stop-sequences\") != null)\n this.stop = (ArrayList<String>) chatGroup.get(\"stop-sequences\");\n\n if (chatGroup.get(\"prompt\") != null)\n this.prompt = (String) chatGroup.get(\"prompt\");\n\n if (chatGroup.get(\"model\") != null)\n this.model = (String) chatGroup.get(\"model\");\n else this.model = DEFAULT_MODEL;\n if (chatGroup.get(\"max-tokens\") != null)\n this.maxTokens = String.valueOf(chatGroup.get(\"max-tokens\"));\n else this.maxTokens = DEFAULT_MAX_TOKENS;\n if (chatGroup.get(\"temperature\") != null)\n this.temperature = (double) chatGroup.get(\"temperature\");\n else this.temperature = Float.parseFloat(DEFAULT_TEMPERATURE);\n if (chatGroup.get(\"top-p\") != null)\n this.topP = (double) chatGroup.get(\"top-p\");\n else this.topP = Float.parseFloat(DEFAULT_TOP_P);\n if (chatGroup.get(\"frequency-penalty\") != null)\n this.frequencyPenalty = (double) chatGroup.get(\"frequency-penalty\");\n else this.frequencyPenalty = Float.parseFloat(DEFAULT_FREQUENCY_PENALTY);\n if (chatGroup.get(\"presence-penalty\") != null)\n this.presencePenalty = (double) chatGroup.get(\"presence-penalty\");\n else this.presencePenalty = Float.parseFloat(DEFAULT_PRESENCE_PENALTY);\n if (chatGroup.get(\"chat-history-size\") != null)\n this.chatHistorySize = (int) chatGroup.get(\"chat-history-size\");\n else this.chatHistorySize = 0;\n if (chatGroup.get(\"include-names\") != null)\n this.includeNames = (boolean) chatGroup.get(\"include-names\");\n else this.includeNames = false;\n }\n}"
},
{
"identifier": "ClientConfig",
"path": "src/main/java/com/citrusmc/aichatlib/configs/ClientConfig.java",
"snippet": "public class ClientConfig extends Config{\n static ClientConfig instance = null;\n\n private ClientConfig() {\n String configFileLocation = \"config/AIChatLib/ClientConfig.yml\";\n this.config = this.loadConfig(configFileLocation, getDefaultConfig());\n }\n\n public static Config getInstance() {\n if (instance == null) {\n instance = new ClientConfig();\n }\n return instance;\n }\n\n\n private ClientConfig(String configLocation, String jarDefault) {\n config = loadConfig(configLocation, jarDefault);\n }\n @Override\n String getDefaultConfig() {\n return String.valueOf(getClass().getClassLoader().getResource(\"configs/ClientConfig.yml\"));\n }\n}"
},
{
"identifier": "Config",
"path": "src/main/java/com/citrusmc/aichatlib/configs/Config.java",
"snippet": "public abstract class Config {\n\n protected Map<String, Object> config = null;\n\n public synchronized Map<String, Object> loadConfig(String configFileLocation, String jarDefaultLocation) {\n Map<String, Object> defaults = null;\n\n try (InputStream stream = new URL(jarDefaultLocation).openStream()) {\n defaults = new Yaml().load(stream);\n\n } catch (IOException e) {\n e.printStackTrace();\n }\n\n Map<String, Object> configsFromFile = new HashMap<>();\n File configFile = new File(configFileLocation);\n\n if (configFile.exists()) {\n try (FileInputStream input = new FileInputStream(configFile)) {\n configsFromFile = new Yaml().load(input);\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n for (Map.Entry<String, Object> entry : configsFromFile.entrySet()) {\n\n assert defaults != null;\n if (defaults.containsKey(entry.getKey())) {\n defaults.put(entry.getKey(), entry.getValue());\n }\n }\n\n saveConfig(configFileLocation, defaults);\n\n return defaults;\n }\n\n\n // save config to file location\n public synchronized void saveConfig(String location, Map<String, Object> config) {\n try {\n Files.createDirectories(new File(location).getParentFile().toPath());\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n try (FileWriter writer = new FileWriter(location, StandardCharsets.UTF_8)) {\n DumperOptions options = new DumperOptions();\n options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);\n options.setPrettyFlow(true);\n Yaml yaml = new Yaml(options);\n yaml.dump(config, writer);\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n abstract String getDefaultConfig();\n\n // get config entry\n public synchronized Object get(String key) {\n String[] keys = key.split(\"\\\\.\");\n Map<String, Object> childConfig = config;\n for (int i = 0; i < keys.length - 1; i++) {\n Pattern pattern = Pattern.compile(\"([^\\\\[\\\\]]+)(?:\\\\[(\\\\\\\\d+)\\\\])?\");\n Matcher matcher = pattern.matcher(keys[i]);\n if (matcher.find()) {\n String entry = matcher.group(1);\n String entryIndex = matcher.group(2);\n if (entryIndex != null) {\n childConfig = (Map<String, Object>) ((List<Object>) childConfig.get(entry)).get(Integer.parseInt(entryIndex));\n }\n else {\n childConfig = (Map<String, Object>) childConfig.get(entry);\n }\n } else {\n throw new IllegalStateException(\"Invalid config key: \" + key);\n }\n }\n return childConfig.get(keys[keys.length - 1]);\n }\n\n}"
}
] | import com.citrusmc.aichatlib.client.ChatGroup;
import com.citrusmc.aichatlib.configs.ClientConfig;
import com.citrusmc.aichatlib.configs.Config;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.net.SocketTimeoutException;
import java.util.concurrent.CompletableFuture; | 2,698 | package com.citrusmc.aichatlib;
public class ChatGPTUtil {
private static final Logger LOGGER = LoggerFactory.getLogger("ChatBot-ChatGPTUtil");
private static final OkHttpClient httpClient = HttpClientFactory.createClient(); | package com.citrusmc.aichatlib;
public class ChatGPTUtil {
private static final Logger LOGGER = LoggerFactory.getLogger("ChatBot-ChatGPTUtil");
private static final OkHttpClient httpClient = HttpClientFactory.createClient(); | private static final Config CONFIG = ClientConfig.getInstance(); | 2 | 2023-11-06 00:04:54+00:00 | 4k |
Griefed/AddEmAll | common/src/main/java/de/griefed/addemall/item/GeneratedModItems.java | [
{
"identifier": "Constants",
"path": "common/src/main/java/de/griefed/addemall/Constants.java",
"snippet": "public class Constants {\n\n\tpublic static final String MOD_ID = \"addemall\";\n\tpublic static final String MOD_NAME = \"AddEmAll\";\n\tpublic static final Logger LOG = LoggerFactory.getLogger(MOD_NAME);\n}"
},
{
"identifier": "Services",
"path": "common/src/main/java/de/griefed/addemall/platform/Services.java",
"snippet": "public class Services {\n\n // In this example we provide a platform helper which provides information about what platform the mod is running on.\n // For example this can be used to check if the code is running on Forge vs Fabric, or to ask the modloader if another\n // mod is loaded.\n public static final IPlatformHelper PLATFORM = load(IPlatformHelper.class);\n\n // This code is used to load a service for the current environment. Your implementation of the service must be defined\n // manually by including a text file in META-INF/services named with the fully qualified class name of the service.\n // Inside the file you should write the fully qualified class name of the implementation to load for the platform. For\n // example our file on Forge points to ForgePlatformHelper while Fabric points to FabricPlatformHelper.\n public static <T> T load(Class<T> clazz) {\n\n final T loadedService = ServiceLoader.load(clazz)\n .findFirst()\n .orElseThrow(() -> new NullPointerException(\"Failed to load service for \" + clazz.getName()));\n Constants.LOG.debug(\"Loaded {} for service {}\", loadedService, clazz);\n return loadedService;\n }\n}"
},
{
"identifier": "RegistrationProvider",
"path": "common/src/main/java/de/griefed/addemall/registry/RegistrationProvider.java",
"snippet": "public interface RegistrationProvider<T> {\n\n /**\n * Gets a provider for specified {@code modId} and {@code resourceKey}. <br>\n * It is <i>recommended</i> to store the resulted provider in a {@code static final} field to\n * the {@link Factory#INSTANCE factory} creating multiple providers for the same resource key and mod id.\n *\n * @param resourceKey the {@link ResourceKey} of the registry of the provider\n * @param modId the mod id that the provider will register objects for\n * @param <T> the type of the provider\n * @return the provider\n */\n static <T> RegistrationProvider<T> get(ResourceKey<? extends Registry<T>> resourceKey, String modId) {\n return Factory.INSTANCE.create(resourceKey, modId);\n }\n\n /**\n * Gets a provider for specified {@code modId} and {@code registry}. <br>\n * It is <i>recommended</i> to store the resulted provider in a {@code static final} field to\n * the {@link Factory#INSTANCE factory} creating multiple providers for the same resource key and mod id.\n *\n * @param registry the {@link Registry} of the provider\n * @param modId the mod id that the provider will register objects for\n * @param <T> the type of the provider\n * @return the provider\n */\n static <T> RegistrationProvider<T> get(Registry<T> registry, String modId) {\n return Factory.INSTANCE.create(registry, modId);\n }\n\n /**\n * Registers an object.\n *\n * @param name the name of the object\n * @param supplier a supplier of the object to register\n * @param <I> the type of the object\n * @return a wrapper containing the lazy registered object. <strong>Calling {@link RegistryObject#get() get} too early\n * on the wrapper might result in crashes!</strong>\n */\n <I extends T> RegistryObject<I> register(String name, Supplier<? extends I> supplier);\n\n /**\n * Gets all the objects currently registered.\n *\n * @return an <strong>immutable</strong> view of all the objects currently registered\n */\n Collection<RegistryObject<T>> getEntries();\n\n /**\n * Gets the mod id that this provider registers objects for.\n *\n * @return the mod id\n */\n String getModId();\n\n /**\n * Factory class for {@link RegistrationProvider registration providers}. <br>\n * This class is loaded using {@link java.util.ServiceLoader Service Loaders}, and only one\n * should exist per mod loader.\n */\n interface Factory {\n\n /**\n * The singleton instance of the {@link Factory}. This is different on each loader.\n */\n Factory INSTANCE = Services.load(Factory.class);\n\n /**\n * Creates a {@link RegistrationProvider}.\n *\n * @param resourceKey the {@link ResourceKey} of the registry to create this provider for\n * @param modId the mod id for which the provider will register objects\n * @param <T> the type of the provider\n * @return the provider\n */\n <T> RegistrationProvider<T> create(ResourceKey<? extends Registry<T>> resourceKey, String modId);\n\n /**\n * Creates a {@link RegistrationProvider}.\n *\n * @param registry the {@link Registry} to create this provider for\n * @param modId the mod id for which the provider will register objects\n * @param <T> the type of the provider\n * @return the provider\n */\n default <T> RegistrationProvider<T> create(Registry<T> registry, String modId) {\n return create(registry.key(), modId);\n }\n }\n}"
},
{
"identifier": "RegistryObject",
"path": "common/src/main/java/de/griefed/addemall/registry/RegistryObject.java",
"snippet": "public interface RegistryObject<T> extends Supplier<T> {\n\n /**\n * Gets the {@link ResourceKey} of the registry of the object wrapped.\n *\n * @return the {@link ResourceKey} of the registry\n */\n ResourceKey<T> getResourceKey();\n\n /**\n * Gets the id of the object.\n *\n * @return the id of the object\n */\n ResourceLocation getId();\n\n /**\n * Gets the object behind this wrapper. Calling this method too early\n * might result in crashes.\n *\n * @return the object behind this wrapper\n */\n @Override\n T get();\n\n /**\n * Gets this object wrapped in a vanilla {@link Holder}.\n *\n * @return the holder\n */\n Holder<T> asHolder();\n}"
}
] | import de.griefed.addemall.Constants;
import de.griefed.addemall.platform.Services;
import de.griefed.addemall.registry.RegistrationProvider;
import de.griefed.addemall.registry.RegistryObject;
import net.minecraft.core.Registry;
import net.minecraft.world.item.Item; | 1,684 | package de.griefed.addemall.item;
@SuppressWarnings("unused")
public class GeneratedModItems {
public static final RegistrationProvider<Item> ITEMS = RegistrationProvider.get(Registry.ITEM_REGISTRY, Constants.MOD_ID);
/*###GENERATED CODE - DO NOT EDIT - MANUALLY EDITED CODE WILL BE LOST###*/
/*###GENERATED CODE - DO NOT EDIT - MANUALLY EDITED CODE WILL BE LOST###*/
private static Item.Properties itemBuilder() { | package de.griefed.addemall.item;
@SuppressWarnings("unused")
public class GeneratedModItems {
public static final RegistrationProvider<Item> ITEMS = RegistrationProvider.get(Registry.ITEM_REGISTRY, Constants.MOD_ID);
/*###GENERATED CODE - DO NOT EDIT - MANUALLY EDITED CODE WILL BE LOST###*/
/*###GENERATED CODE - DO NOT EDIT - MANUALLY EDITED CODE WILL BE LOST###*/
private static Item.Properties itemBuilder() { | return new Item.Properties().tab(Services.PLATFORM.getCreativeTab()); | 1 | 2023-11-06 12:50:10+00:00 | 4k |
MonstrousSoftware/Tut3D | core/src/main/java/com/monstrous/tut3d/behaviours/Behaviour.java | [
{
"identifier": "GameObject",
"path": "core/src/main/java/com/monstrous/tut3d/GameObject.java",
"snippet": "public class GameObject implements Disposable {\n\n public final GameObjectType type;\n public final Scene scene;\n public final PhysicsBody body;\n public final Vector3 direction;\n public boolean visible;\n public float health;\n public Behaviour behaviour;\n\n public GameObject(GameObjectType type, Scene scene, PhysicsBody body) {\n this.type = type;\n this.scene = scene;\n this.body = body;\n if(body != null)\n body.geom.setData(this); // the geom has user data to link back to GameObject for collision handling\n visible = true;\n direction = new Vector3();\n health = 1f;\n behaviour = Behaviour.createBehaviour(this);\n }\n\n public void update(World world, float deltaTime ){\n if(behaviour != null)\n behaviour.update(world, deltaTime);\n }\n\n public boolean isDead() {\n return health <= 0;\n }\n\n public Vector3 getPosition() {\n if(body == null)\n return Vector3.Zero;\n return body.getPosition();\n }\n\n public Vector3 getDirection() {\n direction.set(0,0,1);\n direction.mul(body.getOrientation());\n return direction;\n }\n\n @Override\n public void dispose() {\n body.destroy();\n }\n}"
},
{
"identifier": "World",
"path": "core/src/main/java/com/monstrous/tut3d/World.java",
"snippet": "public class World implements Disposable {\n\n private final Array<GameObject> gameObjects;\n private GameObject player;\n public GameStats stats;\n private final SceneAsset sceneAsset;\n private final PhysicsWorld physicsWorld;\n private final PhysicsBodyFactory factory;\n private final PlayerController playerController;\n public final PhysicsRayCaster rayCaster;\n public final WeaponState weaponState;\n public NavMesh navMesh;\n public NavNode navNode;\n private int prevNode = -1;\n\n public World() {\n gameObjects = new Array<>();\n stats = new GameStats();\n sceneAsset = Main.assets.sceneAsset;\n// for(Node node : sceneAsset.scene.model.nodes){ // print some debug info\n// Gdx.app.log(\"Node \", node.id);\n// }\n physicsWorld = new PhysicsWorld(this);\n factory = new PhysicsBodyFactory(physicsWorld);\n rayCaster = new PhysicsRayCaster(physicsWorld);\n playerController = new PlayerController(this);\n weaponState = new WeaponState();\n }\n\n public void clear() {\n physicsWorld.reset();\n playerController.reset();\n stats.reset();\n weaponState.reset();\n\n gameObjects.clear();\n player = null;\n navMesh = null;\n prevNode = -1;\n }\n public int getNumGameObjects() {\n return gameObjects.size;\n }\n\n public GameObject getGameObject(int index) {\n return gameObjects.get(index);\n }\n\n public GameObject getPlayer() {\n return player;\n }\n\n public void setPlayer( GameObject player ){\n this.player = player;\n player.body.setCapsuleCharacteristics();\n //navMesh.updateDistances(player.getPosition());\n }\n\n public PlayerController getPlayerController() {\n return playerController;\n }\n\n public GameObject spawnObject(GameObjectType type, String name, String proxyName, CollisionShapeType shapeType, boolean resetPosition, Vector3 position){\n Scene scene = loadNode( name, resetPosition, position );\n ModelInstance collisionInstance = scene.modelInstance;\n if(proxyName != null) {\n Scene proxyScene = loadNode( proxyName, resetPosition, position );\n collisionInstance = proxyScene.modelInstance;\n }\n PhysicsBody body = null;\n if(type == GameObjectType.TYPE_NAVMESH){\n navMesh = NavMeshBuilder.build(scene.modelInstance);\n return null;\n }\n body = factory.createBody(collisionInstance, shapeType, type.isStatic);\n GameObject go = new GameObject(type, scene, body);\n gameObjects.add(go);\n if(go.type == GameObjectType.TYPE_ENEMY)\n stats.numEnemies++;\n if(go.type == GameObjectType.TYPE_PICKUP_COIN)\n stats.numCoins++;\n\n return go;\n }\n\n private Scene loadNode( String nodeName, boolean resetPosition, Vector3 position ) {\n Scene scene = new Scene(sceneAsset.scene, nodeName);\n if(scene.modelInstance.nodes.size == 0)\n throw new RuntimeException(\"Cannot find node in GLTF file: \" + nodeName);\n applyNodeTransform(resetPosition, scene.modelInstance, scene.modelInstance.nodes.first()); // incorporate nodes' transform into model instance transform\n scene.modelInstance.transform.translate(position);\n return scene;\n }\n\n private void applyNodeTransform(boolean resetPosition, ModelInstance modelInstance, Node node ){\n if(!resetPosition)\n modelInstance.transform.mul(node.globalTransform);\n node.translation.set(0,0,0);\n node.scale.set(1,1,1);\n node.rotation.idt();\n modelInstance.calculateTransforms();\n }\n\n public void removeObject(GameObject gameObject){\n gameObject.health = 0;\n if(gameObject.type == GameObjectType.TYPE_ENEMY)\n stats.numEnemies--;\n gameObjects.removeValue(gameObject, true);\n gameObject.dispose();\n }\n\n\n\n public void update( float deltaTime ) {\n if(stats.numEnemies > 0 || stats.coinsCollected < stats.numCoins)\n stats.gameTime += deltaTime;\n else {\n if(!stats.levelComplete)\n Main.assets.sounds.GAME_COMPLETED.play();\n stats.levelComplete = true;\n }\n weaponState.update(deltaTime);\n playerController.update(player, deltaTime);\n physicsWorld.update(deltaTime);\n syncToPhysics();\n for(GameObject go : gameObjects) {\n if(go.getPosition().y < -10) // delete objects that fell off the map\n removeObject(go);\n go.update(this, deltaTime);\n }\n\n// navNode = navMesh.findNode( player.getPosition(), Settings.groundRayLength );\n// if(navNode == null)\n// Gdx.app.error(\"player outside the nav mesh:\", \" pos:\"+ player.getPosition().toString());\n// if (navNode != null && navNode.id != prevNode) {\n// Gdx.app.log(\"player moves to nav node:\", \"\" + navNode.id + \" pos:\" + player.getPosition().toString());\n// prevNode = navNode.id;\n// navMesh.updateDistances(player.getPosition());\n// }\n }\n\n private void syncToPhysics() {\n for(GameObject go : gameObjects){\n if( go.body != null && go.body.geom.getBody() != null) {\n if(go.type == GameObjectType.TYPE_PLAYER){\n // use information from the player controller, since the rigid body is not rotated.\n player.scene.modelInstance.transform.setToRotation(Vector3.Z, playerController.getForwardDirection());\n player.scene.modelInstance.transform.setTranslation(go.body.getPosition());\n }\n else if(go.type == GameObjectType.TYPE_ENEMY){\n CookBehaviour cb = (CookBehaviour) go.behaviour;\n go.scene.modelInstance.transform.setToRotation(Vector3.Z, cb.getDirection());\n go.scene.modelInstance.transform.setTranslation(go.body.getPosition());\n }\n else\n go.scene.modelInstance.transform.set(go.body.getPosition(), go.body.getOrientation());\n }\n }\n }\n\n\n private final Vector3 spawnPos = new Vector3();\n private final Vector3 shootForce = new Vector3();\n private final Vector3 impulse = new Vector3();\n\n // fire current weapon\n public void fireWeapon(Vector3 viewingDirection, PhysicsRayCaster.HitPoint hitPoint) {\n if(player.isDead())\n return;\n if(!weaponState.isWeaponReady()) // to give delay between shots\n return;\n weaponState.firing = true; // set state to firing (triggers gun animation in GameScreen)\n\n switch(weaponState.currentWeaponType) {\n case BALL:\n spawnPos.set(viewingDirection);\n spawnPos.add(player.getPosition()); // spawn from 1 unit in front of the player\n GameObject ball = spawnObject(GameObjectType.TYPE_FRIENDLY_BULLET, \"ball\", null, CollisionShapeType.SPHERE, true, spawnPos );\n shootForce.set(viewingDirection); // shoot in viewing direction (can be up or down from player direction)\n shootForce.scl(Settings.ballForce); // scale for speed\n ball.body.geom.getBody().setDamping(0.0f, 0.0f);\n ball.body.applyForce(shootForce);\n break;\n case GUN:\n Main.assets.sounds.GUN_SHOT.play();\n if(hitPoint.hit) {\n GameObject victim = hitPoint.refObject;\n Gdx.app.log(\"gunshot hit\", victim.scene.modelInstance.nodes.first().id);\n if(victim.type.isEnemy)\n bulletHit(victim);\n\n impulse.set(victim.getPosition()).sub(player.getPosition()).nor().scl(Settings.gunForce);\n if(victim.body.geom.getBody() != null ) {\n victim.body.geom.getBody().enable();\n victim.body.applyForceAtPos(impulse, hitPoint.worldContactPoint);\n }\n }\n break;\n }\n }\n\n\n\n\n public void onCollision(GameObject go1, GameObject go2){\n // try either order\n if(go1.type.isStatic || go2.type.isStatic)\n return;\n\n handleCollision(go1, go2);\n handleCollision(go2, go1);\n }\n\n private void handleCollision(GameObject go1, GameObject go2) {\n if (go1.type.isPlayer && go2.type.canPickup) {\n pickup(go1, go2);\n }\n if (go1.type.isPlayer && go2.type.isEnemyBullet) {\n removeObject(go2);\n bulletHit(go1);\n }\n\n if(go1.type.isEnemy && go2.type.isFriendlyBullet) {\n removeObject(go2);\n bulletHit(go1);\n }\n }\n\n private void pickup(GameObject character, GameObject pickup){\n\n removeObject(pickup);\n if(pickup.type == GameObjectType.TYPE_PICKUP_COIN) {\n stats.coinsCollected++;\n Main.assets.sounds.COIN.play();\n }\n else if(pickup.type == GameObjectType.TYPE_PICKUP_HEALTH) {\n character.health = Math.min(character.health + 0.5f, 1f); // +50% health\n Main.assets.sounds.UPGRADE.play();\n }\n else if(pickup.type == GameObjectType.TYPE_PICKUP_GUN) {\n weaponState.haveGun = true;\n weaponState.currentWeaponType = WeaponType.GUN;\n Main.assets.sounds.UPGRADE.play();\n }\n }\n\n private void bulletHit(GameObject character) {\n character.health -= 0.25f; // - 25% health\n Main.assets.sounds.HIT.play();\n if(character.isDead()) {\n removeObject(character);\n if (character.type.isPlayer)\n Main.assets.sounds.GAME_OVER.play();\n }\n }\n\n @Override\n public void dispose() {\n physicsWorld.dispose();\n rayCaster.dispose();\n }\n}"
}
] | import com.monstrous.tut3d.GameObject;
import com.monstrous.tut3d.World; | 2,724 | package com.monstrous.tut3d.behaviours;
public class Behaviour {
protected final GameObject go;
protected Behaviour(GameObject go) {
this.go = go;
}
| package com.monstrous.tut3d.behaviours;
public class Behaviour {
protected final GameObject go;
protected Behaviour(GameObject go) {
this.go = go;
}
| public void update(World world, float deltaTime ) { } | 1 | 2023-11-04 13:15:48+00:00 | 4k |
Einzieg/EinziegCloud | src/main/java/com/cloud/service/impl/LogServiceImpl.java | [
{
"identifier": "Log",
"path": "src/main/java/com/cloud/entity/Log.java",
"snippet": "@Data\n@Builder\n@TableName(\"cloud_log\")\npublic class Log {\n\n\t/**\n\t * 主键\n\t */\n\t@TableId(value = \"ID\", type = IdType.AUTO)\n\tprivate Long id;\n\n\t/**\n\t * 运行结果\n\t */\n\t@TableField(value = \"OUTCOME\")\n\tprivate String outcome;\n\n\t/**\n\t * 创建时间\n\t */\n\t@TableField(value = \"CREATE_TIME\")\n\tprivate Date createTime;\n\n\t/**\n\t * 耗时\n\t */\n\t@TableField(value = \"TAKE_TIME\")\n\tprivate Long takeTime;\n\n\t/**\n\t * http请求方法\n\t */\n\t@TableField(value = \"HTTP_METHOD\")\n\tprivate String httpMethod;\n\n\t/**\n\t * 类方法\n\t */\n\t@TableField(value = \"CLASS_METHOD\")\n\tprivate String classMethod;\n\n\t/**\n\t * 请求URL\n\t */\n\t@TableField(value = \"REQUEST_URL\")\n\tprivate String requestUrl;\n\n\t/**\n\t * 请求IP\n\t */\n\t@TableField(value = \"IP\")\n\tprivate String ip;\n\n\t/**\n\t * 用户\n\t */\n\t@TableField(value = \"USER\")\n\tprivate String user;\n\n\t/**\n\t * 模块\n\t */\n\t@TableField(value = \"MODEL\")\n\tprivate String model;\n\n\t/**\n\t * 说明\n\t */\n\t@TableField(value = \"DETAIL\")\n\tprivate String detail;\n\n\t@TableField(value = \"RETURN_BODY\")\n\tprivate String returnBody;\n}"
},
{
"identifier": "LogMapper",
"path": "src/main/java/com/cloud/mapper/LogMapper.java",
"snippet": "public interface LogMapper extends BaseMapper<Log> {\n}"
},
{
"identifier": "ILogService",
"path": "src/main/java/com/cloud/service/ILogService.java",
"snippet": "public interface ILogService extends IService<Log> {\n\n\tvoid saveLog(ProceedingJoinPoint joinPoint, String outcome, Long currentTime, Object returnBody);\n\n\tMsg<?> getLogs(Log olog, Integer current, Integer size);\n}"
},
{
"identifier": "HttpUtil",
"path": "src/main/java/com/cloud/util/HttpUtil.java",
"snippet": "public class HttpUtil {\n\n\tpublic static HttpServletRequest getHttpServletRequest() {\n\t\tServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();\n\t\treturn attributes != null ? attributes.getRequest() : null;\n\t}\n}"
},
{
"identifier": "IPUtil",
"path": "src/main/java/com/cloud/util/IPUtil.java",
"snippet": "@Slf4j\npublic class IPUtil {\n\tprivate static final String IP_UTILS_FLAG = \",\";\n\tprivate static final String UNKNOWN = \"unknown\";\n\tprivate static final String LOCALHOST_IP = \"0:0:0:0:0:0:0:1\";\n\tprivate static final String LOCALHOST_IP1 = \"127.0.0.1\";\n\n\t/**\n\t * 获取IP地址\n\t * <p>\n\t * 使用Nginx等反向代理软件, 则不能通过request.getRemoteAddr()获取IP地址\n\t * 如果使用了多级反向代理的话,X-Forwarded-For的值并不止一个,而是一串IP地址,X-Forwarded-For中第一个非unknown的有效IP字符串,则为真实IP地址\n\t */\n\tpublic static String getIpAddr() {\n\t\tHttpServletRequest request = HttpUtil.getHttpServletRequest();\n\t\tString ip = null;\n\t\ttry {\n\t\t\t//以下两个获取在k8s中,将真实的客户端IP,放到了x-Original-Forwarded-For。而将WAF的回源地址放到了 x-Forwarded-For了。\n\t\t\tassert request != null;\n\t\t\tip = request.getHeader(\"X-Original-Forwarded-For\");\n\t\t\tif (!StringUtils.hasText(ip) || UNKNOWN.equalsIgnoreCase(ip)) {\n\t\t\t\tip = request.getHeader(\"X-Forwarded-For\");\n\t\t\t}\n\t\t\t//获取nginx等代理的ip\n\t\t\tif (!StringUtils.hasText(ip) || UNKNOWN.equalsIgnoreCase(ip)) {\n\t\t\t\tip = request.getHeader(\"x-forwarded-for\");\n\t\t\t}\n\t\t\tif (!StringUtils.hasText(ip) || UNKNOWN.equalsIgnoreCase(ip)) {\n\t\t\t\tip = request.getHeader(\"Proxy-Client-IP\");\n\t\t\t}\n\t\t\tif (!StringUtils.hasText(ip) || ip.isEmpty() || UNKNOWN.equalsIgnoreCase(ip)) {\n\t\t\t\tip = request.getHeader(\"WL-Proxy-Client-IP\");\n\t\t\t}\n\t\t\tif (!StringUtils.hasText(ip) || UNKNOWN.equalsIgnoreCase(ip)) {\n\t\t\t\tip = request.getHeader(\"HTTP_CLIENT_IP\");\n\t\t\t}\n\t\t\tif (!StringUtils.hasText(ip) || UNKNOWN.equalsIgnoreCase(ip)) {\n\t\t\t\tip = request.getHeader(\"HTTP_X_FORWARDED_FOR\");\n\t\t\t}\n\t\t\t//兼容k8s集群获取ip\n\t\t\tif (!StringUtils.hasText(ip) || UNKNOWN.equalsIgnoreCase(ip)) {\n\t\t\t\tip = request.getRemoteAddr();\n\t\t\t\tif (LOCALHOST_IP1.equalsIgnoreCase(ip) || LOCALHOST_IP.equalsIgnoreCase(ip)) {\n\t\t\t\t\t//根据网卡取本机配置的IP\n\t\t\t\t\tInetAddress iNet = null;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tiNet = InetAddress.getLocalHost();\n\t\t\t\t\t} catch (UnknownHostException e) {\n\t\t\t\t\t\tlog.error(\"获取客户端IP错误:\", e);\n\t\t\t\t\t}\n\t\t\t\t\tip = iNet != null ? iNet.getHostAddress() : null;\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (Exception e) {\n\t\t\tlog.error(\"IPUtil ERROR \", e);\n\t\t}\n\t\t//使用代理,则获取第一个IP地址\n\t\tif (StringUtils.hasText(ip) && ip.indexOf(IP_UTILS_FLAG) > 0) {\n\t\t\tip = ip.substring(0, ip.indexOf(IP_UTILS_FLAG));\n\t\t}\n\n\t\treturn ip;\n\t}\n\n}"
},
{
"identifier": "JwtUtil",
"path": "src/main/java/com/cloud/util/JwtUtil.java",
"snippet": "@Service\npublic class JwtUtil {\n\n\tprivate static final String SECRET_KEY =\n\t\t\t\"B?E+ShuviDoura(H+MbQeShVmYq3t6w9z$C&F)J@NcRfUjWnZr4u7x!A%D*G-KaPdSgVkYp3s5vq3t6w9z$C&F)H@McQfTjWnZr4u7x!A%D*G-KaNdRgUkXp2s5v8y/B?E(H+MbQeSh\";\n\n\t/**\n\t * 提取所有声明\n\t *\n\t * @param token 令牌\n\t * @return {@code Claims}\n\t */\n\tprivate static Claims extractAllClaims(String token) {\n\t\treturn Jwts.parserBuilder() // 获取一个Jwt解析器构建器\n\t\t\t\t.setSigningKey(getSignInKey()) // 设置Jwt验证签名\n\t\t\t\t.build()\n\t\t\t\t.parseClaimsJws(token) // 解析Jwt令牌\n\t\t\t\t.getBody(); // 获取Jwt令牌的主体(Body)其中的声明信息\n\t}\n\n\t/**\n\t * 获取签名密钥\n\t *\n\t * @return {@code Key} 用于验证Jwt签名的密钥。签名密钥必须与生成Jwt令牌时使用的密钥相同,否则无法正确验证Jwt的真实性。\n\t */\n\tprivate static Key getSignInKey() {\n\t\tbyte[] keyBytes = DatatypeConverter.parseBase64Binary(SECRET_KEY);\n\t\treturn Keys.hmacShaKeyFor(keyBytes);\n\t}\n\n\n\t/**\n\t * 从Jwt提取特定声明(Claims)信息\n\t *\n\t * @param token 令牌\n\t * @param claimsResolver 解析器\n\t * @return {@code T}\n\t */\n\tpublic static <T> T extractClaim(String token, Function<Claims, T> claimsResolver) {\n\t\tfinal Claims claims = extractAllClaims(token); // 获取JWT令牌中的所有声明信息,存储在Claims对象中\n\t\treturn claimsResolver.apply(claims);\n\t}\n\n\t/**\n\t * 生成Jwt令牌\n\t *\n\t * @param extraClaims 额外的声明信息\n\t * @param userDetails 用户详细信息\n\t * @return {@code String}\n\t */\n\tpublic String generateToken(Map<String, Object> extraClaims, UserDetails userDetails) {\n\t\treturn Jwts.builder() // 获取一个JWT构建器\n\t\t\t\t.setClaims(extraClaims) // 设置JWT令牌的声明(Claims)部分\n\t\t\t\t.setSubject(userDetails.getUsername()) // 设置JWT令牌的主题(Subject)部分\n\t\t\t\t.setIssuedAt(new Date(System.currentTimeMillis())) // 设置JWT令牌的签发时间\n\t\t\t\t.setExpiration(new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 24)) // 设置JWT令牌的过期时间(24小时)\n\t\t\t\t.signWith(getSignInKey(), SignatureAlgorithm.HS512) // 对JWT令牌进行签名\n\t\t\t\t.compact(); // 生成最终的JWT令牌字符串\n\t}\n\n\t/**\n\t * 生成Jwt令牌\n\t *\n\t * @param userDetails 用户详细信息\n\t * @return {@code String}\n\t */\n\tpublic String generateToken(UserDetails userDetails) {\n\t\treturn generateToken(new HashMap<>(), userDetails);\n\t}\n\n\t/**\n\t * 令牌是否有效\n\t *\n\t * @param token 令牌\n\t * @param userDetails 用户详细信息\n\t * @return boolean\n\t */\n\tpublic static boolean isTokenValid(String token, UserDetails userDetails) {\n\t\tfinal String username = extractUsername(token);\n\t\treturn (username.equals(userDetails.getUsername()) && !extractClaim(token, Claims::getExpiration).before(new Date()));\n\t}\n\n\t/**\n\t * 提取用户名\n\t *\n\t * @param token 令牌\n\t * @return {@code String}\n\t */\n\tpublic static String extractUsername(String token) {\n\t\treturn extractClaim(token, Claims::getSubject);\n\t}\n\n\n}"
},
{
"identifier": "Msg",
"path": "src/main/java/com/cloud/util/msg/Msg.java",
"snippet": "@Data\n@AllArgsConstructor\npublic class Msg<T> {\n\n\t// 状态码\n\tprivate Integer code;\n\n\t// 提示信息\n\tprivate String msg;\n\n\t// 返回给浏览器的数据\n\tprivate T data;\n\n\t// 接口请求时间\n\tprivate long timestamp;\n\n\tpublic Msg() {\n\t\tthis.timestamp = System.currentTimeMillis();\n\t}\n\n\t/**\n\t * 默认请求成功\n\t *\n\t * @return {@code Msg<?>}\n\t */\n\tpublic static Msg<?> success() {\n\t\tMsg<?> msg = new Msg<>();\n\t\tmsg.setCode(ResultCode.SUCCESS.getCode());\n\t\tmsg.setMsg(ResultCode.SUCCESS.getMsg());\n\t\treturn msg;\n\t}\n\n\t/**\n\t * 请求成功\n\t *\n\t * @param resultCode {@code ResultCode}\n\t * @return {@code Msg<?>}\n\t */\n\tpublic static Msg<?> success(ResultCode resultCode) {\n\t\tMsg<?> result = new Msg<>();\n\t\tresult.setCode(ResultCode.SUCCESS.getCode());\n\t\tresult.setMsg(ResultCode.SUCCESS.getMsg());\n\t\treturn result;\n\t}\n\n\t/**\n\t * 请求成功\n\t * 携带数据返回\n\t *\n\t * @param data 返回数据\n\t * @return {@code Msg<T>}\n\t */\n\tpublic static <T> Msg<T> success(T data) {\n\t\tMsg<T> msg = new Msg<>();\n\t\tmsg.setCode(ResultCode.SUCCESS.getCode());\n\t\tmsg.setMsg(ResultCode.SUCCESS.getMsg());\n\t\tmsg.setData(data);\n\t\treturn msg;\n\t}\n\n\t/**\n\t * 默认请求失败\n\t *\n\t * @return {@code Msg<?>}\n\t */\n\tpublic static Msg<?> fail() {\n\t\tMsg<?> msg = new Msg<>();\n\t\tmsg.setCode(ResultCode.FAILED.getCode());\n\t\tmsg.setMsg(ResultCode.FAILED.getMsg());\n\t\treturn msg;\n\t}\n\n\t/**\n\t * 定义请求失败\n\t *\n\t * @param resultCode {@code ResultCode}\n\t * @return {@code Msg<?>}\n\t */\n\tpublic static Msg<?> fail(ResultCode resultCode) {\n\t\tMsg<?> result = new Msg<>();\n\t\tresult.setCode(resultCode.getCode());\n\t\tresult.setMsg(resultCode.getMsg());\n\t\treturn result;\n\t}\n\n\t/**\n\t * 请求失败\n\t * 携带数据返回\n\t *\n\t * @param data 返回数据\n\t * @return {@code Msg<T>}\n\t */\n\tpublic static <T> Msg<T> fail(T data) {\n\t\tMsg<T> msg = new Msg<>();\n\t\tmsg.setCode(ResultCode.FAILED.getCode());\n\t\tmsg.setMsg(ResultCode.FAILED.getMsg());\n\t\tmsg.setData(data);\n\t\treturn msg;\n\t}\n\n\tpublic Msg(ResultCode resultCode) {\n\t\tthis.code = resultCode.getCode();\n\t\tthis.msg = resultCode.getMsg();\n\t\tthis.timestamp = System.currentTimeMillis();\n\t}\n\n\t/**\n\t * 自定义返回状态码、消息、数据\n\t *\n\t * @param resultCode {@code ResultCode}\n\t * @param data 数据\n\t */\n\tpublic Msg(ResultCode resultCode, T data) {\n\t\tthis.code = resultCode.getCode();\n\t\tthis.msg = resultCode.getMsg();\n\t\tthis.data = data;\n\t\tthis.timestamp = System.currentTimeMillis();\n\t}\n\n\tpublic static void returnMsg(HttpServletResponse response, ResultCode resultCode) throws IOException {\n\t\tresponse.setContentType(\"application/json;charset=utf-8\");\n\t\tServletOutputStream os = response.getOutputStream();\n\t\tString jsonString = JSON.toJSONString(new Msg<>(resultCode));\n\t\tos.write(jsonString.getBytes());\n\t\tos.flush();\n\t\tos.close();\n\t}\n}"
}
] | import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cloud.entity.Log;
import com.cloud.mapper.LogMapper;
import com.cloud.service.ILogService;
import com.cloud.util.HttpUtil;
import com.cloud.util.IPUtil;
import com.cloud.util.JwtUtil;
import com.cloud.util.annotation.OLog;
import com.cloud.util.msg.Msg;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import java.util.Arrays;
import java.util.Date;
import java.util.List; | 3,506 | package com.cloud.service.impl;
@Slf4j
@Service
@RequiredArgsConstructor | package com.cloud.service.impl;
@Slf4j
@Service
@RequiredArgsConstructor | public class LogServiceImpl extends ServiceImpl<LogMapper, Log> implements ILogService { | 2 | 2023-11-07 07:27:53+00:00 | 4k |
AbarcaJ/VisibilityToggle | src/dev/cleusgamer201/visibilitytoggle/Main.java | [
{
"identifier": "PlayerVisibilityChangedEvent",
"path": "src/dev/cleusgamer201/visibilitytoggle/api/PlayerVisibilityChangedEvent.java",
"snippet": "public class PlayerVisibilityChangedEvent extends Event {\n\n private static final HandlerList handler = new HandlerList();\n\n private final Player player;\n private final Visibility oldVisibility, newVisibility;\n\n public PlayerVisibilityChangedEvent(Player player, Visibility oldVisibility, Visibility newVisibility) {\n this.player = player;\n this.oldVisibility = oldVisibility;\n this.newVisibility = newVisibility;\n }\n\n public Player getPlayer() {\n return player;\n }\n\n public Visibility getOldVisibility() {\n return oldVisibility;\n }\n\n public Visibility getNewVisibility() {\n return newVisibility;\n }\n\n @Override\n public HandlerList getHandlers() {\n return handler;\n }\n}"
},
{
"identifier": "PlayerVisibilityUpdatedEvent",
"path": "src/dev/cleusgamer201/visibilitytoggle/api/PlayerVisibilityUpdatedEvent.java",
"snippet": "public class PlayerVisibilityUpdatedEvent extends Event {\n\n private static final HandlerList handler = new HandlerList();\n\n private final Player player;\n private final Visibility visibility;\n\n public PlayerVisibilityUpdatedEvent(Player player, Visibility visibility) {\n this.player = player;\n this.visibility = visibility;\n }\n\n public Player getPlayer() {\n return player;\n }\n\n public Visibility getVisibility() {\n return visibility;\n }\n\n @Override\n public HandlerList getHandlers() {\n return handler;\n }\n}"
},
{
"identifier": "Visibility",
"path": "src/dev/cleusgamer201/visibilitytoggle/api/Visibility.java",
"snippet": "public enum Visibility {\n\n\tSHOW_ALL, RANK_ONLY, HIDE_ALL;\n\n}"
},
{
"identifier": "Cache",
"path": "src/dev/cleusgamer201/visibilitytoggle/database/Cache.java",
"snippet": "public class Cache {\n\n private final Player player;\n private double lastUse = 0;\n private Visibility state = Visibility.SHOW_ALL;\n private boolean loaded = false;\n\n public Cache(Player player) {\n this.player = player;\n final String uuid = getUuid().toString();\n final String name = getName();\n Bukkit.getScheduler().runTaskLaterAsynchronously(Main.getInstance(), () -> {\n try {\n final ResultSet rs = Main.getInstance().getDbManager().executeQuery(\"SELECT * FROM VisibilityToggle WHERE Uuid = ?;\", uuid);\n if (rs.next()) {\n this.state = Visibility.valueOf(rs.getString(\"Visibility\").toUpperCase());\n rs.close();\n } else {\n rs.close();\n Main.getInstance().getDbManager().executeUpdate(\"INSERT INTO VisibilityToggle (Uuid, Visibility) VALUES (?, ?);\", uuid, state.name());\n }\n this.loaded = true;\n Bukkit.getScheduler().runTask(Main.getInstance(), () -> Bukkit.getPluginManager().callEvent(new CacheLoadEvent(this, player)));\n } catch (SQLException ex) {\n Utils.log(\"&4WARNING: &7\" + name + \"&c get state/insert error: &f\" + ex);\n }\n }, 3L);\n }\n\n public Player getPlayer() {\n return player;\n }\n\n public void setVisbility(Visibility value) {\n this.state = value;\n }\n\n public Visibility getVisibility() {\n return this.state;\n }\n\n public void setLastUse(double delay) {\n this.lastUse = (TimeUnit.MILLISECONDS.convert(System.nanoTime(), TimeUnit.NANOSECONDS) / 1000.0) + delay;\n }\n\n public double getLastUse() {\n return lastUse;\n }\n\n public UUID getUuid() {\n return player.getUniqueId();\n }\n\n public String getName() {\n return player.getName();\n }\n\n public boolean isLoaded() {\n return loaded;\n }\n}"
},
{
"identifier": "CacheLoadEvent",
"path": "src/dev/cleusgamer201/visibilitytoggle/database/CacheLoadEvent.java",
"snippet": "public class CacheLoadEvent extends Event {\n\n\tprivate final Cache cache;\n\tprivate final Player player;\n\t\n\tpublic CacheLoadEvent(final Cache cache, final Player player) {\n\t\tthis.cache = cache;\n\t\tthis.player = player;\n\t}\n\t\n\tpublic Player getPlayer() {\n\t\treturn this.player;\n\t}\n\t\n\tpublic Cache getCache() {\n\t\treturn this.cache;\n\t}\n\t\n\tprivate static final HandlerList handlers = new HandlerList();\n\tpublic HandlerList getHandlers() {\n\t return handlers;\n\t}\n\t \n\tpublic static HandlerList getHandlerList() {\n\t return handlers;\n\t}\n}"
},
{
"identifier": "DBManager",
"path": "src/dev/cleusgamer201/visibilitytoggle/database/DBManager.java",
"snippet": "public class DBManager implements Listener {\n\n private boolean shutdown = false;\n private final HashMap<Player, Cache> cached = new HashMap<>();\n private DB db;\n\n private final Main plugin;\n\n public DBManager(Main plugin) {\n this.plugin = plugin;\n load();\n }\n\n private void load() {\n final DBSettings.Builder builder = new DBSettings.Builder();\n final Config config = plugin.getConfig();\n if (config.getBoolean(\"MySQL.Enabled\")) {\n builder.host(config.getString(\"MySQL.Host\"));\n builder.port(config.getInt(\"MySQL.Port\"));\n builder.user(config.getString(\"MySQL.Username\"));\n builder.database(config.getString(\"MySQL.Database\"));\n builder.password(config.getString(\"MySQL.Password\"));\n builder.type(DBSettings.DBType.MYSQL);\n } else {\n builder.database(\"Database\");\n }\n db = new DB(builder.build());\n if (db.isConnected()) {\n db.executeUpdate(\"CREATE TABLE IF NOT EXISTS VisibilityToggle (Uuid VARCHAR(36), Visibility VARCHAR(10));\");\n } else {\n Utils.log(\"&cNo database connection detected disabling...\");\n Bukkit.getPluginManager().disablePlugin(plugin);\n return;\n }\n Bukkit.getPluginManager().registerEvents(this, plugin);\n }\n\n public void shutdown() {\n this.shutdown = true;\n if (db.isConnected()) {\n ExecutorService scheduler = Executors.newCachedThreadPool();\n for (List<Cache> data : splitCache(6)) {\n scheduler.execute(() -> data.forEach(DBManager.this::save));\n }\n scheduler.shutdown();\n }\n }\n\n public DB getDB() {\n return db;\n }\n\n public void executeUpdate(String query) {\n db.executeUpdate(query);\n }\n\n public ResultSet executeQuery(String query) {\n return db.executeQuery(query);\n }\n\n public void executeUpdate(String query, Object... values) {\n db.executeUpdate(query, values);\n }\n\n public ResultSet executeQuery(String query, Object... values) {\n return db.executeQuery(query, values);\n }\n\n public void makeCache(Player player) {\n if (!cached.containsKey(player)) {\n cached.put(player, new Cache(player));\n }\n }\n\n public Cache getCache(Player player) {\n makeCache(player);\n return cached.get(player);\n }\n\n public void removeCache(Player player) {\n cached.remove(player);\n }\n\n public void saveAsync() {\n cached.values().forEach(this::saveAsync);\n }\n\n public void save() {\n cached.values().forEach(this::save);\n }\n\n public Collection<List<Cache>> splitCache(int split) {\n AtomicInteger counter = new AtomicInteger(0);\n return cached.values().stream().collect(Collectors.partitioningBy(e -> counter.getAndIncrement() < cached.size() / split, Collectors.toList())).values();\n }\n\n public void saveAsync(Cache cache) {\n if (!cache.isLoaded()) {\n return;\n }\n Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> db.executeUpdate(\"UPDATE VisibilityToggle SET Visibility = ? WHERE Uuid = ?;\", cache.getVisibility().name(), cache.getUuid().toString()));\n }\n\n public void save(Cache cache) {\n if (!cache.isLoaded()) {\n return;\n }\n db.executeUpdate(\"UPDATE VisibilityToggle SET Visibility = ? WHERE Uuid = ?;\", cache.getVisibility().name(), cache.getUuid().toString());\n }\n\n public HashMap<Player, Cache> getAll() {\n return cached;\n }\n\n @EventHandler(priority = EventPriority.NORMAL)\n public void onJoin(PlayerJoinEvent e) {\n final Player p = e.getPlayer();\n makeCache(p);\n }\n\n @EventHandler(priority = EventPriority.LOWEST)\n public void onQuit(PlayerQuitEvent e) {\n final Player player = e.getPlayer();\n if (!this.shutdown) {\n final Cache cache = getCache(player);\n if (cache.isLoaded()) {\n saveAsync(cache);\n }\n removeCache(player);\n Bukkit.getScheduler().runTask(plugin, () -> Bukkit.getPluginManager().callEvent(new CacheUnloadEvent(cache, player)));\n }\n }\n}"
}
] | import dev.cleusgamer201.visibilitytoggle.api.PlayerVisibilityChangedEvent;
import dev.cleusgamer201.visibilitytoggle.api.PlayerVisibilityUpdatedEvent;
import dev.cleusgamer201.visibilitytoggle.api.Visibility;
import dev.cleusgamer201.visibilitytoggle.database.Cache;
import dev.cleusgamer201.visibilitytoggle.database.CacheLoadEvent;
import dev.cleusgamer201.visibilitytoggle.database.DBManager;
import dev.cleusgamer201.visibilitytoggle.utils.*;
import org.bukkit.Bukkit;
import org.bukkit.Sound;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.player.*;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.java.JavaPlugin;
import java.text.DecimalFormat;
import java.util.List;
import java.util.concurrent.TimeUnit; | 2,334 | package dev.cleusgamer201.visibilitytoggle;
public class Main extends JavaPlugin implements Listener {
private static Main instance;
public static Main getInstance() {
return instance;
}
private static String prefix;
public static String getPrefix() {
return prefix;
}
private Config config; | package dev.cleusgamer201.visibilitytoggle;
public class Main extends JavaPlugin implements Listener {
private static Main instance;
public static Main getInstance() {
return instance;
}
private static String prefix;
public static String getPrefix() {
return prefix;
}
private Config config; | private DBManager dbManager; | 5 | 2023-11-02 15:00:52+00:00 | 4k |
1711680493/SPay | app/src/main/java/shendi/pay/activity/TestActivity.java | [
{
"identifier": "Application",
"path": "app/src/main/java/shendi/pay/Application.java",
"snippet": "public class Application extends android.app.Application {\n\n /** 唯一实例 */\n private static Application instance;\n\n private static SLog log = SLog.getLogger(Application.class.getName());\n\n /** 数据库操作 */\n public static SQLiteUtil spaySql;\n\n /** 是否测试通知 */\n public boolean isTestNotify = false;\n\n public static final String NOTIFY_CHANNEL_ID_TEST = \"Test\";\n public static final String NOTIFY_CHANNEL_ID_PAY = \"Pay\";\n\n // 广播字符串\n public static final String RECEIVE_TEST = \"shendi.pay.receive.TestReceive\";\n\n // SP BaseStore 部分\n /** 获取配置信息的URL地址 */\n private String basicInfoUrl;\n /** 用于验证的密钥 */\n private String basicPriKey;\n /** 从网络上获取的配置信息 */\n private JSONObject basicInfo;\n\n @Override\n public void onCreate() {\n super.onCreate();\n instance = this;\n\n // 设置默认时区\n TimeZone.setDefault(TimeZone.getTimeZone(\"GMT+08:00\"));\n\n // 初始化基础信息\n SharedPreferences baseStore = getBaseStore();\n basicInfoUrl = baseStore.getString(\"infoUrl\", null);\n String basicInfoStr = baseStore.getString(\"info\", null);\n if (basicInfoStr != null) {\n try {\n basicInfo = JSON.parseObject(basicInfoStr);\n } catch (Exception e) {\n log.w(\"基础信息中 info 非JSONObject\");\n sendNotify(\"基础信息 info 非JSONObject\", basicInfoUrl);\n }\n }\n basicPriKey = baseStore.getString(\"priKey\", null);\n\n spaySql = SQLiteUtil.getInstance(this);\n }\n\n /** @return 唯一实例 */\n public static Application getInstance() {\n return instance;\n }\n\n public SharedPreferences getStore(String name) {\n return this.getSharedPreferences(name, MODE_PRIVATE);\n }\n\n /**\n {\n infoUrl : \"获取配置信息的URL地址\",\n priKey : \"用于验证的密钥\",\n // 从网络上获取的配置信息\n info : {}\n }\n */\n public SharedPreferences getBaseStore() {\n return getStore(\"base\");\n }\n\n /** 是否开通通知权限 */\n public boolean isNotificationEnabled(Activity context) {\n NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);\n return notificationManager.areNotificationsEnabled();\n }\n\n /** 检验是否开通通知权限,未开通则跳往开通 */\n public void checkNotify(Activity context) {\n if (!isNotificationEnabled(context)) {\n Toast.makeText(context, \"请开启通知权限\", Toast.LENGTH_SHORT).show();\n\n Intent intent;\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {\n String packageName = getPackageName();\n intent = new Intent(Settings.ACTION_APP_NOTIFICATION_SETTINGS);\n intent.putExtra(Settings.EXTRA_APP_PACKAGE, packageName);\n intent.putExtra(Settings.EXTRA_CHANNEL_ID, NOTIFY_CHANNEL_ID_TEST);\n } else {\n intent = new Intent(\"android.settings.APP_NOTIFICATION_SETTINGS\");\n intent.putExtra(\"app_package\", getPackageName());\n intent.putExtra(\"app_uid\", getApplicationInfo().uid);\n }\n context.startActivity(intent);\n }\n }\n\n public static void showToast(Activity context, String text, int duration) {\n new Thread(() -> {\n context.runOnUiThread(() -> {\n Toast.makeText(context, text, duration).show();\n });\n }).start();\n }\n\n /**\n * 发送通知.\n * @param title 通知标题\n * @param content 通知内容\n */\n public void sendNotify(String title, String content) {\n //获取NotifactionManager对象\n NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);\n\n // 适配8.0及以上,创建渠道\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {\n nm.createNotificationChannel(new NotificationChannel(Application.NOTIFY_CHANNEL_ID_TEST, Application.NOTIFY_CHANNEL_ID_TEST, NotificationManager.IMPORTANCE_HIGH));\n }\n\n //构建一个Notification\n Notification n = new Notification.Builder(this, Application.NOTIFY_CHANNEL_ID_TEST)\n .setSmallIcon(R.drawable.logo)\n .setContentTitle(title)\n .setContentText(content)\n .setWhen(System.currentTimeMillis())\n .build();\n nm.notify((int) (System.currentTimeMillis() % 10000), n);\n\n log.i(\"发送了通知,title=[\" + title + \"],content=[\" + content + \"]\");\n }\n\n\n // SP BaseStore 部分\n /**\n * 获取配置信息的URL地址\n * @param defVal 为空则默认值\n */\n public String getBasicInfoUrl(String defVal) {\n return basicInfoUrl == null ? defVal : basicInfoUrl;\n }\n /**\n * 设置配置信息的URL与URL对应的具体信息\n * @param infoUrl url地址\n * @param info 具体信息\n */\n public void setBasicInfoUrl(String infoUrl, JSONObject info) {\n getBaseStore().edit()\n .putString(\"infoUrl\", infoUrl)\n .putString(\"info\", info.toString())\n .apply();\n this.basicInfoUrl = infoUrl;\n this.basicInfo = info;\n }\n\n /** 用于验证的密钥 */\n public String getBasicPriKey(String defVal) {\n return basicPriKey == null ? defVal : basicPriKey;\n }\n /** 用于验证的密钥 */\n public void setBasicPriKey(String basicPriKey) {\n getBaseStore().edit()\n .putString(\"priKey\", basicPriKey)\n .apply();\n this.basicPriKey = basicPriKey;\n }\n\n /** 从网络上获取的配置信息 */\n public JSONObject getBasicInfo() {\n return basicInfo;\n }\n}"
},
{
"identifier": "SLog",
"path": "app/src/main/java/shendi/pay/SLog.java",
"snippet": "public class SLog {\n\n private String mTag;\n\n private SLog(String tag){\n mTag = tag;\n }\n\n public static SLog getLogger(String tag) {\n return new SLog(\"spay_\"+tag);\n }\n\n public void v(String msg){\n Log.v(mTag,msg);\n }\n\n public void d(String msg){\n Log.d(mTag,msg);\n }\n\n public void i(String msg){\n Log.i(mTag,msg);\n }\n\n public void w(String msg){\n Log.w(mTag,msg);\n }\n\n public void e(String msg){\n Log.e(mTag,msg);\n }\n\n}"
},
{
"identifier": "ApiUtil",
"path": "app/src/main/java/shendi/pay/util/ApiUtil.java",
"snippet": "public class ApiUtil {\n\n private static SLog log = SLog.getLogger(ApiUtil.class.getName());\n\n public static OkHttpClient okhttp = new OkHttpClient();\n\n /** 回调接口 */\n public interface Callback {\n\n /**\n * 回调函数.\n * @param data api调用执行的结果\n */\n void callback(JSONObject data);\n\n }\n\n /**\n * 获取使用需要的基本配置.\n * @param url 获取配置的地址\n * @param success 成功的回调\n * @param fail 失败的回调\n */\n public static void baseConfig(String url, Callback success, Callback fail) {\n JSONObject obj = new JSONObject();\n obj.put(\"url\", url);\n obj.put(\"success\", success);\n obj.put(\"fail\", fail);\n\n call(obj);\n }\n\n /**\n * 调用支付回调接口.\n * @param url 支付回调地址\n * @param priKey 密钥\n * @param amount 支付金额,单位分\n * @param type 支付类型\n * @param success 成功的回调\n * @param fail 失败的回调\n */\n public static void pay(String url, String priKey, int amount, String type, Callback success, Callback fail) {\n pay(url, priKey, amount, type, System.currentTimeMillis(), success, fail);\n }\n\n /**\n * 调用支付回调接口.\n * @param url 支付回调地址\n * @param priKey 密钥\n * @param amount 支付金额,单位分\n * @param type 支付类型\n * @param time 时间戳\n * @param success 成功的回调\n * @param fail 失败的回调\n */\n public static void pay(String url, String priKey, int amount, String type, long time, Callback success, Callback fail) {\n JSONObject obj = new JSONObject();\n obj.put(\"url\", url);\n obj.put(\"type\", \"POST\");\n JSONObject param = new JSONObject();\n param.put(\"amount\", amount);\n param.put(\"type\", type);\n param.put(\"priKey\", priKey);\n param.put(\"time\", time);\n obj.put(\"param\", param);\n obj.put(\"success\", success);\n obj.put(\"fail\", fail);\n\n call(obj);\n }\n\n /**\n * 调用api,参考js的ajax,其中obj的某些参数不想被修改则增加一个新参数为 is当前参数名(驼峰式),例如不想修改url,那么 isUrl = true\n * 其中失败的回调,errMsg代表错误信息\n * @param obj 参数\n */\n public static void call(JSONObject obj) {\n new Thread(() -> {\n try {\n String url = obj.getString(\"url\");\n String type = obj.getString(\"type\");\n JSONObject param = obj.getJSONObject(\"param\");\n JSONObject heads = obj.getJSONObject(\"heads\");\n Integer timeout = obj.getInteger(\"timeout\");\n\n if (type == null) type = \"GET\";\n if (heads == null) heads = new JSONObject();\n if (timeout == null) timeout = 5000;\n\n StringBuilder paramStr = new StringBuilder();\n if (param != null) {\n for (Map.Entry<String, Object> kv : param.entrySet()) {\n if (kv.getValue() == null) continue;\n paramStr.append(\"&\").append(kv.getKey()).append(\"=\").append(URLEncoder.encode(kv.getValue().toString(), \"UTF-8\"));\n }\n if (paramStr.length() != 0) paramStr.deleteCharAt(0);\n }\n\n boolean isPost = \"POST\".equalsIgnoreCase(type);\n if (!isPost) {\n if (param != null) {\n paramStr.insert(0, '?');\n // 非post将数据放在url\n url += paramStr.toString();\n }\n } else {\n heads.put(\"Content-Type\", \"application/x-www-form-urlencoded\");\n heads.put(\"Content-Length\", paramStr.toString());\n }\n\n log.i(type + \" \" + url + \" [\" + paramStr + \"]\");\n\n // 创建请求\n Request.Builder reqBuild = new Request.Builder().url(url);\n\n // 设置请求头\n for (Map.Entry<String, Object> kv : heads.entrySet()) {\n reqBuild.header(kv.getKey(), kv.getValue().toString());\n }\n\n if (isPost) {\n reqBuild.post(RequestBody.create(paramStr.toString().getBytes()));\n } else {\n switch (type) {\n case \"GET\": reqBuild.get(); break;\n case \"head\" : reqBuild.head(); break;\n }\n }\n\n Call call = okhttp.newCall(reqBuild.build());\n Response response = call.execute();\n ResponseBody body = response.body();\n byte[] data = body.bytes();\n log.i(url + \" OK, Data Len=\" + data.length);\n\n // 回调\n Callback success = obj.getObject(\"success\", Callback.class);\n JSONObject result = null;\n if (!obj.containsKey(\"isSuccess\")) {\n result = JSONObject.parseObject(new String(data));\n } else {\n result = new JSONObject();\n result.put(\"data\", data);\n }\n\n if (success != null) success.callback(result);\n } catch (Exception e) {\n e.printStackTrace();\n log.e(\"api call error: \" + e.getMessage());\n\n // 有error则调用error\n Callback fail = obj.getObject(\"fail\", Callback.class);\n\n if (fail != null) {\n JSONObject error = new JSONObject();\n error.put(\"err\", e);\n error.put(\"errMsg\", e.getMessage());\n\n fail.callback(error);\n }\n }\n }).start();\n }\n\n}"
}
] | import android.app.Activity;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import java.util.Date;
import shendi.pay.Application;
import shendi.pay.R;
import shendi.pay.SLog;
import shendi.pay.util.ApiUtil; | 3,569 | package shendi.pay.activity;
/**
* 测试.
* 创建时间:2023/11/8
* @author Shendi
*/
public class TestActivity extends AppCompatActivity {
private static SLog log = SLog.getLogger(TestActivity.class.getName());
/** 广播接收器 */
private TestReceive receive;
// 基础信息接口
private EditText testIBaseUrlEdit;
// 支付回调接口
private EditText testIPayUrlEdit,
testIPayPriKeyEdit,
testIPayAmountEdit,
testIPayTypeEdit;
// 通知测试
private EditText testNotifyTitleEdit,
testNotifyContentEdit;
private ListView testNotifyList;
private ArrayAdapter<String> testNotifyListAdapter;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
getSupportActionBar().setTitle(R.string.bar_test);
// 启用ActionBar并显示返回箭头
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
initUI();
//注册广播
receive = new TestReceive();
registerReceiver(receive, new IntentFilter(Application.RECEIVE_TEST));
}
private void initUI() {
// 基础信息接口
testIBaseUrlEdit = findViewById(R.id.testIBaseUrlEdit);
findViewById(R.id.testIBaseBtn).setOnClickListener((v) -> { | package shendi.pay.activity;
/**
* 测试.
* 创建时间:2023/11/8
* @author Shendi
*/
public class TestActivity extends AppCompatActivity {
private static SLog log = SLog.getLogger(TestActivity.class.getName());
/** 广播接收器 */
private TestReceive receive;
// 基础信息接口
private EditText testIBaseUrlEdit;
// 支付回调接口
private EditText testIPayUrlEdit,
testIPayPriKeyEdit,
testIPayAmountEdit,
testIPayTypeEdit;
// 通知测试
private EditText testNotifyTitleEdit,
testNotifyContentEdit;
private ListView testNotifyList;
private ArrayAdapter<String> testNotifyListAdapter;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
getSupportActionBar().setTitle(R.string.bar_test);
// 启用ActionBar并显示返回箭头
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
initUI();
//注册广播
receive = new TestReceive();
registerReceiver(receive, new IntentFilter(Application.RECEIVE_TEST));
}
private void initUI() {
// 基础信息接口
testIBaseUrlEdit = findViewById(R.id.testIBaseUrlEdit);
findViewById(R.id.testIBaseBtn).setOnClickListener((v) -> { | ApiUtil.baseConfig(testIBaseUrlEdit.getText().toString(), (res) -> { | 2 | 2023-11-09 14:00:45+00:00 | 4k |
Bergerk1/Big-Data-Analytics | src/main/java/de/ddm/Main.java | [
{
"identifier": "Guardian",
"path": "src/main/java/de/ddm/actors/Guardian.java",
"snippet": "public class Guardian extends AbstractBehavior<Guardian.Message> {\n\n\t////////////////////\n\t// Actor Messages //\n\t////////////////////\n\n\tpublic interface Message extends AkkaSerializable {\n\t}\n\n\t@NoArgsConstructor\n\tpublic static class StartMessage implements Message {\n\t\tprivate static final long serialVersionUID = -6896669928271349802L;\n\t}\n\n\t@Getter\n\t@NoArgsConstructor\n\t@AllArgsConstructor\n\tpublic static class ShutdownMessage implements Message {\n\t\tprivate static final long serialVersionUID = 7516129288777469221L;\n\t\tprivate ActorRef<Message> initiator;\n\t}\n\n\t@Getter\n\t@NoArgsConstructor\n\t@AllArgsConstructor\n\tpublic static class ReceptionistListingMessage implements Message {\n\t\tprivate static final long serialVersionUID = 2336368568740749020L;\n\t\tReceptionist.Listing listing;\n\t}\n\n\t////////////////////////\n\t// Actor Construction //\n\t////////////////////////\n\n\tpublic static final String DEFAULT_NAME = \"userGuardian\";\n\n\tpublic static final ServiceKey<Guardian.Message> guardianService = ServiceKey.create(Guardian.Message.class, DEFAULT_NAME + \"Service\");\n\n\tpublic static Behavior<Message> create() {\n\t\treturn Behaviors.setup(\n\t\t\t\tcontext -> Behaviors.withTimers(timers -> new Guardian(context, timers)));\n\t}\n\n\tprivate Guardian(ActorContext<Message> context, TimerScheduler<Message> timers) {\n\t\tsuper(context);\n\n\t\tthis.timers = timers;\n\n\t\tthis.reaper = context.spawn(Reaper.create(), Reaper.DEFAULT_NAME);\n\t\tthis.master = this.isMaster() ? context.spawn(Master.create(), Master.DEFAULT_NAME) : null;\n\t\tthis.worker = context.spawn(Worker.create(), Worker.DEFAULT_NAME);\n\n\t\tcontext.getSystem().receptionist().tell(Receptionist.register(guardianService, context.getSelf()));\n\n\t\tfinal ActorRef<Receptionist.Listing> listingResponseAdapter = context.messageAdapter(Receptionist.Listing.class, ReceptionistListingMessage::new);\n\t\tcontext.getSystem().receptionist().tell(Receptionist.subscribe(guardianService, listingResponseAdapter));\n\t}\n\n\tprivate boolean isMaster() {\n\t\treturn SystemConfigurationSingleton.get().getRole().equals(SystemConfiguration.MASTER_ROLE);\n\t}\n\n\t/////////////////\n\t// Actor State //\n\t/////////////////\n\n\tprivate final TimerScheduler<Message> timers;\n\n\tprivate Set<ActorRef<Message>> userGuardians = new HashSet<>();\n\n\tprivate final ActorRef<Reaper.Message> reaper;\n\tprivate ActorRef<Master.Message> master;\n\tprivate ActorRef<Worker.Message> worker;\n\n\t////////////////////\n\t// Actor Behavior //\n\t////////////////////\n\n\t@Override\n\tpublic Receive<Message> createReceive() {\n\t\treturn newReceiveBuilder()\n\t\t\t\t.onMessage(StartMessage.class, this::handle)\n\t\t\t\t.onMessage(ShutdownMessage.class, this::handle)\n\t\t\t\t.onMessage(ReceptionistListingMessage.class, this::handle)\n\t\t\t\t.build();\n\t}\n\n\tprivate Behavior<Message> handle(StartMessage message) {\n\t\tif (this.master != null)\n\t\t\tthis.master.tell(new Master.StartMessage());\n\t\treturn this;\n\t}\n\n\tprivate Behavior<Message> handle(ShutdownMessage message) {\n\t\tActorRef<Message> self = this.getContext().getSelf();\n\n\t\tif ((message.getInitiator() != null) || this.isClusterDown()) {\n\t\t\tthis.shutdown();\n\t\t} else {\n\t\t\tfor (ActorRef<Message> userGuardian : this.userGuardians)\n\t\t\t\tif (!userGuardian.equals(self))\n\t\t\t\t\tuserGuardian.tell(new ShutdownMessage(self));\n\n\t\t\tif (!this.timers.isTimerActive(\"ShutdownReattempt\"))\n\t\t\t\tthis.timers.startTimerAtFixedRate(\"ShutdownReattempt\", message, Duration.ofSeconds(5), Duration.ofSeconds(5));\n\t\t}\n\t\treturn this;\n\t}\n\n\tprivate boolean isClusterDown() {\n\t\treturn this.userGuardians.isEmpty() || (this.userGuardians.contains(this.getContext().getSelf()) && this.userGuardians.size() == 1);\n\t}\n\n\tprivate void shutdown() {\n\t\tif (this.worker != null) {\n\t\t\tthis.worker.tell(new Worker.ShutdownMessage());\n\t\t\tthis.worker = null;\n\t\t}\n\t\tif (this.master != null) {\n\t\t\tthis.master.tell(new Master.ShutdownMessage());\n\t\t\tthis.master = null;\n\t\t}\n\t}\n\n\tprivate Behavior<Message> handle(ReceptionistListingMessage message) {\n\t\tthis.userGuardians = message.getListing().getServiceInstances(Guardian.guardianService);\n\n\t\tif (this.timers.isTimerActive(\"ShutdownReattempt\") && this.isClusterDown())\n\t\t\tthis.shutdown();\n\n\t\treturn this;\n\t}\n}"
},
{
"identifier": "Command",
"path": "src/main/java/de/ddm/configuration/Command.java",
"snippet": "public abstract class Command {\n\n\tabstract int getDefaultPort();\n\n\t@Parameter(names = {\"-h\", \"--host\"}, description = \"This machine's host name or IP that we use to bind this application against\", required = false)\n\tString host = SystemConfigurationSingleton.get().getHost();\n\n\t@Parameter(names = {\"-p\", \"--port\"}, description = \"This machines port that we use to bind this application against\", required = false)\n\tint port = this.getDefaultPort();\n\n\t@Parameter(names = {\"-w\", \"--numWorkers\"}, description = \"The number of workers (indexers/validators) to start locally; should be at least one if the algorithm is started standalone (otherwise there are no workers to run the discovery)\", required = false)\n\tint numWorkers = SystemConfigurationSingleton.get().getNumWorkers();\n\n\tpublic static void applyOn(String[] args) {\n\t\tCommandMaster commandMaster = new CommandMaster();\n\t\tCommandWorker commandWorker = new CommandWorker();\n\t\tJCommander jCommander = JCommander.newBuilder()\n\t\t\t\t.addCommand(SystemConfiguration.MASTER_ROLE, commandMaster)\n\t\t\t\t.addCommand(SystemConfiguration.WORKER_ROLE, commandWorker)\n\t\t\t\t.build();\n\n\t\ttry {\n\t\t\tjCommander.parse(args);\n\n\t\t\tif (jCommander.getParsedCommand() == null)\n\t\t\t\tthrow new ParameterException(\"No command given.\");\n\n\t\t\tswitch (jCommander.getParsedCommand()) {\n\t\t\t\tcase SystemConfiguration.MASTER_ROLE:\n\t\t\t\t\tSystemConfigurationSingleton.get().update(commandMaster);\n\t\t\t\t\tInputConfigurationSingleton.get().update(commandMaster);\n\t\t\t\t\tbreak;\n\t\t\t\tcase SystemConfiguration.WORKER_ROLE:\n\t\t\t\t\tSystemConfigurationSingleton.get().update(commandWorker);\n\t\t\t\t\tInputConfigurationSingleton.set(null);\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tthrow new AssertionError();\n\t\t\t}\n\t\t} catch (ParameterException e) {\n\t\t\tSystem.out.printf(\"Could not parse args: %s\\n\", e.getMessage());\n\t\t\tjCommander.usage();\n\t\t\tSystem.exit(1);\n\t\t}\n\t}\n}"
},
{
"identifier": "SystemConfiguration",
"path": "src/main/java/de/ddm/configuration/SystemConfiguration.java",
"snippet": "@Data\npublic class SystemConfiguration {\n\n\tpublic static final String MASTER_ROLE = \"master\";\n\tpublic static final String WORKER_ROLE = \"worker\";\n\n\tpublic static final int DEFAULT_MASTER_PORT = 7877;\n\tpublic static final int DEFAULT_WORKER_PORT = 7879;\n\n\tprivate String role = MASTER_ROLE; // This machine's role in the cluster.\n\n\tprivate String host = getDefaultHost(); // This machine's host name or IP that we use to bind this application against\n\tprivate int port = DEFAULT_MASTER_PORT; // This machines port that we use to bind this application against\n\n\tprivate String masterHost = getDefaultHost(); // The host name or IP of the master; if this is a master, masterHost = host\n\tprivate int masterPort = DEFAULT_MASTER_PORT; // The port of the master; if this is a master, masterPort = port\n\n\tprivate String actorSystemName = \"ddm\"; // The name of this application\n\n\tprivate int numWorkers = 2; // The number of workers to start locally; should be at least one if the algorithm is started standalone (otherwise there are no workers to run the application)\n\n\tprivate boolean startPaused = false; // Wait for some console input to start; useful, if we want to wait manually until all ActorSystems in the cluster are started (e.g. to avoid work stealing effects in performance evaluations)\n\n\tprivate boolean hardMode = false;\t\t\t\t\t// Solve the hard version of the task\n\n\tprivate static String getDefaultHost() {\n\t\ttry {\n\t\t\treturn InetAddress.getLocalHost().getHostAddress();\n\t\t} catch (UnknownHostException e) {\n\t\t\treturn \"localhost\";\n\t\t}\n\t}\n\n\tpublic void update(CommandMaster commandMaster) {\n\t\tthis.role = MASTER_ROLE;\n\t\tthis.host = commandMaster.host;\n\t\tthis.port = commandMaster.port;\n\t\tthis.masterHost = commandMaster.host;\n\t\tthis.masterPort = commandMaster.port;\n\t\tthis.numWorkers = commandMaster.numWorkers;\n\t\tthis.startPaused = commandMaster.startPaused;\n\t\tthis.hardMode = commandMaster.hardMode;\n\t}\n\n\tpublic void update(CommandWorker commandWorker) {\n\t\tthis.role = WORKER_ROLE;\n\t\tthis.host = commandWorker.host;\n\t\tthis.port = commandWorker.port;\n\t\tthis.masterHost = commandWorker.masterhost;\n\t\tthis.masterPort = commandWorker.masterport;\n\t\tthis.numWorkers = commandWorker.numWorkers;\n\t}\n\n\tpublic Config toAkkaConfig() {\n\t\treturn ConfigFactory.parseString(\"\" +\n\t\t\t\t\"akka.remote.artery.canonical.hostname = \\\"\" + this.host + \"\\\"\\n\" +\n\t\t\t\t\"akka.remote.artery.canonical.port = \" + this.port + \"\\n\" +\n\t\t\t\t\"akka.cluster.roles = [\" + this.role + \"]\\n\" +\n\t\t\t\t\"akka.cluster.seed-nodes = [\\\"akka://\" + this.actorSystemName + \"@\" + this.masterHost + \":\" + this.masterPort + \"\\\"]\")\n\t\t\t\t.withFallback(ConfigFactory.load(\"application\"));\n\t}\n\n\tpublic Config toAkkaTestConfig() {\n\t\treturn ConfigFactory.parseString(\"\" +\n\t\t\t\t\"akka.remote.artery.canonical.hostname = \\\"\" + this.host + \"\\\"\\n\" +\n\t\t\t\t\"akka.remote.artery.canonical.port = \" + this.port + \"\\n\" +\n\t\t\t\t\"akka.cluster.roles = [\" + this.role + \"]\")\n\t\t\t\t.withFallback(ConfigFactory.load(\"application\"));\n\t}\n}"
},
{
"identifier": "SystemConfigurationSingleton",
"path": "src/main/java/de/ddm/singletons/SystemConfigurationSingleton.java",
"snippet": "public class SystemConfigurationSingleton {\n\n\tprivate static SystemConfiguration singleton = new SystemConfiguration();\n\n\tpublic static SystemConfiguration get() {\n\t\treturn singleton;\n\t}\n\n\tpublic static void set(SystemConfiguration instance) {\n\t\tsingleton = instance;\n\t}\n}"
}
] | import akka.actor.typed.ActorSystem;
import de.ddm.actors.Guardian;
import de.ddm.configuration.Command;
import de.ddm.configuration.SystemConfiguration;
import de.ddm.singletons.SystemConfigurationSingleton;
import java.io.IOException; | 2,599 | package de.ddm;
public class Main {
public static void main(String[] args) { | package de.ddm;
public class Main {
public static void main(String[] args) { | Command.applyOn(args); | 1 | 2023-11-01 11:57:53+00:00 | 4k |
20dinosaurs/BassScript | src/main/java/miro/bassscript/BassScript.java | [
{
"identifier": "BaritoneHandler",
"path": "src/main/java/miro/bassscript/baritone/BaritoneHandler.java",
"snippet": "public class BaritoneHandler {\n private final BassScript bassScript;\n\n public BaritoneHandler(BassScript bassScript) {\n this.bassScript = bassScript;\n }\n\n public void initSettings() {\n getSettings().allowInventory.value = true;\n getSettings().autoTool.value = true;\n getSettings().itemSaver.value = true;\n\n getSettings().blockPlacementPenalty.value = 14D;\n getSettings().walkOnWaterOnePenalty.value = 4D;\n getSettings().allowWaterBucketFall.value = true;\n\n getSettings().allowDiagonalDescend.value = true;\n getSettings().allowDiagonalAscend.value = true;\n getSettings().allowParkour.value = true;\n getSettings().allowParkourPlace.value = true;\n\n getSettings().acceptableThrowawayItems.value = List.of(\n Blocks.DIRT.asItem(),\n Blocks.COBBLESTONE.asItem(),\n Blocks.COBBLED_DEEPSLATE.asItem(),\n Blocks.NETHERRACK.asItem(),\n Blocks.STONE.asItem(),\n Blocks.END_STONE.asItem()\n );\n\n // newish blocks\n getSettings().blocksToAvoid.value = List.of(\n Blocks.FLOWERING_AZALEA, Blocks.AZALEA,\n Blocks.POWDER_SNOW,\n Blocks.BIG_DRIPLEAF, Blocks.BIG_DRIPLEAF_STEM,\n Blocks.CAVE_VINES, Blocks.CAVE_VINES_PLANT,\n Blocks.TWISTING_VINES, Blocks.TWISTING_VINES_PLANT, Blocks.WEEPING_VINES, Blocks.WEEPING_VINES_PLANT,\n Blocks.SWEET_BERRY_BUSH,\n Blocks.WARPED_ROOTS, Blocks.CRIMSON_ROOTS,\n Blocks.SMALL_AMETHYST_BUD, Blocks.MEDIUM_AMETHYST_BUD, Blocks.LARGE_AMETHYST_BUD, Blocks.AMETHYST_CLUSTER,\n Blocks.SCULK, Blocks.SCULK_VEIN, Blocks.SCULK_SENSOR, Blocks.SCULK_SHRIEKER, Blocks.SCULK_CATALYST\n );\n\n getSettings().blocksToAvoidBreaking.value = List.of(\n Blocks.CRAFTING_TABLE, Blocks.FURNACE, Blocks.CHEST, Blocks.TRAPPED_CHEST,\n Blocks.SCULK, Blocks.SCULK_VEIN, Blocks.SCULK_SENSOR, Blocks.SCULK_SHRIEKER, Blocks.SCULK_CATALYST\n );\n\n getSettings().avoidance.value = true;\n getSettings().mobAvoidanceRadius.value = 6;\n getSettings().mobSpawnerAvoidanceRadius.value = 14;\n getSettings().mobAvoidanceCoefficient.value = 1.3;\n\n getSettings().rightClickContainerOnArrival.value = false;\n\n getSettings().renderPathAsLine.value = true;\n // getSettings().freeLook.value = false;\n // getSettings().randomLooking.value = 0D;\n // getSettings().randomLooking113.value = 0D;\n // getSettings().smoothLook.value = false;\n\n getSettings().mineScanDroppedItems.value = true;\n getSettings().mineDropLoiterDurationMSThanksLouca.value = 100L;\n\n getSettings().chatDebug.value = true;\n }\n\n public IBaritone getBaritone() {\n if (bassScript.getPlayer() == null) {\n return BaritoneAPI.getProvider().getPrimaryBaritone();\n }\n return BaritoneAPI.getProvider().getBaritoneForPlayer(bassScript.getPlayer());\n }\n\n public Settings getSettings() {\n return BaritoneAPI.getSettings();\n }\n}"
},
{
"identifier": "MineBlocksFunction",
"path": "src/main/java/miro/bassscript/functions/MineBlocksFunction.java",
"snippet": "public class MineBlocksFunction extends Function {\n private final IItemCollection items;\n private final boolean blocksGiven;\n private Set<Block> blocks;\n private IItemCollection prevUnmetItems;\n\n public MineBlocksFunction(BassScript bassScript, FunctionStack functionStack, IItemCollection items, Set<Block> blocks) {\n super(bassScript, functionStack);\n this.items = items;\n this.blocks = blocks;\n blocksGiven = true;\n }\n\n public MineBlocksFunction(BassScript bassScript, FunctionStack functionStack, IItemCollection items) {\n super(bassScript, functionStack);\n this.items = items;\n this.blocks = ItemUtils.blocksFromItems(items.getItems());\n blocksGiven = false;\n }\n\n @Override\n protected void onTick() {\n if (!blocksGiven) {\n IItemCollection unmetItems = items.getItemsUnmetBy(player.getInventory());\n\n if (!unmetItems.equals(prevUnmetItems)) {\n prevUnmetItems = unmetItems;\n blocks = ItemUtils.blocksFromItems(unmetItems.getItems());\n tryPause();\n resume();\n }\n }\n }\n\n @Override\n public void start() {\n bassScript.getBaritone().getPathingBehavior().cancelEverything();\n resume();\n }\n\n @Override\n public void stop() {\n tryPause();\n }\n\n @Override\n public boolean tryPause() {\n return bassScript.getBaritone().getPathingBehavior().cancelEverything();\n }\n\n @Override\n public void forcePause() {\n bassScript.getBaritone().getPathingBehavior().forceCancel();\n }\n\n @Override\n protected void pause() {}\n\n @Override\n public void resume() {\n bassScript.getBaritone().getMineProcess().mine(blocks.toArray(new Block[0]));\n }\n\n @Override\n public boolean isFinished() {\n return items.isMetBy(player.getInventory());\n }\n\n @Override\n public Double getEstimatedTicks() {\n return super.getEstimatedTicks();\n }\n\n @Override\n public String name() {\n return \"MineBlocks\";\n }\n\n @Override\n public String desc() {\n return \"Mining: \" + blocks.toString();\n }\n}"
},
{
"identifier": "FunctionStack",
"path": "src/main/java/miro/bassscript/functionutils/FunctionStack.java",
"snippet": "public class FunctionStack {\n private BassScript bassScript;\n private Deque<Function> stack = new ArrayDeque<>();\n private Queue<Function> functionQueue = new ArrayDeque<>();\n private boolean isPaused;\n\n public FunctionStack(BassScript bassScript, boolean isPaused) {\n this.isPaused = isPaused;\n this.bassScript = bassScript;\n }\n\n public FunctionStack(BassScript bassScript) {\n this(bassScript, true);\n }\n\n public void addFunction(Function function) {\n function.init();\n functionQueue.add(function);\n }\n\n private void removeFunction() {\n stack.pop();\n if (!isPaused && stack.peek() != null) {\n stack.peek().resume();\n }\n }\n\n private void pushToStack(Function function) {\n stack.push(function);\n bassScript.getLogger().logInfo(\"Added function \" + function.name());\n }\n\n public void tick() {\n if (!isPaused) {\n if (stack.peek() != null) {\n stack.peek().tick();\n }\n }\n\n if (stack.peek() != null && stack.peek().isFinished()) {\n removeFunction();\n }\n\n if (!functionQueue.isEmpty()) {\n if (stack.peek() != null) {\n if (stack.peek().tryPause()) {\n pushToStack(functionQueue.remove());\n }\n } else {\n pushToStack(functionQueue.remove());\n }\n }\n }\n\n public boolean tryPause() {\n if (stack.peek() != null) {\n isPaused = stack.peek().tryPause();\n } else {\n isPaused = true;\n }\n return isPaused;\n }\n\n public void forcePause() {\n isPaused = true;\n if (stack.peek() != null) {\n stack.peek().forcePause();\n }\n }\n\n public void resume() {\n isPaused = false;\n if (stack.peek() != null) {\n stack.peek().resume();\n }\n }\n}"
},
{
"identifier": "SimpleItemCollection",
"path": "src/main/java/miro/bassscript/item/SimpleItemCollection.java",
"snippet": "public class SimpleItemCollection implements IItemCollection {\n private Map<Item, Integer> items = new LinkedHashMap<>();\n\n public SimpleItemCollection() {}\n\n public SimpleItemCollection(Item item, int count) {\n items.put(item, count);\n }\n\n public SimpleItemCollection(Item item) {\n items.put(item, 1);\n }\n\n @Override\n public boolean isMetBy(Inventory inv) {\n for (Map.Entry<Item, Integer> itemEntry : items.entrySet()) {\n // If item count in inventory is not >= requested count\n if (!(ItemUtils.countItems(inv, itemEntry.getKey()) >= itemEntry.getValue())) {\n return false;\n }\n }\n return true;\n }\n\n @Override\n public IItemCollection getItemsUnmetBy(Inventory inv) {\n SimpleItemCollection unmetItems = new SimpleItemCollection();\n for (Map.Entry<Item, Integer> itemEntry : items.entrySet()) {\n int count = ItemUtils.countItems(inv, itemEntry.getKey());\n if (!(count >= itemEntry.getValue())) {\n unmetItems.addItem(itemEntry.getKey(), itemEntry.getValue() - count);\n }\n }\n\n return unmetItems;\n }\n\n public void addItem(Item item, int count) {\n items.put(item, count);\n }\n\n public void addItem(Item item) {\n items.put(item, 1);\n }\n\n @Override\n public Set<Item> getItems() {\n return items.keySet();\n }\n\n public Map<Item, Integer> getItemMap() {\n return items;\n }\n\n @Override\n public boolean equals(Object o) {\n if (o == this) {\n return true;\n }\n if (o instanceof SimpleItemCollection) {\n return items.equals(((SimpleItemCollection) o).getItemMap());\n }\n return false;\n }\n\n @Override\n public int hashCode() {\n return items.hashCode();\n }\n\n @Override\n public String toString() {\n return items.toString();\n }\n}"
}
] | import baritone.api.IBaritone;
import miro.bassscript.baritone.BaritoneHandler;
import miro.bassscript.functions.MineBlocksFunction;
import miro.bassscript.functionutils.FunctionStack;
import miro.bassscript.item.SimpleItemCollection;
import net.fabricmc.api.ClientModInitializer;
import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientLifecycleEvents;
import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientTickEvents;
import net.fabricmc.fabric.api.client.message.v1.ClientSendMessageEvents;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.network.ClientPlayerEntity;
import net.minecraft.client.world.ClientWorld;
import net.minecraft.item.Items; | 2,663 | package miro.bassscript;
public class BassScript implements ClientModInitializer {
private BSLogger logger; | package miro.bassscript;
public class BassScript implements ClientModInitializer {
private BSLogger logger; | private FunctionStack functionStack; | 2 | 2023-11-08 05:28:18+00:00 | 4k |
hlysine/create_power_loader | src/main/java/com/hlysine/create_power_loader/CPLBlockEntityTypes.java | [
{
"identifier": "EmptyChunkLoaderBlockEntity",
"path": "src/main/java/com/hlysine/create_power_loader/content/emptychunkloader/EmptyChunkLoaderBlockEntity.java",
"snippet": "@MethodsReturnNonnullByDefault\npublic class EmptyChunkLoaderBlockEntity extends KineticBlockEntity {\n\n public EmptyChunkLoaderBlockEntity(BlockEntityType<?> type, BlockPos pos, BlockState state) {\n super(type, pos, state);\n }\n}"
},
{
"identifier": "EmptyChunkLoaderRenderer",
"path": "src/main/java/com/hlysine/create_power_loader/content/emptychunkloader/EmptyChunkLoaderRenderer.java",
"snippet": "public class EmptyChunkLoaderRenderer extends KineticBlockEntityRenderer<EmptyChunkLoaderBlockEntity> {\n\n public EmptyChunkLoaderRenderer(BlockEntityRendererProvider.Context context) {\n super(context);\n }\n\n @Override\n protected void renderSafe(EmptyChunkLoaderBlockEntity be, float partialTicks, PoseStack ms, MultiBufferSource buffer,\n int light, int overlay) {\n\n Direction direction = be.getBlockState()\n .getValue(FACING);\n VertexConsumer vb = buffer.getBuffer(RenderType.cutoutMipped());\n\n SuperByteBuffer shaftHalf =\n CachedBufferer.partialFacing(AllPartialModels.SHAFT_HALF, be.getBlockState(), direction.getOpposite());\n\n standardKineticRotationTransform(shaftHalf, be, light).renderInto(ms, vb);\n }\n}"
},
{
"identifier": "AndesiteChunkLoaderBlockEntity",
"path": "src/main/java/com/hlysine/create_power_loader/content/andesitechunkloader/AndesiteChunkLoaderBlockEntity.java",
"snippet": "@MethodsReturnNonnullByDefault\npublic class AndesiteChunkLoaderBlockEntity extends AbstractChunkLoaderBlockEntity {\n private static final int LOADING_RANGE = 1;\n\n public AndesiteChunkLoaderBlockEntity(BlockEntityType<?> type, BlockPos pos, BlockState state) {\n super(type, pos, state, LoaderType.ANDESITE);\n }\n\n @Override\n public int getLoadingRange() {\n return LOADING_RANGE;\n }\n\n @Override\n protected double getSpeedMultiplierConfig() {\n return CPLConfigs.server().andesiteSpeedMultiplier.get();\n }\n}"
},
{
"identifier": "AndesiteChunkLoaderRenderer",
"path": "src/main/java/com/hlysine/create_power_loader/content/andesitechunkloader/AndesiteChunkLoaderRenderer.java",
"snippet": "public class AndesiteChunkLoaderRenderer extends AbstractChunkLoaderRenderer {\n\n public AndesiteChunkLoaderRenderer(BlockEntityRendererProvider.Context context) {\n super(context);\n }\n\n @Override\n protected PartialModel getCorePartial(boolean attached, boolean active) {\n if (attached) {\n return active\n ? CPLPartialModels.ANDESITE_CORE_ATTACHED_ACTIVE\n : CPLPartialModels.ANDESITE_CORE_ATTACHED_INACTIVE;\n } else {\n return active\n ? CPLPartialModels.ANDESITE_CORE_ACTIVE\n : CPLPartialModels.ANDESITE_CORE_INACTIVE;\n }\n }\n\n @Override\n protected boolean shouldFunctionOnContraption(MovementContext context) {\n return CPLConfigs.server().andesiteOnContraption.get() &&\n !context.contraption.isActorTypeDisabled(CPLBlocks.ANDESITE_CHUNK_LOADER.asStack()) &&\n !context.contraption.isActorTypeDisabled(ItemStack.EMPTY);\n }\n}"
},
{
"identifier": "BrassChunkLoaderBlockEntity",
"path": "src/main/java/com/hlysine/create_power_loader/content/brasschunkloader/BrassChunkLoaderBlockEntity.java",
"snippet": "@MethodsReturnNonnullByDefault\npublic class BrassChunkLoaderBlockEntity extends AbstractChunkLoaderBlockEntity {\n\n protected ScrollOptionBehaviour<LoadingRange> loadingRange;\n\n public BrassChunkLoaderBlockEntity(BlockEntityType<?> type, BlockPos pos, BlockState state) {\n super(type, pos, state, LoaderType.BRASS);\n }\n\n @Override\n public void addBehaviours(List<BlockEntityBehaviour> behaviours) {\n super.addBehaviours(behaviours);\n\n loadingRange = new ScrollOptionBehaviour<>(LoadingRange.class,\n Component.translatable(CreatePowerLoader.MODID + \".brass_chunk_loader.loading_range\"), this, new LoadingRangeValueBox());\n loadingRange.value = 0;\n loadingRange.withCallback(i -> {\n boolean server = (!level.isClientSide || isVirtual()) && (level instanceof ServerLevel);\n if (server)\n updateForcedChunks();\n });\n loadingRange.onlyActiveWhen(() -> !getBlockState().getValue(ATTACHED));\n behaviours.add(loadingRange);\n }\n\n @Override\n public int getLoadingRange() {\n return loadingRange.getValue() + 1;\n }\n\n public void setLoadingRange(int range) {\n loadingRange.setValue(range - 1);\n }\n\n @Override\n protected double getSpeedMultiplierConfig() {\n return CPLConfigs.server().brassSpeedMultiplier.get();\n }\n\n private static class LoadingRangeValueBox extends CenteredSideValueBoxTransform {\n public LoadingRangeValueBox() {\n super((blockState, direction) -> {\n Direction facing = blockState.getValue(AbstractChunkLoaderBlock.FACING);\n return facing.getAxis() != direction.getAxis();\n });\n }\n\n @Override\n protected Vec3 getSouthLocation() {\n return VecHelper.voxelSpace(8, 8, 15.5);\n }\n\n @Override\n public Vec3 getLocalOffset(BlockState state) {\n Direction facing = state.getValue(AbstractChunkLoaderBlock.FACING);\n return super.getLocalOffset(state).add(Vec3.atLowerCornerOf(facing.getNormal())\n .scale(-4 / 16f));\n }\n\n\n @Override\n public float getScale() {\n return super.getScale();\n }\n }\n\n public enum LoadingRange implements INamedIconOptions {\n LOAD_1x1(CPLIcons.I_1x1),\n LOAD_3x3(CPLIcons.I_3x3),\n LOAD_5x5(CPLIcons.I_5x5),\n ;\n\n private final String translationKey;\n private final AllIcons icon;\n\n LoadingRange(AllIcons icon) {\n this.icon = icon;\n this.translationKey = CreatePowerLoader.MODID + \".brass_chunk_loader.\" + Lang.asId(name());\n }\n\n @Override\n public AllIcons getIcon() {\n return icon;\n }\n\n @Override\n public String getTranslationKey() {\n return translationKey;\n }\n }\n}"
},
{
"identifier": "BrassChunkLoaderRenderer",
"path": "src/main/java/com/hlysine/create_power_loader/content/brasschunkloader/BrassChunkLoaderRenderer.java",
"snippet": "public class BrassChunkLoaderRenderer extends AbstractChunkLoaderRenderer {\n\n public BrassChunkLoaderRenderer(BlockEntityRendererProvider.Context context) {\n super(context);\n }\n\n @Override\n protected PartialModel getCorePartial(boolean attached, boolean active) {\n if (attached) {\n return active\n ? CPLPartialModels.BRASS_CORE_ATTACHED_ACTIVE\n : CPLPartialModels.BRASS_CORE_ATTACHED_INACTIVE;\n } else {\n return active\n ? CPLPartialModels.BRASS_CORE_ACTIVE\n : CPLPartialModels.BRASS_CORE_INACTIVE;\n }\n }\n\n @Override\n protected boolean shouldFunctionOnContraption(MovementContext context) {\n return CPLConfigs.server().brassOnContraption.get() &&\n !context.contraption.isActorTypeDisabled(CPLBlocks.BRASS_CHUNK_LOADER.asStack()) &&\n !context.contraption.isActorTypeDisabled(ItemStack.EMPTY);\n }\n}"
}
] | import com.hlysine.create_power_loader.content.emptychunkloader.EmptyChunkLoaderBlockEntity;
import com.hlysine.create_power_loader.content.emptychunkloader.EmptyChunkLoaderRenderer;
import com.hlysine.create_power_loader.content.andesitechunkloader.AndesiteChunkLoaderBlockEntity;
import com.hlysine.create_power_loader.content.andesitechunkloader.AndesiteChunkLoaderRenderer;
import com.hlysine.create_power_loader.content.brasschunkloader.BrassChunkLoaderBlockEntity;
import com.hlysine.create_power_loader.content.brasschunkloader.BrassChunkLoaderRenderer;
import com.simibubi.create.foundation.data.CreateRegistrate;
import com.tterrag.registrate.util.entry.BlockEntityEntry; | 1,980 | package com.hlysine.create_power_loader;
public class CPLBlockEntityTypes {
private static final CreateRegistrate REGISTRATE = CreatePowerLoader.getRegistrate();
public static final BlockEntityEntry<EmptyChunkLoaderBlockEntity> EMPTY_ANDESITE_CHUNK_LOADER = REGISTRATE
.blockEntity("empty_andesite_chunk_loader", EmptyChunkLoaderBlockEntity::new)
.validBlocks(CPLBlocks.EMPTY_ANDESITE_CHUNK_LOADER) | package com.hlysine.create_power_loader;
public class CPLBlockEntityTypes {
private static final CreateRegistrate REGISTRATE = CreatePowerLoader.getRegistrate();
public static final BlockEntityEntry<EmptyChunkLoaderBlockEntity> EMPTY_ANDESITE_CHUNK_LOADER = REGISTRATE
.blockEntity("empty_andesite_chunk_loader", EmptyChunkLoaderBlockEntity::new)
.validBlocks(CPLBlocks.EMPTY_ANDESITE_CHUNK_LOADER) | .renderer(() -> EmptyChunkLoaderRenderer::new) | 1 | 2023-11-09 04:29:33+00:00 | 4k |
zemise/Spring-Boot-JavaFX-Demo | src/main/java/com/demo/Main.java | [
{
"identifier": "HelloView",
"path": "src/main/java/com/demo/view/HelloView.java",
"snippet": "@FXMLView\npublic class HelloView extends AbstractFxmlView {\n}"
},
{
"identifier": "AbstractJavaFxApplicationSupport",
"path": "src/main/java/de/felixroske/jfxsupport/AbstractJavaFxApplicationSupport.java",
"snippet": "@SuppressWarnings(\"WeakerAccess\")\npublic abstract class AbstractJavaFxApplicationSupport extends Application {\n private static Logger LOGGER = LoggerFactory.getLogger(AbstractJavaFxApplicationSupport.class);\n\n private static String[] savedArgs = new String[0];\n\n static Class<? extends AbstractFxmlView> savedInitialView;\n static de.felixroske.jfxsupport.SplashScreen splashScreen;\n private static ConfigurableApplicationContext applicationContext;\n\n\n private static List<Image> icons = new ArrayList<>();\n private final List<Image> defaultIcons = new ArrayList<>();\n\n private final CompletableFuture<Runnable> splashIsShowing;\n\n protected AbstractJavaFxApplicationSupport() {\n splashIsShowing = new CompletableFuture<>();\n }\n\n public static Stage getStage() {\n return GUIState.getStage();\n }\n\n public static Scene getScene() {\n return GUIState.getScene();\n }\n\n public static HostServices getAppHostServices() {\n return GUIState.getHostServices();\n }\n\n public static SystemTray getSystemTray() {\n return GUIState.getSystemTray();\n }\n\n /**\n * @param window The FxmlView derived class that should be shown.\n * @param mode See {@code javafx.stage.Modality}.\n */\n public static void showView(final Class<? extends AbstractFxmlView> window, final Modality mode) {\n final AbstractFxmlView view = applicationContext.getBean(window);\n Stage newStage = new Stage();\n\n Scene newScene;\n if (view.getView().getScene() != null) {\n // This view was already shown so\n // we have a scene for it and use this one.\n newScene = view.getView().getScene();\n } else {\n newScene = new Scene(view.getView());\n }\n\n newStage.setScene(newScene);\n newStage.initModality(mode);\n newStage.initOwner(getStage());\n newStage.setTitle(view.getDefaultTitle());\n newStage.initStyle(view.getDefaultStyle());\n\n newStage.showAndWait();\n }\n\n private void loadIcons(ConfigurableApplicationContext ctx) {\n try {\n final List<String> fsImages = PropertyReaderHelper.get(ctx.getEnvironment(), Constant.KEY_APPICONS);\n\n if (!fsImages.isEmpty()) {\n fsImages.forEach((s) -> {\n Image img = new Image(getClass().getResource(s).toExternalForm());\n icons.add(img);\n });\n } else { // add factory images\n icons.addAll(defaultIcons);\n }\n } catch (Exception e) {\n LOGGER.error(\"Failed to load icons: \", e);\n }\n\n\n }\n\n /*\n * (non-Javadoc)\n *\n * @see javafx.application.Application#init()\n */\n @Override\n public void init() throws Exception {\n // Load in JavaFx Thread and reused by Completable Future, but should no be a big deal.\n defaultIcons.addAll(loadDefaultIcons());\n CompletableFuture.supplyAsync(() ->\n {\n Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader());\n return SpringApplication.run(this.getClass(), savedArgs);\n }\n// SpringApplication.run(this.getClass(), savedArgs)\n ).whenComplete((ctx, throwable) -> {\n if (throwable != null) {\n LOGGER.error(\"Failed to load spring application context: \", throwable);\n Platform.runLater(() -> showErrorAlert(throwable));\n } else {\n Platform.runLater(() -> {\n loadIcons(ctx);\n launchApplicationView(ctx);\n });\n }\n }).thenAcceptBothAsync(splashIsShowing, (ctx, closeSplash) -> {\n Platform.runLater(closeSplash);\n });\n }\n\n\n /*\n * (non-Javadoc)\n *\n * @see javafx.application.Application#start(javafx.stage.Stage)\n */\n @Override\n public void start(final Stage stage) throws Exception {\n\n GUIState.setStage(stage);\n GUIState.setHostServices(this.getHostServices());\n final Stage splashStage = new Stage(StageStyle.TRANSPARENT);\n\n if (AbstractJavaFxApplicationSupport.splashScreen.visible()) {\n final Scene splashScene = new Scene(splashScreen.getParent(), Color.TRANSPARENT);\n splashStage.setScene(splashScene);\n splashStage.getIcons().addAll(defaultIcons);\n splashStage.initStyle(StageStyle.TRANSPARENT);\n beforeShowingSplash(splashStage);\n splashStage.show();\n }\n\n splashIsShowing.complete(() -> {\n showInitialView();\n if (AbstractJavaFxApplicationSupport.splashScreen.visible()) {\n splashStage.hide();\n splashStage.setScene(null);\n }\n });\n }\n\n\n /**\n * Show initial view.\n */\n private void showInitialView() {\n final String stageStyle = applicationContext.getEnvironment().getProperty(Constant.KEY_STAGE_STYLE);\n if (stageStyle != null) {\n GUIState.getStage().initStyle(StageStyle.valueOf(stageStyle.toUpperCase()));\n } else {\n GUIState.getStage().initStyle(StageStyle.DECORATED);\n }\n\n beforeInitialView(GUIState.getStage(), applicationContext);\n\n showView(savedInitialView);\n }\n\n\n /**\n * Launch application view.\n */\n private void launchApplicationView(final ConfigurableApplicationContext ctx) {\n AbstractJavaFxApplicationSupport.applicationContext = ctx;\n }\n\n /**\n * Show view.\n *\n * @param newView the new view\n */\n public static void showView(final Class<? extends AbstractFxmlView> newView) {\n try {\n final AbstractFxmlView view = applicationContext.getBean(newView);\n\n if (GUIState.getScene() == null) {\n GUIState.setScene(new Scene(view.getView()));\n } else {\n GUIState.getScene().setRoot(view.getView());\n }\n GUIState.getStage().setScene(GUIState.getScene());\n\n applyEnvPropsToView();\n\n GUIState.getStage().getIcons().addAll(icons);\n GUIState.getStage().show();\n\n } catch (Throwable t) {\n LOGGER.error(\"Failed to load application: \", t);\n showErrorAlert(t);\n }\n }\n\n /**\n * Show error alert that close app.\n *\n * @param throwable cause of error\n */\n private static void showErrorAlert(Throwable throwable) {\n Alert alert = new Alert(AlertType.ERROR, \"Oops! An unrecoverable error occurred.\\n\" + \"Please contact your software vendor.\\n\\n\" + \"The application will stop now.\\n\\n\" + \"Error: \" + throwable.getMessage());\n alert.showAndWait().ifPresent(response -> Platform.exit());\n }\n\n /**\n * Apply env props to view.\n */\n private static void applyEnvPropsToView() {\n PropertyReaderHelper.setIfPresent(applicationContext.getEnvironment(), Constant.KEY_TITLE, String.class, GUIState.getStage()::setTitle);\n\n PropertyReaderHelper.setIfPresent(applicationContext.getEnvironment(), Constant.KEY_STAGE_WIDTH, Double.class, GUIState.getStage()::setWidth);\n\n PropertyReaderHelper.setIfPresent(applicationContext.getEnvironment(), Constant.KEY_STAGE_HEIGHT, Double.class, GUIState.getStage()::setHeight);\n\n PropertyReaderHelper.setIfPresent(applicationContext.getEnvironment(), Constant.KEY_STAGE_RESIZABLE, Boolean.class, GUIState.getStage()::setResizable);\n }\n\n /*\n * (non-Javadoc)\n *\n * @see javafx.application.Application#stop()\n */\n @Override\n public void stop() throws Exception {\n super.stop();\n if (applicationContext != null) {\n applicationContext.close();\n } // else: someone did it already\n }\n\n /**\n * Sets the title. Allows to overwrite values applied during construction at\n * a later time.\n *\n * @param title the new title\n */\n protected static void setTitle(final String title) {\n GUIState.getStage().setTitle(title);\n }\n\n /**\n * Launch app.\n *\n * @param appClass the app class\n * @param view the view\n * @param args the args\n */\n public static void launch(final Class<? extends Application> appClass, final Class<? extends AbstractFxmlView> view, final String[] args) {\n\n launch(appClass, view, new de.felixroske.jfxsupport.SplashScreen(), args);\n }\n\n /**\n * Launch app.\n *\n * @param appClass the app class\n * @param view the view\n * @param args the args\n * @deprecated To be more in line with javafx.application please use launch\n */\n @Deprecated\n public static void launchApp(final Class<? extends Application> appClass, final Class<? extends AbstractFxmlView> view, final String[] args) {\n\n launch(appClass, view, new de.felixroske.jfxsupport.SplashScreen(), args);\n }\n\n /**\n * Launch app.\n *\n * @param appClass the app class\n * @param view the view\n * @param splashScreen the splash screen\n * @param args the args\n */\n public static void launch(final Class<? extends Application> appClass, final Class<? extends AbstractFxmlView> view, final de.felixroske.jfxsupport.SplashScreen splashScreen, final String[] args) {\n savedInitialView = view;\n savedArgs = args;\n\n if (splashScreen != null) {\n AbstractJavaFxApplicationSupport.splashScreen = splashScreen;\n } else {\n AbstractJavaFxApplicationSupport.splashScreen = new de.felixroske.jfxsupport.SplashScreen();\n }\n\n if (SystemTray.isSupported()) {\n GUIState.setSystemTray(SystemTray.getSystemTray());\n }\n\n Application.launch(appClass, args);\n }\n\n /**\n * Launch app.\n *\n * @param appClass the app class\n * @param view the view\n * @param splashScreen the splash screen\n * @param args the args\n * @deprecated To be more in line with javafx.application please use launch\n */\n @Deprecated\n public static void launchApp(final Class<? extends Application> appClass, final Class<? extends AbstractFxmlView> view, final SplashScreen splashScreen, final String[] args) {\n launch(appClass, view, splashScreen, args);\n }\n\n /**\n * Gets called after full initialization of Spring application context\n * and JavaFX platform right before the initial view is shown.\n * Override this method as a hook to add special code for your app. Especially meant to\n * add AWT code to add a system tray icon and behavior by calling\n * GUIState.getSystemTray() and modifying it accordingly.\n * <p>\n * By default noop.\n *\n * @param stage can be used to customize the stage before being displayed\n * @param ctx represents spring ctx where you can loog for beans.\n */\n public void beforeInitialView(final Stage stage, final ConfigurableApplicationContext ctx) {\n }\n\n public void beforeShowingSplash(Stage splashStage) {\n\n }\n\n public Collection<Image> loadDefaultIcons() {\n return Arrays.asList(new Image(getClass().getResource(\"/icons/gear_16x16.png\").toExternalForm()), new Image(getClass().getResource(\"/icons/gear_24x24.png\").toExternalForm()), new Image(getClass().getResource(\"/icons/gear_36x36.png\").toExternalForm()), new Image(getClass().getResource(\"/icons/gear_42x42.png\").toExternalForm()), new Image(getClass().getResource(\"/icons/gear_64x64.png\").toExternalForm()));\n }\n}"
}
] | import com.demo.view.HelloView;
import de.felixroske.jfxsupport.AbstractJavaFxApplicationSupport;
import org.springframework.boot.autoconfigure.SpringBootApplication; | 2,939 | package com.demo;
/**
* <p>
*
* </p>
*
* @author <a href= "https://github.com/zemise">zemise</a>
* @Date 2023/11/8
* @since 1.0
*/
@SpringBootApplication
public class Main extends AbstractJavaFxApplicationSupport {
public static void main(String[] args) { | package com.demo;
/**
* <p>
*
* </p>
*
* @author <a href= "https://github.com/zemise">zemise</a>
* @Date 2023/11/8
* @since 1.0
*/
@SpringBootApplication
public class Main extends AbstractJavaFxApplicationSupport {
public static void main(String[] args) { | launch(Main.class, HelloView.class, args); | 0 | 2023-11-08 03:20:19+00:00 | 4k |
dingodb/dingo-expr | rel/src/main/java/io/dingodb/expr/rel/mapper/RelOpMapper.java | [
{
"identifier": "RelConfig",
"path": "rel/src/main/java/io/dingodb/expr/rel/RelConfig.java",
"snippet": "public interface RelConfig {\n RelConfig DEFAULT = new RelConfig() {\n };\n\n default ExprParser getExprParser() {\n return ExprParser.DEFAULT;\n }\n\n default ExprCompiler getExprCompiler() {\n return ExprCompiler.ADVANCED;\n }\n}"
},
{
"identifier": "RelOp",
"path": "rel/src/main/java/io/dingodb/expr/rel/RelOp.java",
"snippet": "public interface RelOp {\n void init(TupleType type, @NonNull RelConfig config);\n\n TupleType getType();\n\n <R, T> R accept(@NonNull RelOpVisitor<R, T> visitor, T obj);\n}"
},
{
"identifier": "TandemOp",
"path": "rel/src/main/java/io/dingodb/expr/rel/TandemOp.java",
"snippet": "@RequiredArgsConstructor(access = AccessLevel.PROTECTED)\n@EqualsAndHashCode(of = {\"input\", \"output\"})\npublic abstract class TandemOp implements RelOp {\n @Getter\n protected final RelOp input;\n @Getter\n protected final RelOp output;\n\n @Override\n public void init(TupleType type, @NonNull RelConfig config) {\n input.init(type, config);\n output.init(input.getType(), config);\n }\n\n @Override\n public TupleType getType() {\n return output.getType();\n }\n\n @Override\n public <R, T> R accept(@NonNull RelOpVisitor<R, T> visitor, T obj) {\n return visitor.visitTandemOp(this, obj);\n }\n\n @Override\n public String toString() {\n return input + \", \" + output;\n }\n}"
},
{
"identifier": "FilterOpDto",
"path": "rel/src/main/java/io/dingodb/expr/rel/dto/FilterOpDto.java",
"snippet": "@Data\n@EqualsAndHashCode(callSuper = true)\npublic class FilterOpDto extends RelDto {\n @JsonProperty(\"filter\")\n private String filter;\n}"
},
{
"identifier": "GroupedAggregateOpDto",
"path": "rel/src/main/java/io/dingodb/expr/rel/dto/GroupedAggregateOpDto.java",
"snippet": "@Data\n@EqualsAndHashCode(callSuper = true)\npublic class GroupedAggregateOpDto extends RelDto {\n @JsonProperty(\"groups\")\n private int[] groupIndices;\n @JsonProperty(\"aggList\")\n private List<String> aggList;\n}"
},
{
"identifier": "ProjectOpDto",
"path": "rel/src/main/java/io/dingodb/expr/rel/dto/ProjectOpDto.java",
"snippet": "@Data\n@EqualsAndHashCode(callSuper = true)\npublic class ProjectOpDto extends RelDto {\n @JsonProperty(\"projects\")\n private String[] projects;\n}"
},
{
"identifier": "RelDto",
"path": "rel/src/main/java/io/dingodb/expr/rel/dto/RelDto.java",
"snippet": "@JsonTypeInfo(\n use = JsonTypeInfo.Id.DEDUCTION\n)\n@JsonSubTypes({\n @JsonSubTypes.Type(FilterOpDto.class),\n @JsonSubTypes.Type(ProjectOpDto.class),\n @JsonSubTypes.Type(TandemOpDto.class),\n @JsonSubTypes.Type(GroupedAggregateOpDto.class),\n @JsonSubTypes.Type(UngroupedAggregateOpDto.class),\n})\npublic class RelDto {\n}"
},
{
"identifier": "TandemOpDto",
"path": "rel/src/main/java/io/dingodb/expr/rel/dto/TandemOpDto.java",
"snippet": "@Data\n@EqualsAndHashCode(callSuper = true)\npublic class TandemOpDto extends RelDto {\n @JsonProperty(\"i\")\n private RelDto input;\n @JsonProperty(\"o\")\n private RelDto output;\n}"
},
{
"identifier": "UngroupedAggregateOpDto",
"path": "rel/src/main/java/io/dingodb/expr/rel/dto/UngroupedAggregateOpDto.java",
"snippet": "@Data\n@EqualsAndHashCode(callSuper = true)\npublic class UngroupedAggregateOpDto extends RelDto {\n @JsonProperty(\"aggList\")\n private List<String> aggList;\n}"
},
{
"identifier": "FilterOp",
"path": "rel/src/main/java/io/dingodb/expr/rel/op/FilterOp.java",
"snippet": "@EqualsAndHashCode(callSuper = true, of = {\"filter\"})\npublic final class FilterOp extends TypedPipeOp {\n public static final String NAME = \"FILTER\";\n\n @Getter\n private Expr filter;\n\n public FilterOp(Expr filter) {\n this.filter = filter;\n }\n\n @Override\n public Object @Nullable [] put(Object @NonNull [] tuple) {\n final TupleEvalContext context = new TupleEvalContext(tuple);\n Object v = filter.eval(context, exprConfig);\n return (v != null && (Boolean) v) ? tuple : null;\n }\n\n @Override\n public void init(TupleType type, @NonNull RelConfig config) {\n super.init(type, config);\n final TupleCompileContext context = new TupleCompileContext(type);\n ExprCompiler compiler = config.getExprCompiler();\n filter = compiler.visit(filter, context);\n this.type = type;\n }\n\n @Override\n public <R, T> R accept(@NonNull RelOpVisitor<R, T> visitor, T obj) {\n return visitor.visitFilterOp(this, obj);\n }\n\n @Override\n public @NonNull String toString() {\n return NAME + \": \" + filter.toString();\n }\n}"
},
{
"identifier": "GroupedAggregateOp",
"path": "rel/src/main/java/io/dingodb/expr/rel/op/GroupedAggregateOp.java",
"snippet": "@EqualsAndHashCode(callSuper = true, of = {\"groupIndices\"})\npublic final class GroupedAggregateOp extends AggregateOp {\n public static final String NAME = \"AGG\";\n\n @Getter\n private final int[] groupIndices;\n\n private final Map<TupleKey, Object[]> cache;\n\n public GroupedAggregateOp(int @NonNull [] groupIndices, List<Expr> aggList) {\n super(aggList);\n this.groupIndices = groupIndices;\n this.cache = new ConcurrentHashMap<>();\n }\n\n @Override\n public void put(Object @NonNull [] tuple) {\n Object[] keyTuple = ArrayUtils.map(tuple, groupIndices);\n Object[] vars = cache.computeIfAbsent(new TupleKey(keyTuple), k -> new Object[aggList.size()]);\n for (int i = 0; i < vars.length; ++i) {\n AggExpr aggExpr = (AggExpr) aggList.get(i);\n vars[i] = aggExpr.add(vars[i], new TupleEvalContext(tuple), exprConfig);\n }\n }\n\n @Override\n public @NonNull Stream<Object[]> get() {\n return cache.entrySet().stream()\n .map(e -> ArrayUtils.concat(e.getKey().getTuple(), e.getValue()));\n }\n\n @Override\n public void init(TupleType type, @NonNull RelConfig config) {\n super.init(type, config);\n this.type = Types.tuple(\n ArrayUtils.concat(\n ArrayUtils.map(type.getTypes(), groupIndices),\n aggList.stream().map(Expr::getType).toArray(Type[]::new)\n )\n );\n }\n\n @Override\n public <R, T> R accept(@NonNull RelOpVisitor<R, T> visitor, T obj) {\n return visitor.visitGroupedAggregateOp(this, obj);\n }\n\n @Override\n public @NonNull String toString() {\n return NAME + \": \" + Arrays.toString(groupIndices) + aggList.toString();\n }\n\n /**\n * Wrap tuples to provide hash and equals.\n */\n @RequiredArgsConstructor(access = AccessLevel.PACKAGE)\n public static class TupleKey {\n @Getter\n private final Object[] tuple;\n\n @Override\n public int hashCode() {\n return Arrays.hashCode(tuple);\n }\n\n @Override\n public boolean equals(Object obj) {\n if (obj instanceof TupleKey) {\n return Arrays.equals(this.tuple, ((TupleKey) obj).tuple);\n }\n return false;\n }\n }\n}"
},
{
"identifier": "ProjectOp",
"path": "rel/src/main/java/io/dingodb/expr/rel/op/ProjectOp.java",
"snippet": "@EqualsAndHashCode(callSuper = true, of = {\"projects\"})\npublic final class ProjectOp extends TypedPipeOp {\n public static final String NAME = \"PROJECT\";\n\n @Getter\n private Expr[] projects;\n\n public ProjectOp(Expr[] projects) {\n this.projects = projects;\n }\n\n @Override\n public Object @NonNull [] put(Object @NonNull [] tuple) {\n final TupleEvalContext context = new TupleEvalContext(tuple);\n return Arrays.stream(projects)\n .map(p -> p.eval(context, exprConfig))\n .toArray(Object[]::new);\n }\n\n @Override\n public void init(TupleType type, @NonNull RelConfig config) {\n super.init(type, config);\n final TupleCompileContext context = new TupleCompileContext(type);\n ExprCompiler compiler = config.getExprCompiler();\n projects = Arrays.stream(projects)\n .map(p -> compiler.visit(p, context))\n .toArray(Expr[]::new);\n this.type = Types.tuple(Arrays.stream(projects)\n .map(Expr::getType)\n .toArray(Type[]::new));\n }\n\n @Override\n public <R, T> R accept(@NonNull RelOpVisitor<R, T> visitor, T obj) {\n return visitor.visitProjectOp(this, obj);\n }\n\n @Override\n public @NonNull String toString() {\n return NAME + \": \" + Arrays.toString(projects);\n }\n}"
},
{
"identifier": "UngroupedAggregateOp",
"path": "rel/src/main/java/io/dingodb/expr/rel/op/UngroupedAggregateOp.java",
"snippet": "public final class UngroupedAggregateOp extends AggregateOp {\n public static final String NAME = \"AGG\";\n\n private transient Object[] vars;\n\n public UngroupedAggregateOp(List<Expr> aggList) {\n super(aggList);\n }\n\n @Override\n public void put(Object @NonNull [] tuple) {\n if (vars == null) {\n vars = new Object[aggList.size()];\n }\n for (int i = 0; i < vars.length; ++i) {\n AggExpr aggExpr = (AggExpr) aggList.get(i);\n vars[i] = aggExpr.add(vars[i], new TupleEvalContext(tuple), exprConfig);\n }\n }\n\n @Override\n public @NonNull Stream<Object[]> get() {\n if (vars != null) {\n return Stream.<Object[]>of(vars);\n }\n return Stream.<Object[]>of(\n aggList.stream()\n .map(agg -> ((AggExpr) agg).emptyValue())\n .toArray(Object[]::new)\n );\n }\n\n @Override\n public void init(TupleType type, @NonNull RelConfig config) {\n super.init(type, config);\n this.type = Types.tuple(aggList.stream().map(Expr::getType).toArray(Type[]::new));\n }\n\n @Override\n public <R, T> R accept(@NonNull RelOpVisitor<R, T> visitor, T obj) {\n return visitor.visitUngroupedAggregateOp(this, obj);\n }\n\n @Override\n public @NonNull String toString() {\n return NAME + \": \" + aggList.toString();\n }\n}"
}
] | import org.mapstruct.Mapper;
import org.mapstruct.SubclassExhaustiveStrategy;
import org.mapstruct.SubclassMapping;
import org.mapstruct.factory.Mappers;
import io.dingodb.expr.rel.RelConfig;
import io.dingodb.expr.rel.RelOp;
import io.dingodb.expr.rel.TandemOp;
import io.dingodb.expr.rel.dto.FilterOpDto;
import io.dingodb.expr.rel.dto.GroupedAggregateOpDto;
import io.dingodb.expr.rel.dto.ProjectOpDto;
import io.dingodb.expr.rel.dto.RelDto;
import io.dingodb.expr.rel.dto.TandemOpDto;
import io.dingodb.expr.rel.dto.UngroupedAggregateOpDto;
import io.dingodb.expr.rel.op.FilterOp;
import io.dingodb.expr.rel.op.GroupedAggregateOp;
import io.dingodb.expr.rel.op.ProjectOp;
import io.dingodb.expr.rel.op.UngroupedAggregateOp;
import org.mapstruct.Context; | 3,052 | /*
* Copyright 2021 DataCanvas
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.dingodb.expr.rel.mapper;
@Mapper(
uses = {
ExprMapper.class,
FilterOpMapper.class,
ProjectOpMapper.class,
TandemOpMapper.class,
},
subclassExhaustiveStrategy = SubclassExhaustiveStrategy.RUNTIME_EXCEPTION
)
public interface RelOpMapper {
RelOpMapper MAPPER = Mappers.getMapper(RelOpMapper.class);
@SubclassMapping(target = FilterOp.class, source = FilterOpDto.class) | /*
* Copyright 2021 DataCanvas
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.dingodb.expr.rel.mapper;
@Mapper(
uses = {
ExprMapper.class,
FilterOpMapper.class,
ProjectOpMapper.class,
TandemOpMapper.class,
},
subclassExhaustiveStrategy = SubclassExhaustiveStrategy.RUNTIME_EXCEPTION
)
public interface RelOpMapper {
RelOpMapper MAPPER = Mappers.getMapper(RelOpMapper.class);
@SubclassMapping(target = FilterOp.class, source = FilterOpDto.class) | @SubclassMapping(target = ProjectOp.class, source = ProjectOpDto.class) | 11 | 2023-11-04 08:43:49+00:00 | 4k |
sesamecare/stripe-mock | src/main/java/com/sesame/oss/stripemock/StripeMock.java | [
{
"identifier": "StripeEntities",
"path": "src/main/java/com/sesame/oss/stripemock/entities/StripeEntities.java",
"snippet": "public class StripeEntities {\n private final Map<Class<? extends ApiResource>, EntityManager<? extends ApiResource>> entityManagers = new HashMap<>();\n private final Map<String, EntityManager<? extends ApiResource>> entityManagersByNormalizedEntityName = new HashMap<>();\n\n public StripeEntities(Clock clock) {\n // As these entity managers will need to have access to each other, often in a circular dependency fashion,\n // we're passing in the StripeEntities so they can do resolution using it. This means that we're leaking 'this'\n // before the object is constructed, but it still seems more elegant than calling a setter on each manager later.\n\n add(new TransferReversalManager(clock, this));\n add(new PaymentMethodManager(clock, this));\n add(new PaymentIntentManager(clock, this));\n add(new SubscriptionManager(clock, this));\n add(new RefundManager(clock, this));\n add(new SetupIntentManager(clock));\n add(new TransferManager(clock, this));\n add(new CustomerManager(clock, this));\n add(new InvoiceManager(clock, this));\n add(new ProductManager(clock));\n add(new AccountManager(clock));\n }\n\n private void add(EntityManager<?> entityManager) {\n entityManagers.put(entityManager.getEntityClass(), entityManager);\n entityManagersByNormalizedEntityName.put(entityManager.getNormalizedEntityName(), entityManager);\n entityManager.bootstrap();\n }\n\n public <T extends ApiResource & HasId> EntityManager<T> getEntityManager(Class<T> entityClass) {\n return (EntityManager<T>) entityManagers.get(entityClass);\n }\n\n /**\n * @param normalizedEntityName {@code payment_intents} for {@link com.stripe.model.PaymentIntent} for example. It's whatever the URL path would be start with.\n * @see EntityManager#getNormalizedEntityName()\n */\n public EntityManager<?> getEntityManager(String normalizedEntityName) {\n return entityManagersByNormalizedEntityName.get(normalizedEntityName);\n }\n\n public void clear() {\n for (EntityManager<?> entityManager : entityManagers.values()) {\n entityManager.clear();\n entityManager.bootstrap();\n }\n }\n\n public Optional<?> getEntityById(String id) {\n // This isn't very fast, and we could be more selective by using the prefix in the id, but it'll do for now.\n // Also, there likely won't be a lot of entities in memory in any given unit test\n return entityManagers.values()\n .stream()\n .map(entityManager -> safeGet(id, entityManager))\n .filter(Objects::nonNull)\n .findAny();\n }\n\n private static Object safeGet(String id, EntityManager<?> entityManager) {\n try {\n return entityManager.get(id)\n .orElse(null);\n } catch (ResponseCodeException e) {\n // We have to do this, rather than just rely on the optional, as each entity is able to throw a custom exception.\n // See for example the AccountManager, which has special treatment.\n return null;\n }\n }\n}"
},
{
"identifier": "StripeApiHttpHandler",
"path": "src/main/java/com/sesame/oss/stripemock/http/StripeApiHttpHandler.java",
"snippet": "public class StripeApiHttpHandler implements HttpHandler {\n private final IdempotencyManager idempotencyManager = new IdempotencyManager();\n private final Parser parser = new Parser();\n\n private final JsonResponseProducer jsonResponseProducer;\n private final EntityRequestHandler requestHandler;\n\n public StripeApiHttpHandler(StripeEntities stripeEntities) {\n this.jsonResponseProducer = new JsonResponseProducer(stripeEntities);\n this.requestHandler = new EntityRequestHandler(stripeEntities);\n }\n\n @Override\n public void handle(HttpExchange exchange) throws IOException {\n String requestId = Utilities.randomIdWithPrefix(\"req\", 14);\n String method = exchange.getRequestMethod();\n URI requestURI = exchange.getRequestURI();\n String query = requestURI.getQuery();\n Headers requestHeaders = exchange.getRequestHeaders();\n String requestBody = readInputFully(exchange);\n\n if (StripeMock.isLogRequests()) {\n String message = \"\"\"\n \n Request: %s %s%s\n Headers: %s\n Body: %s\n Request-Id: %s\n \"\"\";\n Logger.getLogger(\"stripe-mock-requests\")\n .log(Level.INFO, String.format(message, method, requestURI, query == null ? \"\" : query, requestHeaders, requestBody, requestId));\n }\n\n RawResponse rawResponse = processRequest(requestURI, query, requestHeaders, method, requestBody, requestId);\n Headers responseHeaders = sendResponse(exchange, rawResponse, requestId);\n\n if (StripeMock.isLogRequests()) {\n String message = \"\"\"\n \n Response to request: %s\n Code: %d\n Headers: %s\n Body: %s\n \"\"\";\n Logger.getLogger(\"stripe-mock-responses\")\n .log(Level.INFO, String.format(message, requestId, rawResponse.code(), responseHeaders, rawResponse.body()));\n }\n }\n\n private Headers sendResponse(HttpExchange exchange, RawResponse rawResponse, String requestId) throws IOException {\n Headers responseHeaders = exchange.getResponseHeaders();\n responseHeaders.putAll(rawResponse.headers());\n if (!requestId.equals(rawResponse.requestId())) {\n // If the request ids are different in the request and the response, this was a replay of an idempotent request\n // todo: ideally we'd like to do all of this in the IdempotencyManager\n responseHeaders.add(\"Original-Request\", rawResponse.requestId());\n responseHeaders.add(\"Idempotent-Replayed\", \"true\");\n }\n byte[] responseBodyBytes = rawResponse.body()\n .getBytes(StandardCharsets.UTF_8);\n exchange.sendResponseHeaders(rawResponse.code(), responseBodyBytes.length);\n try (OutputStream responseBody = exchange.getResponseBody()) {\n responseBody.write(responseBodyBytes);\n responseBody.flush();\n }\n return responseHeaders;\n }\n\n private RawResponse processRequest(URI requestURI, String query, Headers requestHeaders, String method, String requestBody, String requestId) {\n try {\n String[] path = requestURI.getPath()\n .split(\"/\");\n QueryParameters queryParameters = new QueryParameters(query);\n\n String idempotencyKey = requestHeaders.getFirst(\"Idempotency-Key\");\n return idempotencyManager.start(idempotencyKey, method, queryParameters, requestBody, requestHeaders, requestId)\n .finish(() -> {\n // This body here MUST NOT throw any exceptions. If it does, the idempotent request remains unfinished forever.\n // Thus, we have to catch here and produce a response, even if it's a broken one.\n\n\n // This is only called if we didn't already have a response for this request+idempotency key\n Headers headers = Utilities.defaultHeaders(idempotencyKey, requestId);\n try {\n Map<String, Object> requestBodyFormData =\n parser.parseRequestBody(requestBody, requestHeaders.getFirst(\"Content-Type\"));\n EntityResponse response = requestHandler.handleRequest(method, path, queryParameters, requestBodyFormData);\n return switch (response) {\n case Single(int code, Object entity) -> new RawResponse(code,\n jsonResponseProducer.toJson(entity,\n requestBodyFormData,\n queryParameters),\n headers,\n requestId);\n case Multiple(int code, List<?> entities) -> new RawResponse(code,\n jsonResponseProducer.toJson(entities,\n requestBodyFormData,\n queryParameters),\n headers,\n requestId);\n };\n } catch (ResponseCodeException e) {\n return new RawResponse(e.getResponseCode(), Utilities.toApiError(e), headers, requestId);\n } catch (Throwable e) {\n Logger.getLogger(\"stripe-mock\")\n .log(Level.SEVERE, \"Could not process response\", e);\n return new RawResponse(500, Utilities.toApiError(e.getMessage(), null, null, null), headers, requestId);\n }\n });\n } catch (Throwable e) {\n Logger.getLogger(\"stripe-mock\")\n .log(Level.SEVERE, \"Could not process request\", e);\n return new RawResponse(500, Utilities.toApiError(e.getMessage(), null, null, null), Utilities.defaultHeaders(null, requestId), requestId);\n }\n }\n\n private String readInputFully(HttpExchange exchange) throws IOException {\n try (InputStream requestBody = exchange.getRequestBody()) {\n byte[] bytes = requestBody.readAllBytes();\n return new String(bytes, StandardCharsets.UTF_8);\n }\n }\n}"
},
{
"identifier": "MutableClock",
"path": "src/main/java/com/sesame/oss/stripemock/util/MutableClock.java",
"snippet": "public class MutableClock extends Clock {\n private final ZoneId zoneId;\n private volatile Instant instant;\n\n public MutableClock(ZoneId zoneId, Instant instant) {\n this.zoneId = zoneId;\n this.instant = instant;\n }\n\n @Override\n public ZoneId getZone() {\n return zoneId;\n }\n\n @Override\n public Clock withZone(ZoneId zone) {\n return new MutableClock(zone, instant);\n }\n\n @Override\n public Instant instant() {\n return instant;\n }\n\n public void setInstant(Instant instant) {\n this.instant = instant;\n }\n\n public void plusSeconds(int seconds) {\n setInstant(this.instant.plusSeconds(seconds));\n }\n}"
}
] | import com.sesame.oss.stripemock.entities.StripeEntities;
import com.sesame.oss.stripemock.http.StripeApiHttpHandler;
import com.sesame.oss.stripemock.util.MutableClock;
import com.stripe.Stripe;
import com.stripe.exception.StripeException;
import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.time.Clock;
import java.time.Instant; | 2,472 | package com.sesame.oss.stripemock;
public class StripeMock {
/**
* When switching from using a normal stripe integration during testing, there might be "known" values, for example customers with a known
* set of payment methods, that are returned in other mocks. As those mocks might be static, we're going to make it possible to mimic this
* behavior. This is done by allowing an ID to be overridden when passed in as metadata. Ideally this should be rare, but it will smooth
* transition from real stripe tests to mocked stripe tests.
*/
public static final String OVERRIDE_ID_FOR_TESTING = "__override_id_for_testing";
private static final MutableClock CLOCK = new MutableClock(Clock.systemDefaultZone()
.getZone(),
Clock.systemDefaultZone()
.instant()); | package com.sesame.oss.stripemock;
public class StripeMock {
/**
* When switching from using a normal stripe integration during testing, there might be "known" values, for example customers with a known
* set of payment methods, that are returned in other mocks. As those mocks might be static, we're going to make it possible to mimic this
* behavior. This is done by allowing an ID to be overridden when passed in as metadata. Ideally this should be rare, but it will smooth
* transition from real stripe tests to mocked stripe tests.
*/
public static final String OVERRIDE_ID_FOR_TESTING = "__override_id_for_testing";
private static final MutableClock CLOCK = new MutableClock(Clock.systemDefaultZone()
.getZone(),
Clock.systemDefaultZone()
.instant()); | private final StripeEntities stripeEntities = new StripeEntities(CLOCK); | 0 | 2023-11-03 08:51:13+00:00 | 4k |
Bo-Vane/Chatbot-api | chatbot-api-application/src/main/java/com/bo/chatbot/api/application/job/ChatbotSchedule.java | [
{
"identifier": "IOpenAI",
"path": "chatbot-api-domain/src/main/java/com/bo/chatbot/api/domain/ai/IOpenAI.java",
"snippet": "public interface IOpenAI {\n String doChatGLM(String question) throws IOException;\n}"
},
{
"identifier": "IZsxqApi",
"path": "chatbot-api-domain/src/main/java/com/bo/chatbot/api/domain/zsxq/IZsxqApi.java",
"snippet": "public interface IZsxqApi {\n\n QuestionAggregates queryQuestion(String groupId, String cookie) throws IOException;\n\n boolean answer(String groupId,String cookie,String topicId,String text) throws IOException;\n}"
},
{
"identifier": "QuestionAggregates",
"path": "chatbot-api-domain/src/main/java/com/bo/chatbot/api/domain/zsxq/aggregates/QuestionAggregates.java",
"snippet": "public class QuestionAggregates {\n\n private boolean succeeded;\n private Resp_data resp_data;\n\n public QuestionAggregates(boolean succeeded, Resp_data resp_data) {\n this.succeeded = succeeded;\n this.resp_data = resp_data;\n }\n\n public boolean isSucceeded() {\n return succeeded;\n }\n\n public void setSucceeded(boolean succeeded) {\n this.succeeded = succeeded;\n }\n\n public Resp_data getResp_data() {\n return resp_data;\n }\n\n public void setResp_data(Resp_data resp_data) {\n this.resp_data = resp_data;\n }\n}"
},
{
"identifier": "Favorites",
"path": "chatbot-api-domain/src/main/java/com/bo/chatbot/api/domain/zsxq/vo/Favorites.java",
"snippet": "public class Favorites\n{\n private String favor_time;\n\n private Topic topic;\n\n public void setFavor_time(String favor_time){\n this.favor_time = favor_time;\n }\n public String getFavor_time(){\n return this.favor_time;\n }\n public void setTopic(Topic topic){\n this.topic = topic;\n }\n public Topic getTopic(){\n return this.topic;\n }\n}"
},
{
"identifier": "Topic",
"path": "chatbot-api-domain/src/main/java/com/bo/chatbot/api/domain/zsxq/vo/Topic.java",
"snippet": "public class Topic\n{\n private String topic_id;\n\n private Group group;\n\n private String type;\n\n private Task task;\n\n private Statistics statistics;\n\n private boolean enabled_task;\n\n private boolean show_solutions;\n\n private List<Show_comments> show_comments;\n\n private int likes_count;\n\n private int rewards_count;\n\n private int comments_count;\n\n private int reading_count;\n\n private int readers_count;\n\n private boolean digested;\n\n private boolean sticky;\n\n private String create_time;\n\n private User_specific user_specific;\n\n public void setTopic_id(String topic_id){\n this.topic_id = topic_id;\n }\n public String getTopic_id(){\n return this.topic_id;\n }\n public void setGroup(Group group){\n this.group = group;\n }\n public Group getGroup(){\n return this.group;\n }\n public void setType(String type){\n this.type = type;\n }\n public String getType(){\n return this.type;\n }\n public void setTask(Task task){\n this.task = task;\n }\n public Task getTask(){\n return this.task;\n }\n public void setStatistics(Statistics statistics){\n this.statistics = statistics;\n }\n public Statistics getStatistics(){\n return this.statistics;\n }\n public void setEnabled_task(boolean enabled_task){\n this.enabled_task = enabled_task;\n }\n public boolean getEnabled_task(){\n return this.enabled_task;\n }\n public void setShow_solutions(boolean show_solutions){\n this.show_solutions = show_solutions;\n }\n public boolean getShow_solutions(){\n return this.show_solutions;\n }\n public void setShow_comments(List<Show_comments> show_comments){\n this.show_comments = show_comments;\n }\n public List<Show_comments> getShow_comments(){\n return this.show_comments;\n }\n public void setLikes_count(int likes_count){\n this.likes_count = likes_count;\n }\n public int getLikes_count(){\n return this.likes_count;\n }\n public void setRewards_count(int rewards_count){\n this.rewards_count = rewards_count;\n }\n public int getRewards_count(){\n return this.rewards_count;\n }\n public void setComments_count(int comments_count){\n this.comments_count = comments_count;\n }\n public int getComments_count(){\n return this.comments_count;\n }\n public void setReading_count(int reading_count){\n this.reading_count = reading_count;\n }\n public int getReading_count(){\n return this.reading_count;\n }\n public void setReaders_count(int readers_count){\n this.readers_count = readers_count;\n }\n public int getReaders_count(){\n return this.readers_count;\n }\n public void setDigested(boolean digested){\n this.digested = digested;\n }\n public boolean getDigested(){\n return this.digested;\n }\n public void setSticky(boolean sticky){\n this.sticky = sticky;\n }\n public boolean getSticky(){\n return this.sticky;\n }\n public void setCreate_time(String create_time){\n this.create_time = create_time;\n }\n public String getCreate_time(){\n return this.create_time;\n }\n public void setUser_specific(User_specific user_specific){\n this.user_specific = user_specific;\n }\n public User_specific getUser_specific(){\n return this.user_specific;\n }\n}"
}
] | import com.bo.chatbot.api.domain.ai.IOpenAI;
import com.bo.chatbot.api.domain.zsxq.IZsxqApi;
import com.bo.chatbot.api.domain.zsxq.aggregates.QuestionAggregates;
import com.bo.chatbot.api.domain.zsxq.vo.Favorites;
import com.bo.chatbot.api.domain.zsxq.vo.Topic;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import javax.annotation.Resource;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Random; | 1,620 | package com.bo.chatbot.api.application.job;
/**
* @author bovane
* @description 问题任务job
* @github <a href="https://github.com/Bo-Vane/Chatbot-api">...</a>
* @Copyright 2023
*/
@EnableScheduling
@Configuration
public class ChatbotSchedule {
private Logger logger = LoggerFactory.getLogger(ChatbotSchedule.class);
@Value("${chatbot-api.groupId}")
private String groupId;
@Value("${chatbot-api.cookie}")
private String cookie;
@Resource
private IZsxqApi zsxqApi;
@Resource | package com.bo.chatbot.api.application.job;
/**
* @author bovane
* @description 问题任务job
* @github <a href="https://github.com/Bo-Vane/Chatbot-api">...</a>
* @Copyright 2023
*/
@EnableScheduling
@Configuration
public class ChatbotSchedule {
private Logger logger = LoggerFactory.getLogger(ChatbotSchedule.class);
@Value("${chatbot-api.groupId}")
private String groupId;
@Value("${chatbot-api.cookie}")
private String cookie;
@Resource
private IZsxqApi zsxqApi;
@Resource | private IOpenAI openAI; | 0 | 2023-11-06 08:52:38+00:00 | 4k |
Arborsm/ArborCore | src/main/java/org/arbor/gtnn/api/machine/multiblock/NeutronActivator.java | [
{
"identifier": "HighSpeedPipeBlock",
"path": "src/main/java/org/arbor/gtnn/api/machine/multiblock/part/HighSpeedPipeBlock.java",
"snippet": "@ParametersAreNonnullByDefault\n@MethodsReturnNonnullByDefault\npublic class HighSpeedPipeBlock extends MultiblockPartMachine{\n public HighSpeedPipeBlock(IMachineBlockEntity holder) {\n super(holder);\n }\n\n @Override\n public boolean shouldOpenUI(Player player, InteractionHand hand, BlockHitResult hit) {\n return false;\n }\n\n @Override\n public void scheduleRenderUpdate() {\n }\n\n @Override\n public boolean shouldRenderGrid(Player player, ItemStack held, Set<GTToolType> toolTypes) {\n return false;\n }\n}"
},
{
"identifier": "NeutronAccelerator",
"path": "src/main/java/org/arbor/gtnn/api/machine/multiblock/part/NeutronAccelerator.java",
"snippet": "@Getter@Setter\n@ParametersAreNonnullByDefault\n@MethodsReturnNonnullByDefault\npublic class NeutronAccelerator extends EnergyHatchPartMachine {\n protected static final ManagedFieldHolder MANAGED_FIELD_HOLDER;\n private boolean isActive;\n\n @Override\n public boolean shouldOpenUI(Player player, InteractionHand hand, BlockHitResult hit) {\n return true;\n }\n\n public NeutronAccelerator(IMachineBlockEntity holder, int tier, Object... args) {\n super(holder, tier, IO.IN, 1, args);\n }\n\n public int getMaxEUConsume() {\n return (int) (GTValues.V[tier] * 8 / 10);\n }\n\n @Override\n public ManagedFieldHolder getFieldHolder() {\n return MANAGED_FIELD_HOLDER;\n }\n\n public void energyTick(){\n if (!this.getLevel().isClientSide){\n if (this.energyContainer.getEnergyStored() >= getMaxEUConsume() && this.isWorkingEnabled()){\n this.energyContainer.setEnergyStored(this.energyContainer.getEnergyStored() - getMaxEUConsume());\n isActive = true;\n } else{\n isActive = false;\n }\n }\n }\n\n static {\n MANAGED_FIELD_HOLDER = new ManagedFieldHolder(NeutronAccelerator.class, TieredIOPartMachine.MANAGED_FIELD_HOLDER);\n }\n}"
},
{
"identifier": "NeutronActivatorCondition",
"path": "src/main/java/org/arbor/gtnn/api/recipe/NeutronActivatorCondition.java",
"snippet": "@Getter\npublic class NeutronActivatorCondition extends RecipeCondition {\n public static final NeutronActivatorCondition INSTANCE = new NeutronActivatorCondition();\n private int evRange = 0;\n public NeutronActivatorCondition(int max, int min){\n super();\n this.evRange = max * 10000 + min;\n }\n\n public NeutronActivatorCondition() {\n super();\n }\n\n @Override\n public String getType() {\n return \"neutron_activator_condition\";\n }\n\n @Override\n public Component getTooltips() {\n int max = evRange % 10000;\n int min = evRange / 10000;\n return Component.translatable(\"gtnn.recipe.condition.neutron_activator_condition_tooltip\", max, min);\n }\n\n @Override\n public boolean test(@NotNull GTRecipe gtRecipe, @NotNull RecipeLogic recipeLogic) {\n return NeutronActivator.checkNeutronActivatorCondition((MetaMachine) recipeLogic.machine, gtRecipe);\n }\n\n @Override\n public RecipeCondition createTemplate() {\n return new NeutronActivatorCondition();\n }\n\n @NotNull\n @Override\n public JsonObject serialize() {\n JsonObject value = super.serialize();\n value.addProperty(\"evRange\", this.evRange);\n return value;\n }\n\n @Override\n public RecipeCondition deserialize(@NotNull JsonObject config) {\n super.deserialize(config);\n this.evRange = GsonHelper.getAsInt(config, \"evRange\", 0);\n return this;\n }\n\n @Override\n public void toNetwork(FriendlyByteBuf buf) {\n super.toNetwork(buf);\n buf.writeInt(this.evRange);\n }\n\n @Override\n public RecipeCondition fromNetwork(FriendlyByteBuf buf) {\n super.fromNetwork(buf);\n this.evRange = buf.readInt();\n return this;\n }\n}"
},
{
"identifier": "GTNNItems",
"path": "src/main/java/org/arbor/gtnn/data/GTNNItems.java",
"snippet": "@SuppressWarnings(\"unused\")\npublic class GTNNItems {\n static {\n REGISTRATE.creativeModeTab(() -> GTNNCreativeModeTabs.MAIN_TAB);\n }\n public static final ItemEntry<Item> RADIOACTIVE_WASTE = REGISTRATE.item(\"radioactive_waste\", Item::new)\n .lang(\"放射性废料\")\n .properties(p -> p.rarity(Rarity.UNCOMMON))\n .register();\n\n public static final ItemEntry<Item> HEAVY_INGOT_T1 = REGISTRATE.item(\"heavy_ingot_t1\", Item::new)\n .lang(\"T1重型锭\")\n .properties(p -> p.rarity(Rarity.UNCOMMON))\n //.onRegister(item -> item.appendHoverText())\n .register();\n\n public static void init() {\n }\n}"
}
] | import com.gregtechceu.gtceu.api.capability.IEnergyContainer;
import com.gregtechceu.gtceu.api.capability.recipe.EURecipeCapability;
import com.gregtechceu.gtceu.api.capability.recipe.IO;
import com.gregtechceu.gtceu.api.capability.recipe.ItemRecipeCapability;
import com.gregtechceu.gtceu.api.data.chemical.ChemicalHelper;
import com.gregtechceu.gtceu.api.data.tag.TagPrefix;
import com.gregtechceu.gtceu.api.gui.GuiTextures;
import com.gregtechceu.gtceu.api.gui.fancy.IFancyUIProvider;
import com.gregtechceu.gtceu.api.gui.fancy.TooltipsPanel;
import com.gregtechceu.gtceu.api.machine.ConditionalSubscriptionHandler;
import com.gregtechceu.gtceu.api.machine.IMachineBlockEntity;
import com.gregtechceu.gtceu.api.machine.MetaMachine;
import com.gregtechceu.gtceu.api.machine.feature.IExplosionMachine;
import com.gregtechceu.gtceu.api.machine.feature.IFancyUIMachine;
import com.gregtechceu.gtceu.api.machine.feature.multiblock.IDisplayUIMachine;
import com.gregtechceu.gtceu.api.machine.feature.multiblock.IMultiPart;
import com.gregtechceu.gtceu.api.machine.multiblock.WorkableMultiblockMachine;
import com.gregtechceu.gtceu.api.recipe.GTRecipe;
import com.gregtechceu.gtceu.api.recipe.content.Content;
import com.gregtechceu.gtceu.common.data.GTMaterials;
import com.gregtechceu.gtceu.common.machine.multiblock.part.ItemBusPartMachine;
import com.gregtechceu.gtceu.utils.FormattingUtil;
import com.lowdragmc.lowdraglib.gui.modular.ModularUI;
import com.lowdragmc.lowdraglib.gui.widget.*;
import com.lowdragmc.lowdraglib.syncdata.field.ManagedFieldHolder;
import it.unimi.dsi.fastutil.longs.Long2ObjectMaps;
import net.minecraft.ChatFormatting;
import net.minecraft.MethodsReturnNonnullByDefault;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.HoverEvent;
import net.minecraft.network.chat.Style;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.crafting.Ingredient;
import org.arbor.gtnn.api.machine.multiblock.part.HighSpeedPipeBlock;
import org.arbor.gtnn.api.machine.multiblock.part.NeutronAccelerator;
import org.arbor.gtnn.api.recipe.NeutronActivatorCondition;
import org.arbor.gtnn.data.GTNNItems;
import org.jetbrains.annotations.NotNull;
import javax.annotation.Nullable;
import javax.annotation.ParametersAreNonnullByDefault;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ThreadLocalRandom; | 2,258 | package org.arbor.gtnn.api.machine.multiblock;
@ParametersAreNonnullByDefault
@MethodsReturnNonnullByDefault
public class NeutronActivator extends WorkableMultiblockMachine implements IFancyUIMachine, IDisplayUIMachine, IExplosionMachine {
public static final ManagedFieldHolder MANAGED_FIELD_HOLDER = new ManagedFieldHolder(NeutronActivator.class, WorkableMultiblockMachine.MANAGED_FIELD_HOLDER);
protected int height;
protected int eV = 0, mCeil = 0, mFloor = 0;
protected ConditionalSubscriptionHandler tickSubscription;
private int aTick = 0;
private float efficiency = 0;
public final int maxNeutronKineticEnergy = 1200000000;
public NeutronActivator(IMachineBlockEntity holder, Object... args) {
super(holder, args);
this.tickSubscription = new ConditionalSubscriptionHandler(this, this::naTick, this::isFormed);
}
//////////////////////////////////////
//*** Multiblock LifeCycle ***//
//////////////////////////////////////
@Override
public void onStructureFormed() {
height = 0;
super.onStructureFormed();
Map<Long, IO> ioMap = getMultiblockState().getMatchContext().getOrCreate("ioMap", Long2ObjectMaps::emptyMap);
for (IMultiPart part : getParts()) {
IO io = ioMap.getOrDefault(part.self().getPos().asLong(), IO.BOTH);
if (io == IO.NONE) continue;
for (var handler : part.getRecipeHandlers()) {
var handlerIO = handler.getHandlerIO();
// If IO not compatible
if (io != IO.BOTH && handlerIO != IO.BOTH && io != handlerIO) continue;
if (handler.getCapability() == EURecipeCapability.CAP && handler instanceof IEnergyContainer) {
traitSubscriptions.add(handler.addChangedListener(tickSubscription::updateSubscription));
}
} | package org.arbor.gtnn.api.machine.multiblock;
@ParametersAreNonnullByDefault
@MethodsReturnNonnullByDefault
public class NeutronActivator extends WorkableMultiblockMachine implements IFancyUIMachine, IDisplayUIMachine, IExplosionMachine {
public static final ManagedFieldHolder MANAGED_FIELD_HOLDER = new ManagedFieldHolder(NeutronActivator.class, WorkableMultiblockMachine.MANAGED_FIELD_HOLDER);
protected int height;
protected int eV = 0, mCeil = 0, mFloor = 0;
protected ConditionalSubscriptionHandler tickSubscription;
private int aTick = 0;
private float efficiency = 0;
public final int maxNeutronKineticEnergy = 1200000000;
public NeutronActivator(IMachineBlockEntity holder, Object... args) {
super(holder, args);
this.tickSubscription = new ConditionalSubscriptionHandler(this, this::naTick, this::isFormed);
}
//////////////////////////////////////
//*** Multiblock LifeCycle ***//
//////////////////////////////////////
@Override
public void onStructureFormed() {
height = 0;
super.onStructureFormed();
Map<Long, IO> ioMap = getMultiblockState().getMatchContext().getOrCreate("ioMap", Long2ObjectMaps::emptyMap);
for (IMultiPart part : getParts()) {
IO io = ioMap.getOrDefault(part.self().getPos().asLong(), IO.BOTH);
if (io == IO.NONE) continue;
for (var handler : part.getRecipeHandlers()) {
var handlerIO = handler.getHandlerIO();
// If IO not compatible
if (io != IO.BOTH && handlerIO != IO.BOTH && io != handlerIO) continue;
if (handler.getCapability() == EURecipeCapability.CAP && handler instanceof IEnergyContainer) {
traitSubscriptions.add(handler.addChangedListener(tickSubscription::updateSubscription));
}
} | if (part instanceof HighSpeedPipeBlock) height++; | 0 | 2023-11-04 07:59:02+00:00 | 4k |
WebNetMC/WebNetBedwars | src/main/java/dev/foxikle/webnetbedwars/listeners/InteractListener.java | [
{
"identifier": "WebNetBedWars",
"path": "src/main/java/dev/foxikle/webnetbedwars/WebNetBedWars.java",
"snippet": "public final class WebNetBedWars extends JavaPlugin {\n\n private GameManager gameManager;\n public static WebNetBedWars INSTANCE;\n private ItemAbilityDispatcher itemAbilityDispatcher;\n\n @Override\n public void onEnable() {\n INSTANCE = this;\n File file = new File(\"plugins/WebNetBedWars/config.yml\");\n if(!file.exists())\n this.saveResource(\"config.yml\", false);\n\n gameManager = new GameManager(this);\n registerCommands();\n registerListeners();\n gameManager.setup();\n NPCApi.initialize();\n changeBlastResistence();\n itemAbilityDispatcher = new ItemAbilityDispatcher(this);\n Menus.init(this);\n }\n\n private void changeBlastResistence(){\n //aF == resistence\n Arrays.stream(Blocks.GLASS.getClass().getSuperclass().getSuperclass().getSuperclass().getSuperclass().getDeclaredFields()).forEach(field -> {\n if(field.getType() == float.class){\n try {\n field.setAccessible(true);\n if(field.getName().equals(\"aF\")){\n field.setFloat(Blocks.GLASS, 1200.0F);\n\n field.setFloat(Blocks.BLACK_STAINED_GLASS, 1200.0F);\n field.setFloat(Blocks.WHITE_STAINED_GLASS, 1200.0F);\n field.setFloat(Blocks.CYAN_STAINED_GLASS, 1200.0F);\n field.setFloat(Blocks.LIGHT_BLUE_STAINED_GLASS, 1200.0F);\n field.setFloat(Blocks.BLUE_STAINED_GLASS, 1200.0F);\n field.setFloat(Blocks.PINK_STAINED_GLASS, 1200.0F);\n field.setFloat(Blocks.PURPLE_STAINED_GLASS, 1200.0F);\n field.setFloat(Blocks.LIME_STAINED_GLASS, 1200.0F);\n field.setFloat(Blocks.GREEN_STAINED_GLASS, 1200.0F);\n field.setFloat(Blocks.RED_STAINED_GLASS, 1200.0F);\n field.setFloat(Blocks.ORANGE_STAINED_GLASS, 1200.0F);\n field.setFloat(Blocks.YELLOW_STAINED_GLASS, 1200.0F);\n field.setFloat(Blocks.LIGHT_GRAY_STAINED_GLASS, 1200.0F);\n field.setFloat(Blocks.GRAY_STAINED_GLASS, 1200.0F);\n field.setFloat(Blocks.BROWN_STAINED_GLASS, 1200.0F);\n field.setFloat(Blocks.MAGENTA_STAINED_GLASS, 1200.0F);\n\n field.setFloat(Blocks.BLACK_BED, 1200.0F);\n field.setFloat(Blocks.WHITE_BED, 1200.0F);\n field.setFloat(Blocks.CYAN_BED, 1200.0F);\n field.setFloat(Blocks.LIGHT_BLUE_BED, 1200.0F);\n field.setFloat(Blocks.BLUE_BED, 1200.0F);\n field.setFloat(Blocks.PINK_BED, 1200.0F);\n field.setFloat(Blocks.PURPLE_BED, 1200.0F);\n field.setFloat(Blocks.LIME_BED, 1200.0F);\n field.setFloat(Blocks.GREEN_BED, 1200.0F);\n field.setFloat(Blocks.RED_BED, 1200.0F);\n field.setFloat(Blocks.ORANGE_BED, 1200.0F);\n field.setFloat(Blocks.YELLOW_BED, 1200.0F);\n field.setFloat(Blocks.LIGHT_GRAY_BED, 1200.0F);\n field.setFloat(Blocks.GRAY_BED, 1200.0F);\n field.setFloat(Blocks.BROWN_BED, 1200.0F);\n field.setFloat(Blocks.MAGENTA_BED, 1200.0F);\n }\n } catch (IllegalAccessException e) {\n throw new RuntimeException(e);\n }\n }\n });\n\n }\n\n @Override\n public void onDisable() {\n gameManager.cleanup();\n }\n\n private void registerListeners(){\n getServer().getPluginManager().registerEvents(new DamageListener(this), this);\n getServer().getPluginManager().registerEvents(new JoinListener(this), this);\n getServer().getPluginManager().registerEvents(new LeaveListener(this), this);\n getServer().getPluginManager().registerEvents(new BlockBreakListener(this), this);\n getServer().getPluginManager().registerEvents(new BlockPlaceListener(this), this);\n getServer().getPluginManager().registerEvents(new ExplosionListener(this), this);\n getServer().getPluginManager().registerEvents(new InteractListener(this), this);\n getServer().getPluginManager().registerEvents(new MoveListener(this), this);\n getServer().getPluginManager().registerEvents(new GamemodeChangeListener(this), this);\n getServer().getPluginManager().registerEvents(new ArmorEquipListener(this), this);\n getServer().getPluginManager().registerEvents(new InventoryClickListener(this), this);\n getServer().getPluginManager().registerEvents(new DropItemListener(this), this);\n }\n\n\n\n private void registerCommands(){\n getCommand(\"debug\").setExecutor(new DebugCommand(this));\n getCommand(\"item\").setExecutor(new ItemCommand());\n getCommand(\"item\").setAliases(List.of(\"i\"));\n }\n\n public GameManager getGameManager() {\n return gameManager;\n }\n\n public ItemAbilityDispatcher getItemAbilityDispatcher() {\n return itemAbilityDispatcher;\n }\n}"
},
{
"identifier": "Items",
"path": "src/main/java/dev/foxikle/webnetbedwars/utils/Items.java",
"snippet": "public class Items {\n private static final WebNetBedWars plugin = WebNetBedWars.INSTANCE;\n private static final Map<String, ItemStack> itemRegistry = new HashMap<>();\n public static NamespacedKey NAMESPACE = new NamespacedKey(plugin, \"bwID\");\n public static NamespacedKey MOVE_BLACKLIST = new NamespacedKey(plugin, \"move_blacklist\");\n public static NamespacedKey ALLOWED_SLOTS = new NamespacedKey(plugin, \"allowed_slots\");\n public static NamespacedKey NO_DROP = new NamespacedKey(plugin, \"no_drop\");\n\n // item constants\n\n // spectator items\n public static ItemStack SPECTATOR_TARGET_SELECTOR = createItem(ChatColor.GREEN + \"Target Selector\", \"SPECTATOR_COMPASS\", Material.COMPASS, true, true, List.of(0), ChatColor.GRAY + \"Right click to teleport to a player!\");\n public static ItemStack SPECTATOR_SPEED_SELECTOR = createItem(ChatColor.AQUA + \"Speed Selector\", \"SPECTATOR_BOOTS\", Material.HEART_OF_THE_SEA, true, true, List.of(4), ChatColor.GRAY + \"Right click to change flight speed.\");\n public static ItemStack SPECTATOR_LOBBY_REQEST = createItem(ChatColor.RED + \"Go to Lobby\", \"LOBBY_REQUEST\", Material.RED_BED, true, true, List.of(8), ChatColor.GOLD + \"To the lobby!\");\n public static ItemStack SPECTATOR_ARMOR = createItem(\"\", \"SPECTATOR_ARMOR\", Material.BARRIER, true, true, List.of(36, 37, 38, 39));\n\n // shop items\n public static ItemStack FIREBALL = createItem(\"Fireball\", \"FIREBALL\", Material.FIRE_CHARGE, false, false, List.of());\n public static ItemStack TNT = createItem(\"TNT\", \"TNT\", Material.TNT, false, false, List.of());\n\n private static ItemStack createItem(String displayname, String id, Material type, boolean noMove, boolean noDrop, List<Integer> allowedSlots, String... lore){\n ItemStack item = new ItemStack(type);\n ItemMeta meta = item.getItemMeta();\n\n meta.setDisplayName(displayname);\n meta.setLore(List.of(lore));\n meta.addItemFlags(ItemFlag.values());\n PersistentDataContainer pdc = meta.getPersistentDataContainer();\n if(noDrop) {\n pdc.set(NO_DROP, PersistentDataType.BOOLEAN, true);\n }\n if(noMove) {\n pdc.set(MOVE_BLACKLIST, PersistentDataType.BOOLEAN, true);\n pdc.set(ALLOWED_SLOTS, PersistentDataType.INTEGER_ARRAY, allowedSlots.stream().mapToInt(Integer::intValue).toArray());\n }\n pdc.set(NAMESPACE, PersistentDataType.STRING, id);\n\n item.setItemMeta(meta);\n itemRegistry.put(id, item);\n return item;\n }\n\n @Nullable\n public static ItemStack get(String id){\n return itemRegistry.get(id);\n }\n\n public static Set<String> getItemIDs(){\n return itemRegistry.keySet();\n }\n}"
}
] | import dev.foxikle.webnetbedwars.WebNetBedWars;
import dev.foxikle.webnetbedwars.utils.Items;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.persistence.PersistentDataType; | 2,196 | package dev.foxikle.webnetbedwars.listeners;
public class InteractListener implements Listener {
private final WebNetBedWars plugin;
public InteractListener(WebNetBedWars plugin) {
this.plugin = plugin;
}
@EventHandler
public void OnInteract(PlayerInteractEvent event){
if(event.getItem() == null) return;
if(event.getItem().getItemMeta() == null) return; | package dev.foxikle.webnetbedwars.listeners;
public class InteractListener implements Listener {
private final WebNetBedWars plugin;
public InteractListener(WebNetBedWars plugin) {
this.plugin = plugin;
}
@EventHandler
public void OnInteract(PlayerInteractEvent event){
if(event.getItem() == null) return;
if(event.getItem().getItemMeta() == null) return; | if(event.getItem().getItemMeta().getPersistentDataContainer().getKeys().contains(Items.NAMESPACE)){ | 1 | 2023-11-04 00:18:20+00:00 | 4k |
satisfyu/HerbalBrews | common/src/main/java/satisfyu/herbalbrews/client/recipebook/TeaKettleRecipeBook.java | [
{
"identifier": "HerbalBrews",
"path": "common/src/main/java/satisfyu/herbalbrews/HerbalBrews.java",
"snippet": "public class HerbalBrews {\n public static final String MOD_ID = \"herbalbrews\";\n public static final Logger LOGGER = LogManager.getLogger(MOD_ID);\n\n public static void init() {\n EffectRegistry.init();\n ObjectRegistry.init();\n BlockEntityRegistry.init();\n SoundEventRegistry.init();\n RecipeTypeRegistry.init();\n ScreenHandlerTypeRegistry.init();\n TabRegistry.init();\n }\n}"
},
{
"identifier": "TeaKettleRecipe",
"path": "common/src/main/java/satisfyu/herbalbrews/recipe/TeaKettleRecipe.java",
"snippet": "public class TeaKettleRecipe implements Recipe<Container> {\n\n final ResourceLocation id;\n private final NonNullList<Ingredient> inputs;\n private final ItemStack output;\n\n public TeaKettleRecipe(ResourceLocation id, NonNullList<Ingredient> inputs, ItemStack output) {\n this.id = id;\n this.inputs = inputs;\n this.output = output;\n }\n\n @Override\n public boolean matches(Container inventory, Level world) {\n return GeneralUtil.matchesRecipe(inventory, inputs, 0, 6);\n }\n\n public ItemStack assemble() {\n return assemble(null, null);\n }\n\n @Override\n public ItemStack assemble(Container inventory, RegistryAccess registryManager) {\n return this.output.copy();\n }\n\n @Override\n public boolean canCraftInDimensions(int width, int height) {\n return false;\n }\n\n public ItemStack getResultItem() {\n return getResultItem(null);\n }\n\n @Override\n public ItemStack getResultItem(RegistryAccess registryManager) {\n return this.output;\n }\n\n @Override\n public ResourceLocation getId() {\n return id;\n }\n\n @Override\n public RecipeSerializer<?> getSerializer() {\n return RecipeTypeRegistry.TEAK_KETTLE_RECIPE_SERIALIZER.get();\n }\n\n @Override\n public RecipeType<?> getType() {\n return RecipeTypeRegistry.TEA_KETTLE_RECIPE_TYPE.get();\n }\n\n @Override\n public NonNullList<Ingredient> getIngredients() {\n return this.inputs;\n }\n\n @Override\n public boolean isSpecial() {\n return true;\n }\n\n public static class Serializer implements RecipeSerializer<TeaKettleRecipe> {\n\n @Override\n public TeaKettleRecipe fromJson(ResourceLocation id, JsonObject json) {\n final var ingredients = GeneralUtil.deserializeIngredients(GsonHelper.getAsJsonArray(json, \"ingredients\"));\n if (ingredients.isEmpty()) {\n throw new JsonParseException(\"No ingredients for Tea Kettle Recipe\");\n } else if (ingredients.size() > 6) {\n throw new JsonParseException(\"Too many ingredients for Tea Kettle Recipe\");\n } else {\n return new TeaKettleRecipe(id, ingredients, ShapedRecipe.itemStackFromJson(GsonHelper.getAsJsonObject(json, \"result\")));\n }\n }\n\n @Override\n public TeaKettleRecipe fromNetwork(ResourceLocation id, FriendlyByteBuf buf) {\n final var ingredients = NonNullList.withSize(buf.readVarInt(), Ingredient.EMPTY);\n ingredients.replaceAll(ignored -> Ingredient.fromNetwork(buf));\n return new TeaKettleRecipe(id, ingredients, buf.readItem());\n }\n\n @Override\n public void toNetwork(FriendlyByteBuf buf, TeaKettleRecipe recipe) {\n buf.writeVarInt(recipe.inputs.size());\n recipe.inputs.forEach(entry -> entry.toNetwork(buf));\n buf.writeItem(recipe.output);\n }\n }\n\n public static class Type implements RecipeType<TeaKettleRecipe> {\n private Type() {\n }\n\n public static final Type INSTANCE = new Type();\n\n public static final String ID = \"cooking\";\n }\n}"
},
{
"identifier": "RecipeTypeRegistry",
"path": "common/src/main/java/satisfyu/herbalbrews/registry/RecipeTypeRegistry.java",
"snippet": "public class RecipeTypeRegistry {\n\n private static final DeferredRegister<RecipeSerializer<?>> RECIPE_SERIALIZERS = DeferredRegister.create(HerbalBrews.MOD_ID, Registries.RECIPE_SERIALIZER);\n private static final DeferredRegister<RecipeType<?>> RECIPE_TYPES = DeferredRegister.create(HerbalBrews.MOD_ID, Registries.RECIPE_TYPE);\n\n public static final RegistrySupplier<RecipeType<TeaKettleRecipe>> TEA_KETTLE_RECIPE_TYPE = create(\"kettle_brewing\");\n public static final RegistrySupplier<RecipeSerializer<TeaKettleRecipe>> TEAK_KETTLE_RECIPE_SERIALIZER = create(\"kettle_brewing\", TeaKettleRecipe.Serializer::new);\n public static final RegistrySupplier<RecipeType<CauldronRecipe>> CAULDRON_RECIPE_TYPE = create(\"cauldron_brewing\");\n public static final RegistrySupplier<RecipeSerializer<CauldronRecipe>> CAULDRON_RECIPE_SERIALIZER = create(\"cauldron_brewing\", CauldronRecipe.Serializer::new);\n\n private static <T extends Recipe<?>> RegistrySupplier<RecipeSerializer<T>> create(String name, Supplier<RecipeSerializer<T>> serializer) {\n return RECIPE_SERIALIZERS.register(name, serializer);\n }\n\n private static <T extends Recipe<?>> RegistrySupplier<RecipeType<T>> create(String name) {\n Supplier<RecipeType<T>> type = () -> new RecipeType<>() {\n @Override\n public String toString() {\n return name;\n }\n };\n return RECIPE_TYPES.register(name, type);\n }\n\n public static void init() {\n RECIPE_SERIALIZERS.register();\n RECIPE_TYPES.register();\n }\n\n\n}"
}
] | import de.cristelknight.doapi.client.recipebook.screen.widgets.PrivateRecipeBookWidget;
import net.minecraft.client.Minecraft;
import net.minecraft.core.RegistryAccess;
import net.minecraft.network.chat.Component;
import net.minecraft.util.RandomSource;
import net.minecraft.world.Container;
import net.minecraft.world.inventory.ClickType;
import net.minecraft.world.inventory.Slot;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.crafting.Ingredient;
import net.minecraft.world.item.crafting.Recipe;
import net.minecraft.world.item.crafting.RecipeType;
import org.jetbrains.annotations.Nullable;
import satisfyu.herbalbrews.HerbalBrews;
import satisfyu.herbalbrews.recipe.TeaKettleRecipe;
import satisfyu.herbalbrews.registry.RecipeTypeRegistry;
import java.util.List; | 1,641 | package satisfyu.herbalbrews.client.recipebook;
public class TeaKettleRecipeBook extends PrivateRecipeBookWidget {
private static final Component TOGGLE_COOKABLE_TEXT;
public TeaKettleRecipeBook() {
}
@Override
protected RecipeType<? extends Recipe<Container>> getRecipeType() {
return RecipeTypeRegistry.TEA_KETTLE_RECIPE_TYPE.get();
}
@Override
public void insertRecipe(Recipe<?> recipe) {
int usedInputSlots = 1;
| package satisfyu.herbalbrews.client.recipebook;
public class TeaKettleRecipeBook extends PrivateRecipeBookWidget {
private static final Component TOGGLE_COOKABLE_TEXT;
public TeaKettleRecipeBook() {
}
@Override
protected RecipeType<? extends Recipe<Container>> getRecipeType() {
return RecipeTypeRegistry.TEA_KETTLE_RECIPE_TYPE.get();
}
@Override
public void insertRecipe(Recipe<?> recipe) {
int usedInputSlots = 1;
| HerbalBrews.LOGGER.error(recipe.getIngredients().size()); | 0 | 2023-11-05 16:46:52+00:00 | 4k |
sizdshi/download-server | server/main/src/main/java/com/example/service/impl/DownloadServiceImpl.java | [
{
"identifier": "ErrorCode",
"path": "server/common/src/main/java/com/example/common/ErrorCode.java",
"snippet": "public enum ErrorCode {\r\n /**\r\n * 成功\r\n */\r\n SUCCESS(0, \"ok\"),\r\n /**\r\n * 请求参数错误\r\n */\r\n PARAMS_ERROR(40000, \"请求参数错误\"),\r\n /**\r\n * 未登录\r\n */\r\n NOT_LOGIN_ERROR(40100, \"未登录\"),\r\n /**\r\n * 无权限\r\n */\r\n NO_AUTH_ERROR(40101, \"无权限\"),\r\n /**\r\n * 账号已封禁\r\n */\r\n PROHIBITED(40001, \"账号已封禁\"),\r\n /**\r\n * 请求数据不存在\r\n */\r\n NOT_FOUND_ERROR(40400, \"请求数据不存在\"),\r\n /**\r\n * 禁止访问\r\n */\r\n FORBIDDEN_ERROR(40300, \"禁止访问\"),\r\n /**\r\n * 系统内部异常\r\n */\r\n SYSTEM_ERROR(50000, \"系统内部异常\"),\r\n /**\r\n * 操作错误\r\n */\r\n FILE_ERROR(40500, \"下载失败,文件过大,请下载2GB以下文件\"),\r\n /**\r\n * 操作错误\r\n */\r\n OPERATION_ERROR(50001, \"操作失败\");\r\n\r\n\r\n\r\n /**\r\n * 状态码\r\n */\r\n private final int code;\r\n\r\n /**\r\n * 信息\r\n */\r\n private final String message;\r\n\r\n ErrorCode(int code, String message) {\r\n this.code = code;\r\n this.message = message;\r\n }\r\n\r\n public int getCode() {\r\n return code;\r\n }\r\n\r\n public String getMessage() {\r\n return message;\r\n }\r\n}\r"
},
{
"identifier": "CommonConstant",
"path": "server/main/src/main/java/com/example/constant/CommonConstant.java",
"snippet": "public interface CommonConstant {\r\n /**\r\n * 升序\r\n */\r\n String SORT_ORDER_ASC = \"ascend\";\r\n\r\n /**\r\n * 降序\r\n */\r\n String SORT_ORDER_DESC = \" descend\";\r\n}\r"
},
{
"identifier": "DownloadRequest",
"path": "server/main/src/main/java/com/example/model/dto/DownloadRequest.java",
"snippet": "@Data\r\n@EqualsAndHashCode(callSuper = true)\r\npublic class DownloadRequest extends PageRequest implements Serializable {\r\n\r\n /**\r\n * id\r\n */\r\n private Long id;\r\n\r\n /**\r\n * 文件名\r\n */\r\n private String file_name;\r\n\r\n /**\r\n * 下载地址\r\n */\r\n private String url;\r\n\r\n /**\r\n * 文件状态(STATUS_NONE: 默认状态 STATUS_WAITING : 等待下载 STATUS_DOWNLOADING : 正在下载\r\n STATUS_PAUSED : 停止下载 STATUS_DOWNLOADED : 下载完成)\r\n */\r\n private String status;\r\n\r\n private static final long serialVersionUID = 1L;\r\n}\r"
},
{
"identifier": "ThreadRequest",
"path": "server/main/src/main/java/com/example/model/dto/ThreadRequest.java",
"snippet": "@Data\r\npublic class ThreadRequest implements Serializable {\r\n private String id;\r\n\r\n private Long count;\r\n\r\n private static final long serialVersionUID = 1L;\r\n}\r"
},
{
"identifier": "Download",
"path": "server/main/src/main/java/com/example/model/entity/Download.java",
"snippet": "@TableName(value =\"download\")\n@Data\npublic class Download implements Serializable {\n /**\n * id\n */\n @TableId(type = IdType.ASSIGN_ID)\n private Long id;\n\n /**\n * 文件名\n */\n private String file_name;\n\n /**\n * 下载地址\n */\n private String url;\n\n /**\n * 发布人\n */\n private String user_id;\n\n /**\n * 当前线程数\n */\n private Long count;\n\n /**\n * 文件状态(STATUS_NONE: 默认状态 STATUS_WAITING : 等待下载 STATUS_DOWNLOADING : 正在下载\n STATUS_PAUSED : 停止下载 STATUS_DOWNLOADED : 下载完成)\n */\n private String status;\n\n /**\n * 文件存储路径\n */\n private String file_url;\n\n /**\n * http or bt\n */\n private String task_type;\n\n /**\n * bt种子信息\n */\n private String torrent;\n\n /**\n * 曾经上传过的分片号\n */\n private Long bytes_download;\n\n /**\n * 文件的总分片数\n */\n private Long total_chunks;\n\n /**\n * 资源大小,单位为字节\n */\n private Long upload_file_size;\n\n /**\n * 文件MD5值\n */\n private String md5;\n\n /**\n * 下载时长\n */\n private String total_time;\n\n /**\n * 创建时间\n */\n @JsonFormat(pattern = \"yyyy-MM-dd HH:mm:ss\",timezone = \"GMT+8\")\n private Date create_time;\n\n /**\n * 更新时间\n */\n @JsonFormat(pattern = \"yyyy-MM-dd HH:mm:ss\",timezone = \"GMT+8\")\n private Date update_time;\n\n /**\n * 是否删除\n */\n\n private Integer is_delete;\n\n @TableField(exist = false)\n private static final long serialVersionUID = 1L;\n}"
},
{
"identifier": "DownloadVO",
"path": "server/main/src/main/java/com/example/model/vo/DownloadVO.java",
"snippet": "@Data\r\npublic class DownloadVO implements Serializable {\r\n /**\r\n * id\r\n */\r\n private String id;\r\n\r\n /**\r\n * 文件名\r\n */\r\n private String file_name;\r\n\r\n /**\r\n * 下载地址\r\n */\r\n private String url;\r\n\r\n /**\r\n * 当前线程数\r\n */\r\n private Long count;\r\n\r\n /**\r\n * 文件状态(STATUS_NONE: 默认状态 STATUS_WAITING : 等待下载 STATUS_DOWNLOADING : 正在下载\r\n STATUS_PAUSED : 停止下载 STATUS_DOWNLOADED : 下载完成)\r\n */\r\n private String status;\r\n\r\n\r\n\r\n /**\r\n * http or bt\r\n */\r\n private String task_type;\r\n\r\n\r\n\r\n /**\r\n * 资源大小,单位为字节\r\n */\r\n private Long upload_file_size;\r\n\r\n /**\r\n * 下载时长\r\n */\r\n private String total_time;\r\n\r\n /**\r\n * 创建时间\r\n */\r\n @JsonFormat(pattern = \"yyyy-MM-dd HH:mm:ss\",timezone = \"GMT+8\")\r\n private Date create_time;\r\n\r\n /**\r\n * 更新时间\r\n */\r\n @JsonFormat(pattern = \"yyyy-MM-dd HH:mm:ss\",timezone = \"GMT+8\")\r\n private Date update_time;\r\n\r\n\r\n private static final long serialVersionUID = 1L;\r\n\r\n public static Download voToObj(DownloadVO downloadVO){\r\n if (downloadVO == null) {\r\n return null;\r\n }\r\n Download download = new Download();\r\n BeanUtils.copyProperties(downloadVO,download);\r\n long id = Long.parseLong(downloadVO.getId());\r\n download.setId(id);\r\n return download;\r\n }\r\n\r\n public static DownloadVO objToVo(Download download){\r\n if (download == null) {\r\n return null;\r\n }\r\n DownloadVO downloadVO = new DownloadVO();\r\n BeanUtils.copyProperties(download,downloadVO);\r\n String id = Long.toString(download.getId());\r\n downloadVO.setId(id);\r\n return downloadVO;\r\n }\r\n}\r"
},
{
"identifier": "SqlUtils",
"path": "server/main/src/main/java/com/example/utils/SqlUtils.java",
"snippet": "public class SqlUtils {\r\n /**\r\n * 校验排序字段是否合法(防止 SQL 注入)\r\n *\r\n * @param sortField\r\n * @return\r\n */\r\n public static boolean validSortField(String sortField) {\r\n if (StringUtils.isBlank(sortField)) {\r\n return false;\r\n }\r\n return !StringUtils.containsAny(sortField, \"=\", \"(\", \")\", \" \");\r\n }\r\n}\r"
},
{
"identifier": "BusinessException",
"path": "server/common/src/main/java/com/example/exception/BusinessException.java",
"snippet": "public class BusinessException extends RuntimeException{\r\n private static final long serialVersionUID = 2942420535500634982L;\r\n private final int code;\r\n\r\n\r\n public BusinessException(int code,String message) {\r\n super(message);\r\n this.code = code;\r\n }\r\n\r\n public BusinessException(ErrorCode errorCode){\r\n super(errorCode.getMessage());\r\n this.code = errorCode.getCode();\r\n }\r\n\r\n /**\r\n * 自定义错误消息\r\n * @param errorCode\r\n * @param message\r\n */\r\n public BusinessException(ErrorCode errorCode,String message){\r\n super(message);\r\n this.code = errorCode.getCode();\r\n }\r\n\r\n public int getCode(){\r\n return code;\r\n }\r\n\r\n\r\n}\r"
},
{
"identifier": "DownloadStatus",
"path": "server/main/src/main/java/com/example/model/enums/DownloadStatus.java",
"snippet": "@Getter\r\npublic enum DownloadStatus {\r\n STATUS_NONE(\"默认状态\",\"STATUS_NONE\"),\r\n\r\n STATUS_WAITING(\"等待下载\",\"STATUS_WAITING\"),\r\n\r\n STATUS_DOWNLOADING(\"正在下载\",\"downloaded\"),\r\n\r\n STATUS_PAUSED(\"停止下载\",\"pending\"),\r\n\r\n STATUS_DELETE(\"已删除\",\"canceled\"),\r\n\r\n STATUS_DOWNLOADED(\"下载完成\",\"downloading\");\r\n\r\n private final String text;\r\n\r\n private final String value;\r\n\r\n DownloadStatus(String text,String value){\r\n this.text = text;\r\n this.value = value;\r\n }\r\n\r\n\r\n}\r"
},
{
"identifier": "DownloadService",
"path": "server/main/src/main/java/com/example/service/DownloadService.java",
"snippet": "public interface DownloadService extends IService<Download> {\r\n\r\n long changeThread(ThreadRequest threadRequest, HttpServletRequest request);\r\n\r\n long start(List<String> ids,HttpServletRequest request);\r\n\r\n long suspend(List<String> ids, HttpServletRequest request);\r\n\r\n long restart(List<String> ids, HttpServletRequest request);\r\n\r\n long delete(List<String> ids);\r\n\r\n String submit(String url);\r\n\r\n\r\n\r\n Page<DownloadVO> getDownloadVOPage(Page<Download> downloadPage,HttpServletRequest request);\r\n\r\n Page<DownloadVO> listDownloadVOByPage(DownloadRequest downloadRequest,HttpServletRequest request);\r\n\r\n /**\r\n * 获取查询条件\r\n *\r\n * @param downloadRequest\r\n * @return\r\n */\r\n QueryWrapper<Download> getQueryWrapper(DownloadRequest downloadRequest);\r\n\r\n long suspend(List<String> ids);\r\n\r\n}\r"
},
{
"identifier": "DownloadMapper",
"path": "server/main/src/main/java/com/example/mapper/DownloadMapper.java",
"snippet": "public interface DownloadMapper extends BaseMapper<Download> {\r\n\r\n\r\n int queryByIds(@Param(\"ew\") LambdaUpdateWrapper<Download> wrapper);\r\n}\r"
}
] | import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.common.ErrorCode;
import com.example.constant.CommonConstant;
import com.example.model.dto.DownloadRequest;
import com.example.model.dto.ThreadRequest;
import com.example.model.entity.Download;
import com.example.model.vo.DownloadVO;
import com.example.utils.SqlUtils;
import com.example.exception.BusinessException;
import com.example.model.enums.DownloadStatus;
import com.example.service.DownloadService;
import com.example.mapper.DownloadMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import org.apache.commons.collections4.CollectionUtils;
| 2,821 | package com.example.service.impl;
/**
* @author sizd-shi
* @description 针对表【download(上传下载表)】的数据库操作Service实现
* @createDate 2023-11-09 14:40:30
*/
@Service
@Slf4j
| package com.example.service.impl;
/**
* @author sizd-shi
* @description 针对表【download(上传下载表)】的数据库操作Service实现
* @createDate 2023-11-09 14:40:30
*/
@Service
@Slf4j
| public class DownloadServiceImpl extends ServiceImpl<DownloadMapper, Download>
| 10 | 2023-11-02 06:09:03+00:00 | 4k |
RapierXbox/Benium-Client | src/main/java/net/rapierxbox/beniumclient/hacks/PacketReach.java | [
{
"identifier": "BeniumClient",
"path": "src/main/java/net/rapierxbox/beniumclient/BeniumClient.java",
"snippet": "public class BeniumClient implements ModInitializer {\n\tpublic static final Logger LOGGER = LoggerFactory.getLogger(\"modid\");\n\tprivate static BeniumClient instance;\n\tpublic static List<String> hacks_string = new ArrayList();\n\n\t@Override\n\tpublic void onInitialize() {\n\t\tif (instance == null) instance = this;\n\t\tClientTickEvents.END_CLIENT_TICK.register(this::tick);\n\t\tHacks.init();\n\t\tLOGGER.info(\"Benium Client!\");\n\t}\n\n\n\tpublic void tick(MinecraftClient client) {\n\t\tclient.getWindow().setTitle(\"Benium Client V1\");\n\t\tclient.updateWindowTitle();\n\t\tHacks.tick(client);\n\n\t}\n\n}"
},
{
"identifier": "BUtil",
"path": "src/main/java/net/rapierxbox/beniumclient/util/BUtil.java",
"snippet": "public class BUtil {\r\n public static Entity getNearestEntity(MinecraftClient client) {\r\n Entity best_entity = null;\r\n Double best_dis = 6.0;\r\n\r\n for (Entity entity : client.world.getEntities()) {\r\n if (!entity.isPlayer() && entity.isAttackable() && entity.isAlive()) {\r\n if (BMath.getdistance(client.player.getPos(), entity.getPos()) < best_dis) {\r\n best_entity = entity;\r\n best_dis = BMath.getdistance(client.player.getPos(), entity.getPos());\r\n }\r\n }\r\n }\r\n return best_entity;\r\n }\r\n\r\n public static Entity getNearestEntity(MinecraftClient client, BlockPos pos) {\r\n Entity best_entity = null;\r\n Double best_dis = 5.0;\r\n\r\n for (Entity entity : client.world.getEntities()) {\r\n if (!entity.isPlayer() && entity.isAttackable() && entity.isAlive()) {\r\n if (BMath.getdistance(new Vec3d(pos.getX(), pos.getY(), pos.getZ()), entity.getPos()) < best_dis) {\r\n best_entity = entity;\r\n best_dis = BMath.getdistance(new Vec3d(pos.getX(), pos.getY(), pos.getZ()), entity.getPos());\r\n }\r\n }\r\n }\r\n return best_entity;\r\n }\r\n}\r"
},
{
"identifier": "Hack",
"path": "src/main/java/net/rapierxbox/beniumclient/util/Hack.java",
"snippet": "public class Hack {\r\n private final String name;\r\n\r\n private static boolean enabled;\r\n public Hack(String name)\r\n {\r\n this.name = name;\r\n }\r\n\r\n public static final boolean isEnabled()\r\n {\r\n return enabled;\r\n }\r\n\r\n public String getName() {return this.name;}\r\n\r\n public final void setEnabled(boolean enabled)\r\n {\r\n if (this.enabled == enabled){\r\n return;\r\n }\r\n this.enabled = enabled;\r\n\r\n if (enabled) {\r\n onEnable();\r\n } else {\r\n onDisable();\r\n }\r\n }\r\n\r\n public final String getEnabledString() {\r\n if (enabled) {\r\n return name + \" enabled\";\r\n } else {\r\n return name + \" disabled\";\r\n }\r\n }\r\n\r\n public final void toggle() {\r\n setEnabled(!enabled);\r\n }\r\n\r\n protected void onEnable()\r\n {\r\n\r\n }\r\n\r\n protected void onDisable()\r\n {\r\n\r\n }\r\n\r\n protected void tick(MinecraftClient client) {\r\n\r\n }\r\n}\r"
},
{
"identifier": "Raycast",
"path": "src/main/java/net/rapierxbox/beniumclient/util/Raycast.java",
"snippet": "public class Raycast {\r\n\r\n public static HitResult raycast(\r\n Entity entity,\r\n double maxDistance,\r\n boolean includeFluids,\r\n Vec3d direction\r\n ) {\r\n Vec3d end = entity.getCameraPosVec(0).add(direction.multiply(maxDistance));\r\n return entity.world.raycast(new RaycastContext(\r\n entity.getCameraPosVec(0),\r\n end,\r\n RaycastContext.ShapeType.OUTLINE,\r\n includeFluids ? RaycastContext.FluidHandling.ANY : RaycastContext.FluidHandling.NONE,\r\n entity\r\n ));\r\n }\r\n\r\n public static HitResult raycastInDirection(MinecraftClient client, Vec3d direction) {\r\n Entity entity = client.getCameraEntity();\r\n if (entity == null || client.world == null) {\r\n return null;\r\n }\r\n\r\n double reachDistance = 100.0;//Change this to extend the reach\r\n HitResult target = raycast(entity, reachDistance, false, direction);\r\n boolean tooFar = false;\r\n double extendedReach = reachDistance;\r\n\r\n Vec3d cameraPos = entity.getCameraPosVec(0);\r\n\r\n extendedReach = extendedReach * extendedReach;\r\n if (target != null) {\r\n extendedReach = target.getPos().squaredDistanceTo(cameraPos);\r\n }\r\n\r\n Vec3d vec3d3 = cameraPos.add(direction.multiply(reachDistance));\r\n Box box = entity\r\n .getBoundingBox()\r\n .stretch(entity.getRotationVec(1.0F).multiply(reachDistance))\r\n .expand(1.0D, 1.0D, 1.0D);\r\n EntityHitResult entityHitResult = ProjectileUtil.raycast(\r\n entity,\r\n cameraPos,\r\n vec3d3,\r\n box,\r\n (entityx) -> !entityx.isSpectator(),\r\n extendedReach\r\n );\r\n\r\n if (entityHitResult == null) {\r\n return target;\r\n }\r\n\r\n Entity entity2 = entityHitResult.getEntity();\r\n Vec3d vec3d4 = entityHitResult.getPos();\r\n double g = cameraPos.squaredDistanceTo(vec3d4);\r\n if (tooFar && g > 9.0D) {\r\n return null;\r\n } else if (g < extendedReach || target == null) {\r\n target = entityHitResult;\r\n if (entity2 instanceof LivingEntity || entity2 instanceof ItemFrameEntity) {\r\n client.targetedEntity = entity2;\r\n }\r\n }\r\n\r\n return target;\r\n }\r\n}\r"
}
] | import net.minecraft.client.MinecraftClient;
import net.minecraft.entity.Entity;
import net.minecraft.network.packet.c2s.play.PlayerInteractEntityC2SPacket;
import net.minecraft.network.packet.c2s.play.PlayerMoveC2SPacket;
import net.minecraft.text.Text;
import net.minecraft.util.hit.BlockHitResult;
import net.minecraft.util.hit.EntityHitResult;
import net.minecraft.util.hit.HitResult;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Vec3d;
import net.rapierxbox.beniumclient.BeniumClient;
import net.rapierxbox.beniumclient.util.BUtil;
import net.rapierxbox.beniumclient.util.Hack;
import net.rapierxbox.beniumclient.util.Raycast;
| 1,713 | package net.rapierxbox.beniumclient.hacks;
public class PacketReach extends Hack {
public PacketReach() {
super("PacketReach");
}
@Override
protected void tick(MinecraftClient client) {
if (client.options.attackKey.wasPressed()) {
client.player.sendMessage(Text.of("Attack"));
attack(client, getTarget(client));
}
}
public static Entity getTarget (MinecraftClient client) {
Vec3d cameraDirection = client.cameraEntity.getRotationVector();
HitResult hit = Raycast.raycastInDirection(client, cameraDirection);
HitResult.Type hittype = hit.getType();
| package net.rapierxbox.beniumclient.hacks;
public class PacketReach extends Hack {
public PacketReach() {
super("PacketReach");
}
@Override
protected void tick(MinecraftClient client) {
if (client.options.attackKey.wasPressed()) {
client.player.sendMessage(Text.of("Attack"));
attack(client, getTarget(client));
}
}
public static Entity getTarget (MinecraftClient client) {
Vec3d cameraDirection = client.cameraEntity.getRotationVector();
HitResult hit = Raycast.raycastInDirection(client, cameraDirection);
HitResult.Type hittype = hit.getType();
| BeniumClient.LOGGER.info("Type=" + hittype.toString());
| 0 | 2023-11-09 13:23:48+00:00 | 4k |
SatyaRajAwasth1/smart-credit-manager | src/main/java/np/com/satyarajawasthi/smartcreditmanager/controller/LoginController.java | [
{
"identifier": "UserManager",
"path": "src/main/java/np/com/satyarajawasthi/smartcreditmanager/manager/UserManager.java",
"snippet": "public class UserManager {\n private static final String CONFIG_URL = \"/np/com/satyarajawasthi/smartcreditmanager/config.properties\";\n private static final Logger logger = Logger.getLogger(UserManager.class.getName());\n\n public static boolean isFirstLogin() {\n try {\n // Check if it's the first login by reading from the properties file\n if (isFirstLoginInPropertiesFile()) {\n if (!UserRepository.isUserTableExists()) {\n return true; // Table doesn't exist yet, consider it as the first login\n }\n int passwordUpdatedValue = UserRepository.getPasswordUpdatedValue();\n return (passwordUpdatedValue == 0);\n }\n } catch (SQLException e) {\n throw new RuntimeException(e);\n }\n return false;\n }\n\n public static void onFirstLogin\n () {\n Connection connection = null;\n try {\n connection = getConnection();\n connection.setAutoCommit(false); // Start a transaction\n\n UserRepository.createUserTable(connection);\n UserRepository.insertInitialUserRecords(connection);\n UserRepository.restrictUserInsertion(connection);\n CredentialRepository.createCredentialTable(connection);\n connection.commit(); // Commit the transaction\n\n logger.info(\"Users & credentials table created, default user inserted, and insertion restricted.\");\n } catch (SQLException e) {\n if (connection != null) {\n try {\n connection.rollback(); // Rollback in case of an error\n } catch (SQLException rollbackException) {\n logger.log(Level.WARNING, \"Error during rollback: {0}\", rollbackException.getMessage());\n } finally {\n closeConnection();\n }\n }\n logger.log(Level.SEVERE, \"Error during database initialization: {0}\", e.getMessage());\n } finally {\n closeConnection();\n }\n }\n\n public static void showChangeCredentialsDialog() {\n try {\n FXMLLoader loader = new FXMLLoader(UserManager.class.getResource(\"/np/com/satyarajawasthi/smartcreditmanager/fxml/change_credentials_dialog.fxml\"));\n Parent root = loader.load();\n\n Stage dialogStage = new Stage();\n dialogStage.setTitle(\"Change Credentials\");\n dialogStage.initModality(Modality.APPLICATION_MODAL);\n dialogStage.initStyle(StageStyle.UTILITY);\n dialogStage.initOwner(null); // Set to null or the main stage if you have a reference to it.\n\n Scene scene = new Scene(root);\n dialogStage.setScene(scene);\n\n ChangeCredentialsDialogController controller = loader.getController();\n controller.setDialogStage(dialogStage);\n\n // Show the dialog and wait for it to be closed\n dialogStage.showAndWait();\n\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n private static boolean isFirstLoginInPropertiesFile() {\n try (InputStream input = UserRepository.class.getResourceAsStream(CONFIG_URL)) {\n Properties properties = new Properties();\n properties.load(input);\n return Boolean.parseBoolean(properties.getProperty(\"isFirstLogin\"));\n } catch (IOException e) {\n logger.log(Level.SEVERE, \"Error reading from the properties file: {0}\", e.getMessage());\n }\n return true;\n }\n\n public static void finalizeFirstLoginSetup() {\n try (FileOutputStream output = new FileOutputStream(CONFIG_URL)) {\n Properties properties = new Properties();\n properties.setProperty(\"isFirstLogin\", String.valueOf(false));\n properties.store(output, null);\n } catch (IOException e) {\n logger.log(Level.SEVERE, \"Error updating the properties file: {0}\", e.getMessage());\n }\n\n // Call incrementPasswordUpdateCount from UserRepository\n try {\n UserRepository.markPasswordAsUpdated();\n } catch (SQLException e) {\n logger.log(Level.SEVERE, \"Error incrementing password update count: {0}\", e.getMessage());\n }\n }\n\n public static void changeDefaultUser(User updatedUser){\n User user = UserRepository.getUser();\n user.setUsername(updatedUser.getUsername());\n user.setPassphrase(updatedUser.getPassphrase());\n user.setPassword(updatedUser.getPassword());\n UserRepository.updateUser(user);\n }\n public static User getUser(){\n return UserRepository.getUser();\n }\n\n}"
},
{
"identifier": "UserRepository",
"path": "src/main/java/np/com/satyarajawasthi/smartcreditmanager/repository/UserRepository.java",
"snippet": "public class UserRepository {\n private static final Logger logger = Logger.getLogger(UserRepository.class.getName());\n private static final String KEY = \"5a98beed71b7d65e10d914d3456f25b1\";\n private static final String DEFAULT_USERNAME = \"root\";\n private static final String DEFAULT_PASSWORD = \"root\";\n private static final String DEFAULT_PASSPHRASE = \"DEFAULT\";\n\n public static void createUserTable(Connection connection) throws SQLException {\n String createTableQuery = \"\"\"\n CREATE TABLE IF NOT EXISTS users (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n username TEXT NOT NULL,\n password TEXT NOT NULL,\n passphrase TEXT NOT NULL,\n is_password_updated INTEGER NOT NULL DEFAULT 0\n );\n \"\"\";\n try (PreparedStatement statement = connection.prepareStatement(createTableQuery)) {\n statement.executeUpdate();\n }\n logger.info(\"Users table created.\");\n }\n\n public static void insertInitialUserRecords(Connection connection) throws SQLException {\n String insertRecordQuery = \"\"\"\n INSERT INTO users (id, username, password, passphrase, is_password_updated)\n VALUES (0, ?, ?, ?, ?);\n \"\"\";\n try (PreparedStatement statement = connection.prepareStatement(insertRecordQuery)) {\n statement.setString(1, DEFAULT_USERNAME);\n statement.setString(2, EncryptionUtil.encrypt(DEFAULT_PASSWORD, KEY));\n statement.setString(3, EncryptionUtil.encrypt(DEFAULT_PASSPHRASE, KEY));\n statement.setInt(4, 0);\n statement.executeUpdate();\n }\n logger.info(\"Initial user records inserted.\");\n }\n\n public static void restrictUserInsertion(Connection connection) throws SQLException {\n String restrictInsertionQuery = \"\"\"\n CREATE TRIGGER no_insert_users\n BEFORE INSERT ON users\n BEGIN\n SELECT RAISE(FAIL, 'Insertion into users table is not allowed.');\n END;\n \"\"\";\n try (PreparedStatement statement = connection.prepareStatement(restrictInsertionQuery)) {\n statement.executeUpdate();\n }\n logger.info(\"User insertion restricted.\");\n }\n\n public static User getUser() {\n String query = \"SELECT * FROM users LIMIT 1\"; // Limit to 1 record, as there is only one user\n try (Connection connection = getConnection();\n PreparedStatement statement = connection.prepareStatement(query)) {\n ResultSet resultSet = statement.executeQuery();\n return mapUser(resultSet);\n } catch (SQLException e) {\n throw new RuntimeException(e);\n }\n }\n\n public static int getPasswordUpdatedValue() throws SQLException {\n String query = \"SELECT is_password_updated FROM users LIMIT 1\"; // Limit to 1 record\n try (Connection connection = getConnection();\n PreparedStatement statement = connection.prepareStatement(query)) {\n ResultSet resultSet = statement.executeQuery();\n if (resultSet.next()) {\n return resultSet.getInt(\"is_password_updated\");\n }\n }\n return 0;\n }\n\n public static void markPasswordAsUpdated() throws SQLException {\n int currentCount = getPasswordUpdatedValue();\n String query = \"UPDATE users SET is_password_updated = ?\";\n try (Connection connection = getConnection();\n PreparedStatement statement = connection.prepareStatement(query)) {\n statement.setInt(1, ++currentCount);\n statement.executeUpdate();\n }\n }\n\n\n public static boolean isUserTableExists() {\n try (Connection connection = getConnection();\n ResultSet resultSet = connection.getMetaData().getTables(null, null, \"users\", null)) {\n return resultSet.next(); // If the table exists, result set will have at least one row\n } catch (SQLException e) {\n throw new RuntimeException(e);\n }\n }\n\n public static void updateUser(User updatedUser) {\n String updateUserQuery = \"\"\"\n UPDATE users\n SET username = ?,\n password = ?,\n passphrase = ?,\n is_password_updated = ?\n WHERE id = ?\n \"\"\";\n try (Connection connection = getConnection();\n PreparedStatement statement = connection.prepareStatement(updateUserQuery)) {\n int passwordUpdatedValue = getPasswordUpdatedValue();\n statement.setString(1, updatedUser.getUsername());\n statement.setString(2, EncryptionUtil.encrypt(updatedUser.getPassword(), KEY));\n statement.setString(3, EncryptionUtil.encrypt(updatedUser.getPassphrase(), KEY));\n statement.setInt(4, ++passwordUpdatedValue);\n statement.setInt(5, updatedUser.getId());\n statement.executeUpdate();\n } catch (SQLException e) {\n logger.info(\"Issue updating default credits with: \"+updatedUser+ \"With error message: \"+e.getMessage());\n }\n logger.info(\"User updated successfully.\");\n }\n\n private static User mapUser(ResultSet resultSet) throws SQLException {\n String username = resultSet.getString(\"username\");\n String password = EncryptionUtil.decrypt(resultSet.getString(\"password\"), KEY);\n String passphrase = EncryptionUtil.decrypt(resultSet.getString(\"passphrase\"), KEY);\n int passwordUpdated = resultSet.getInt(\"is_password_updated\");\n return new User(username, password, passphrase, passwordUpdated);\n }\n}"
}
] | import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import np.com.satyarajawasthi.smartcreditmanager.manager.UserManager;
import np.com.satyarajawasthi.smartcreditmanager.repository.UserRepository;
import java.io.IOException;
import java.util.Objects; | 2,386 | package np.com.satyarajawasthi.smartcreditmanager.controller;
/**
* Controller for the login view.
* Handles user authentication and password management.
*
* @author Satya Raj Awasthi
* @since 10/24/2023
*/
public class LoginController {
@FXML
private TextField usernameField;
@FXML
private PasswordField passwordField;
@FXML
private Label loginMessage;
@FXML
private Button loginButton;
@FXML
private Button changePasswordButton;
/**
* Initializes the login view.
* Sets the label and button text based on the user's first login status.
*/
public void initialize() { | package np.com.satyarajawasthi.smartcreditmanager.controller;
/**
* Controller for the login view.
* Handles user authentication and password management.
*
* @author Satya Raj Awasthi
* @since 10/24/2023
*/
public class LoginController {
@FXML
private TextField usernameField;
@FXML
private PasswordField passwordField;
@FXML
private Label loginMessage;
@FXML
private Button loginButton;
@FXML
private Button changePasswordButton;
/**
* Initializes the login view.
* Sets the label and button text based on the user's first login status.
*/
public void initialize() { | boolean isFirstTimeUser = UserManager.isFirstLogin(); | 0 | 2023-11-05 03:53:02+00:00 | 4k |
wqj666666/embyboot | src/main/java/com/emby/boot/service/impl/MusicDownloaderImpl.java | [
{
"identifier": "ErrorCodeEnum",
"path": "src/main/java/com/emby/boot/core/common/ErrorCodeEnum.java",
"snippet": "@Getter\n@AllArgsConstructor\npublic enum ErrorCodeEnum {\n\n /**\n * 正确执行后的返回\n */\n OK(\"00000\", \"成功\"),\n\n /**\n * 一级宏观错误码,用户端错误\n */\n USER_ERROR(\"A0001\", \"用户端错误\"),\n\n /**\n * 二级宏观错误码,用户注册错误\n */\n USER_REGISTER_ERROR(\"A0100\", \"用户注册错误\"),\n /**\n * 二级宏观错误码,emby已经注册\n */\n USER_EMBY_REGISTER_ERROR(\"A0104\", \"存在emby账户,无法重复注册\"),\n /**\n * 二级宏观错误码,emby注册失败,可能是用户名已存在\n */\n USER_EMBY_REPEAT_ERROR(\"A0106\", \"emby注册失败,可能是用户名已存在\"),\n /**\n * 二级宏观错误码,音乐服已经注册\n */\n USER_MUSIC_REGISTER_ERROR(\"A0107\", \"存在音乐服账户,无法重复注册\"),\n\n /**\n *\n * 二级宏观错误码,用户注册错误\n */\n USER_REGISTER_EMBY_ERROR(\"A0102\", \"未注册Emby\"),\n /**\n * 二级宏观错误码,用户注册错误\n */\n USER_REGISTER_NAVIDROME_ERROR(\"A0103\", \"未注册Navidrome\"),\n /**\n * 用户未同意隐私协议\n */\n USER_NO_AGREE_PRIVATE_ERROR(\"A0101\", \"用户未同意隐私协议\"),\n\n /**\n * 注册国家或地区受限\n */\n USER_REGISTER_AREA_LIMIT_ERROR(\"A0102\", \"注册国家或地区受限\"),\n\n /**\n * 用户验证码错误\n */\n USER_VERIFY_CODE_ERROR(\"A0240\", \"用户验证码错误\"),\n\n /**\n * 用户名已存在\n */\n USER_NAME_EXIST(\"A0111\", \"用户名已存在\"),\n\n /**\n * 用户账号不存在\n */\n USER_ACCOUNT_NOT_EXIST(\"A0201\", \"用户账号不存在\"),\n\n /**\n * 用户密码错误\n */\n USER_PASSWORD_ERROR(\"A0210\", \"用户密码错误\"),\n /**\n * navidrome用户更新密码错误\n */\n USER_PASSWORD_NAVIDROME_ERROR(\"A0211\", \"navidrome用户更新密码错误\"),\n /**\n * navidrome用户删除错误\n */\n USER_DELETE_NAVIDROME_ERROR(\"A0212\", \"navidrome用户删除错误\"),\n /**\n * 二级宏观错误码,用户请求参数错误\n */\n USER_REQUEST_PARAM_ERROR(\"A0400\", \"用户请求参数错误\"),\n\n /**\n * 用户登录已过期\n */\n USER_LOGIN_EXPIRED(\"A0230\", \"用户登录已过期\"),\n\n /**\n * 访问未授权\n */\n USER_UN_AUTH(\"A0301\", \"访问未授权\"),\n\n /**\n * 用户请求服务异常\n */\n USER_REQ_EXCEPTION(\"A0500\", \"用户请求服务异常\"),\n\n /**\n * 请求超出限制\n */\n USER_REQ_MANY(\"A0501\", \"请求超出限制\"),\n\n /**\n * 用户上传文件异常\n */\n USER_UPLOAD_FILE_ERROR(\"A0700\", \"用户上传文件异常\"),\n\n /**\n * 用户上传文件类型不匹配\n */\n USER_UPLOAD_FILE_TYPE_NOT_MATCH(\"A0701\", \"用户上传文件类型不匹配\"),\n\n /**\n * 一级宏观错误码,系统执行出错\n */\n SYSTEM_ERROR(\"B0001\", \"系统执行出错\"),\n\n /**\n * 二级宏观错误码,系统执行超时\n */\n SYSTEM_TIMEOUT_ERROR(\"B0100\", \"系统执行超时\"),\n /**\n * 音乐已存在,无法重复下载\n */\n MUISC_DOWN_ERROR(\"D0100\", \"音乐已存在,无法重复下载\"),\n /**\n * 音乐下载今天超过5次\n */\n MUISC_DOWN_DATE_ERROR(\"D0101\", \"音乐下载今天超过5次\"),\n\n /**\n * 一级宏观错误码,调用第三方服务出错\n */\n THIRD_SERVICE_ERROR(\"C0001\", \"调用第三方服务出错\"),\n\n /**\n * 一级宏观错误码,中间件服务出错\n */\n MIDDLEWARE_SERVICE_ERROR(\"C0100\", \"中间件服务出错\");\n\n /**\n * 错误码\n */\n private final String code;\n\n /**\n * 中文描述\n */\n private final String message;\n\n}"
},
{
"identifier": "BusinessException",
"path": "src/main/java/com/emby/boot/core/exception/BusinessException.java",
"snippet": "@EqualsAndHashCode(callSuper = true)\n@Data\npublic class BusinessException extends RuntimeException{\n private final ErrorCodeEnum errorCodeEnum;\n\n public BusinessException(ErrorCodeEnum errorCodeEnum) {\n // 不调用父类 Throwable的fillInStackTrace() 方法生成栈追踪信息,提高应用性能\n // 构造器之间的调用必须在第一行\n super(errorCodeEnum.getMessage(), null, false, false);\n this.errorCodeEnum = errorCodeEnum;\n }\n}"
},
{
"identifier": "MusicDownloaderRecord",
"path": "src/main/java/com/emby/boot/dao/entity/MusicDownloaderRecord.java",
"snippet": "@Schema(description = \"muisc下载工具用户下载记录成员变量\")\n@Data\n@TableName(\"muisc_downloader_record\")\npublic class MusicDownloaderRecord {\n @Schema(description = \"记录id\")\n @TableId(value = \"id\", type = IdType.AUTO)\n private Integer id;\n @Schema(description = \"电报用户id\")\n private String chatid;\n @Schema(description = \"音乐标题\")\n private String title;\n @Schema(description = \"音乐作者\")\n private String singer;\n @Schema(description = \"音乐专辑\")\n private String album;\n @Schema(description = \"创建时间\")\n private Long createTime;\n @Schema(description = \"更新时间\")\n private Long updateTime;\n @Schema(description = \"删除时间\")\n private Long deleteTime;\n}"
},
{
"identifier": "MusicDownloaderRecordMapper",
"path": "src/main/java/com/emby/boot/dao/mapper/MusicDownloaderRecordMapper.java",
"snippet": "@Mapper\npublic interface MusicDownloaderRecordMapper extends BaseMapper<MusicDownloaderRecord> {\n}"
},
{
"identifier": "MusicDownReq",
"path": "src/main/java/com/emby/boot/dto/req/MusicDownReq.java",
"snippet": "@Schema(description = \"muisc下载成员变量\")\n@Data\npublic class MusicDownReq {\n\n private String album;\n private String albumMid;\n private String extra;\n private String mid;\n private Integer musicid;\n private String notice;\n private String prefix;\n private String readableText;\n private String singer;\n private String size;\n private String songmid;\n private String time_publish;\n private String title;\n\n}"
},
{
"identifier": "RestResp",
"path": "src/main/java/com/emby/boot/dto/resp/RestResp.java",
"snippet": "@Getter\npublic class RestResp<T> {\n\n /**\n * 响应码\n */\n private String code;\n\n /**\n * 响应消息\n */\n private String message;\n\n /**\n * 响应数据\n */\n private T data;\n\n private RestResp() {\n this.code = ErrorCodeEnum.OK.getCode();\n this.message = ErrorCodeEnum.OK.getMessage();\n }\n\n private RestResp(ErrorCodeEnum errorCode) {\n this.code = errorCode.getCode();\n this.message = errorCode.getMessage();\n }\n\n private RestResp(T data) {\n this();\n this.data = data;\n }\n\n /**\n * 业务处理成功,无数据返回\n */\n public static RestResp<Void> ok() {\n return new RestResp<>();\n }\n\n /**\n * 业务处理成功,有数据返回\n */\n public static <T> RestResp<T> ok(T data) {\n return new RestResp<>(data);\n }\n\n /**\n * 业务处理失败\n */\n public static RestResp<Void> fail(ErrorCodeEnum errorCode) {\n return new RestResp<>(errorCode);\n }\n\n\n /**\n * 系统错误\n */\n public static RestResp<Void> error() {\n return new RestResp<>(ErrorCodeEnum.SYSTEM_ERROR);\n }\n\n /**\n * 判断是否成功\n */\n public boolean isOk() {\n return Objects.equals(this.code, ErrorCodeEnum.OK.getCode());\n }\n\n}"
},
{
"identifier": "MusicDownloaderService",
"path": "src/main/java/com/emby/boot/service/MusicDownloaderService.java",
"snippet": "public interface MusicDownloaderService {\n /**\n * 歌曲搜索\n * @param keywords 搜索关键字\n * @param pageNo 页码\n * @param pageSize 页码大小\n * @return 搜索结果\n */\n JSONObject search(String keywords,Integer pageNo,Integer pageSize);\n /**\n * 歌曲下载\n * @param musicDownReq\n * @return\n */\n RestResp<Void> download(MusicDownReq musicDownReq,String chatid);\n}"
}
] | import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;
import com.emby.boot.core.common.ErrorCodeEnum;
import com.emby.boot.core.exception.BusinessException;
import com.emby.boot.dao.entity.MusicDownloaderRecord;
import com.emby.boot.dao.mapper.MusicDownloaderRecordMapper;
import com.emby.boot.dto.req.MusicDownReq;
import com.emby.boot.dto.resp.RestResp;
import com.emby.boot.service.MusicDownloaderService;
import lombok.RequiredArgsConstructor;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.ZonedDateTime; | 3,003 | package com.emby.boot.service.impl;
/**
* 音乐下载相关的实现类
* @author laojian
* @date 2023/10/9 14:36
*/
@Service
@RequiredArgsConstructor
public class MusicDownloaderImpl implements MusicDownloaderService {
@Value("${spring.musicDownloader.config.url}")
private String url;
@Value("${spring.musicDownloader.config.downloadFolder}")
private String downloadFolder;
private final MusicDownloaderRecordMapper musicDownloaderRecordMapper;
/**
* 歌曲搜索接口
* @param keywords 搜索关键字
* @param pageNo 页码
* @param pageSize 页码大小
* @return
*/
@Override
public JSONObject search(String keywords,Integer pageNo,Integer pageSize) {
String encode=null;
try {
encode = URLEncoder.encode(keywords, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
try {
HttpResponse<String> response = Unirest.get(url+"/qq/search/"+encode+"/"+pageNo+"/"+pageSize)
.header("User-Agent", "Apifox/1.0.0 (https://apifox.com)")
.asString();
String body = response.getBody();
JSONObject jsonObject = JSONObject.parseObject(body);
return jsonObject;
} catch (UnirestException e) {
throw new RuntimeException(e);
}
}
/**
* 歌曲下载实现方法
* @param musicDownReq
* @return
*/
@Override
public RestResp<Void> download(MusicDownReq musicDownReq,String chatid) {
//判断是否已经下载过或者已经存在
QueryWrapper<MusicDownloaderRecord> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("title",musicDownReq.getTitle());
queryWrapper.eq("singer",musicDownReq.getSinger());
queryWrapper.eq("album",musicDownReq.getAlbum());
queryWrapper.isNull("delete_time");
Long count = musicDownloaderRecordMapper.selectCount(queryWrapper);
if (count>0){ | package com.emby.boot.service.impl;
/**
* 音乐下载相关的实现类
* @author laojian
* @date 2023/10/9 14:36
*/
@Service
@RequiredArgsConstructor
public class MusicDownloaderImpl implements MusicDownloaderService {
@Value("${spring.musicDownloader.config.url}")
private String url;
@Value("${spring.musicDownloader.config.downloadFolder}")
private String downloadFolder;
private final MusicDownloaderRecordMapper musicDownloaderRecordMapper;
/**
* 歌曲搜索接口
* @param keywords 搜索关键字
* @param pageNo 页码
* @param pageSize 页码大小
* @return
*/
@Override
public JSONObject search(String keywords,Integer pageNo,Integer pageSize) {
String encode=null;
try {
encode = URLEncoder.encode(keywords, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
try {
HttpResponse<String> response = Unirest.get(url+"/qq/search/"+encode+"/"+pageNo+"/"+pageSize)
.header("User-Agent", "Apifox/1.0.0 (https://apifox.com)")
.asString();
String body = response.getBody();
JSONObject jsonObject = JSONObject.parseObject(body);
return jsonObject;
} catch (UnirestException e) {
throw new RuntimeException(e);
}
}
/**
* 歌曲下载实现方法
* @param musicDownReq
* @return
*/
@Override
public RestResp<Void> download(MusicDownReq musicDownReq,String chatid) {
//判断是否已经下载过或者已经存在
QueryWrapper<MusicDownloaderRecord> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("title",musicDownReq.getTitle());
queryWrapper.eq("singer",musicDownReq.getSinger());
queryWrapper.eq("album",musicDownReq.getAlbum());
queryWrapper.isNull("delete_time");
Long count = musicDownloaderRecordMapper.selectCount(queryWrapper);
if (count>0){ | throw new BusinessException(ErrorCodeEnum.MUISC_DOWN_ERROR); | 0 | 2023-11-09 17:15:57+00:00 | 4k |
AnhyDev/AnhyLingo | src/main/java/ink/anh/lingo/listeners/protocol/PacketListenerManager.java | [
{
"identifier": "AnhyLingo",
"path": "src/main/java/ink/anh/lingo/AnhyLingo.java",
"snippet": "public class AnhyLingo extends JavaPlugin {\n\n private static AnhyLingo instance;\n \n private boolean isSpigot;\n private boolean isPaper;\n private boolean isFolia;\n private boolean hasPaperComponent;\n \n private GlobalManager globalManager;\n\n /**\n * Called when the plugin is loaded by the Bukkit system.\n * Sets the static instance for global access.\n */\n @Override\n public void onLoad() {\n instance = this;\n }\n\n /**\n * Called when the plugin is enabled.\n * Performs initial setup such as checking dependencies, determining server type,\n * initializing managers, and setting up commands and listeners.\n */\n @Override\n public void onEnable() {\n checkDepends(\"ProtocolLib\");\n checkServer();\n \n globalManager = GlobalManager.getManager(this);\n new PacketListenerManager().addListeners();\n new ListenerManager(this);\n this.getCommand(\"lingo\").setExecutor(new LingoCommand(this));\n }\n\n /**\n * Called when the plugin is disabled.\n * Currently, this method does not perform any specific actions.\n */\n @Override\n public void onDisable() {\n // Plugin shutdown logic\n }\n \n /**\n * Checks if the current server version is equal to or newer than a specified version.\n * \n * @param minorVersionToCheck The minor version to compare against.\n * @return true if the current server version is equal or newer than the specified version.\n */\n public static boolean isVersionOrNewer(int minorVersionToCheck) {\n String version = Bukkit.getBukkitVersion();\n String[] splitVersion = version.split(\"-\")[0].split(\"\\\\.\");\n\n int major = Integer.parseInt(splitVersion[0]);\n int minor = 0;\n\n if (splitVersion.length > 1) {\n minor = Integer.parseInt(splitVersion[1]);\n }\n\n return major == 1 && minor >= minorVersionToCheck;\n }\n\n /**\n * Checks the server for specific implementations like Spigot, Paper, or Folia.\n * Updates the respective boolean fields based on the server type.\n */\n private void checkServer() {\n try {\n Class.forName(\"org.bukkit.entity.Player$Spigot\");\n isSpigot = true;\n } catch (Throwable tr) {\n isSpigot = false;\n Logger.error(this, \"Console-Sender.Messages.Initialize.Require-Spigot\");\n return;\n }\n try {\n Class.forName(\"com.destroystokyo.paper.VersionHistoryManager$VersionData\");\n isPaper = true;\n try {\n Class.forName(\"io.papermc.paper.text.PaperComponents\");\n hasPaperComponent = true;\n } catch (Throwable tr) {\n hasPaperComponent = false;\n }\n } catch (Throwable tr) {\n isPaper = false;\n }\n try {\n Class.forName(\"io.papermc.paper.threadedregions.RegionizedServer\");\n isFolia = true;\n } catch (ClassNotFoundException e) {\n isFolia = false;\n }\n }\n\n /**\n * Checks for the presence of specified dependencies.\n * If any dependency is missing, the plugin is disabled.\n * \n * @param depends An array of plugin names to check for.\n * @return true if any dependency is missing.\n */\n private boolean checkDepends(String... depends) {\n boolean missingDepend = false;\n PluginManager pluginManager = Bukkit.getPluginManager();\n for (String depend : depends) {\n if (pluginManager.getPlugin(depend) == null) {\n Logger.error(this, \"Console-Sender.Messages.Initialize.Missing-Dependency \" + depend);\n missingDepend = true;\n }\n }\n if (missingDepend) {\n pluginManager.disablePlugin(instance);\n }\n return missingDepend;\n }\n\n /**\n * Gets the singleton instance of this plugin.\n * \n * @return The singleton instance of AnhyLingo.\n */\n public static AnhyLingo getInstance() {\n return instance;\n }\n\n /**\n * Gets the GlobalManager instance associated with this plugin.\n * \n * @return The GlobalManager instance.\n */\n public GlobalManager getGlobalManager() {\n return globalManager;\n }\n\n /**\n * Checks if the server is running Spigot.\n * \n * @return true if the server is Spigot.\n */\n public boolean isSpigot() {\n return isSpigot;\n }\n\n /**\n * Checks if the server is running Paper.\n * \n * @return true if the server is Paper.\n */\n public boolean isPaper() {\n return isPaper;\n }\n\n /**\n * Checks if the server is running Folia.\n * \n * @return true if the server is Folia.\n */\n public boolean isFolia() {\n return isFolia;\n }\n\n /**\n * Checks if the server has the PaperComponents feature.\n * \n * @return true if the server has PaperComponents.\n */\n public boolean hasPaperComponent() {\n return hasPaperComponent;\n }\n}"
},
{
"identifier": "PacketSystemChat",
"path": "src/main/java/ink/anh/lingo/listeners/protocol/server/PacketSystemChat.java",
"snippet": "public class PacketSystemChat extends AbstractPacketListener {\n /**\n * Constructor for PacketSystemChat.\n * Sets up the listener for Server.SYSTEM_CHAT packet type with normal priority.\n */\n public PacketSystemChat() {\n super(getPacketType());\n\n ProtocolManager protocolManager = ProtocolLibrary.getProtocolManager();\n \n\n protocolManager.addPacketListener(this.packetAdapter = new PacketAdapter(lingoPlugin, ListenerPriority.NORMAL, packetType) {\n \n \t@Override\n \tpublic void onPacketSending(PacketEvent event) {\n \t\t\n \t\tif (!lingoPlugin.getGlobalManager().isPacketLingo()) {\n \t\t\treturn;\n \t\t}\n \t \n handlePacket(event);\n \t}\n });\n }\n\t\n\tprivate static PacketType getPacketType() {\n\t\tdouble ver = getCurrentServerVersion();\n\n\t\tif (AnhyLingo.getInstance().getGlobalManager().isDebug()) {\n\t\t\tLogger.info(AnhyLingo.getInstance(), \"CurrentServerVersion: \" + ver);\n\t\t}\n\t\t\n if (ver < 1.19) {\n \treturn PacketType.Play.Server.CHAT;\n }\n \treturn PacketType.Play.Server.SYSTEM_CHAT;\n \n\t}\n\n /**\n * Handles the modification of system chat packets.\n * This method is called when a system chat packet is being sent to a player, allowing modification of its content.\n *\n * @param event The PacketEvent to be handled.\n */\n @Override\n protected void handlePacket(PacketEvent event) {\n double currentVersion = getCurrentServerVersion();\n if (currentVersion < 1.19) {\n if(!handleWrappedChatComponent(event)) {\n \thandleChatPacketForOldVersions(event);\n }\n } else {\n \thandleStructureModifier(event);\n }\n }\n\n private void handleChatPacketForOldVersions(PacketEvent event) {\n ModificationState modState = new ModificationState();\n String[] langs = getPlayerLanguage(event.getPlayer());\n\n PacketContainer packet = event.getPacket();\n StructureModifier<Component> components = packet.getModifier().withType(Component.class);\n\n if (components.size() > 0 && components.read(0) != null) {\n Component component = components.read(0);\n String jsonSystemChat = PaperUtils.serializeComponent(component);\n String modifiedJson = modifyChat(jsonSystemChat, langs, modState, \"text\");\n\n if (modState.isModified() && modifiedJson != null) {\n Component modifiedComponent = PaperUtils.getPaperGsonComponentSerializer().deserialize(modifiedJson);\n components.write(0, modifiedComponent);\n }\n }\n }\n\n private boolean handleWrappedChatComponent(PacketEvent event) {\n ModificationState modState = new ModificationState();\n String[] langs = getPlayerLanguage(event.getPlayer());\n\n PacketContainer packet = event.getPacket();\n\n try {\n StructureModifier<WrappedChatComponent> chatComponents = packet.getChatComponents();\n if (chatComponents.size() > 0 && chatComponents.read(0) != null) {\n WrappedChatComponent wrappedChat = chatComponents.read(0);\n String jsonChat = wrappedChat.getJson();\n String modifiedJson = modifyChat(jsonChat, langs, modState, \"text\");\n\n if (modState.isModified() && modifiedJson != null) {\n WrappedChatComponent modifiedComponent = WrappedChatComponent.fromJson(modifiedJson);\n chatComponents.write(0, modifiedComponent);\n return true;\n }\n }\n } catch (Exception e) {\n // Якщо виникла помилка, повертаємо false\n return false;\n }\n\n return false;\n }\n\n private void handleStructureModifier(PacketEvent event) {\n ModificationState modState = new ModificationState();\n String[] langs = getPlayerLanguage(event.getPlayer());\n\n PacketContainer packet = event.getPacket();\n Optional<Boolean> isFiltered = packet.getMeta(\"psr_filtered_packet\");\n if (!(isFiltered.isPresent() && isFiltered.get())) {\n StructureModifier<Boolean> booleans = packet.getBooleans();\n if (booleans.size() == 1 && booleans.read(0)) {\n reSetActionBar(event, langs, modState);\n return;\n }\n\n StructureModifier<String> stringModifier = packet.getStrings();\n StructureModifier<Component> componentModifier = packet.getModifier().withType(Component.class);\n String contentField = stringModifier.read(0);\n\n String jsonSystemChat;\n String modifiedJson;\n boolean isPaper = false;\n\n if (contentField != null) {\n jsonSystemChat = contentField.toString();\n } else {\n Component read = componentModifier.read(0);\n if (read == null) {\n return;\n }\n jsonSystemChat = PaperUtils.serializeComponent(read);\n isPaper = true;\n }\n\n modifiedJson = modifyChat(jsonSystemChat, langs, modState, \"text\");\n\n if (modState.isModified() && modifiedJson != null) {\n if (isPaper) {\n Component modifiedComponent = PaperUtils.getPaperGsonComponentSerializer().deserialize(modifiedJson);\n componentModifier.write(0, modifiedComponent);\n } else {\n stringModifier.write(0, modifiedJson);\n }\n }\n }\n }\n\n\n /**\n * Gets the LanguageManager instance from the plugin.\n *\n * @return The LanguageManager instance.\n */\n\t@Override\n\tpublic LanguageManager getLangMan() {\n\t\treturn lingoPlugin.getGlobalManager().getLanguageManager();\n\t}\n\t\n\tpublic static double getCurrentServerVersion() {\n\t String versionString = Bukkit.getBukkitVersion().split(\"-\")[0];\n\t String[] splitVersion = versionString.split(\"\\\\.\");\n\n\t try {\n\t int major = Integer.parseInt(splitVersion[0]);\n\t int minor = splitVersion.length > 1 ? Integer.parseInt(splitVersion[1]) : 0;\n\t double version = major + minor / (minor >= 10 ? 100.0 : 10.0);\n\t return version;\n\t } catch (NumberFormatException e) {\n\t e.printStackTrace();\n\t return 0;\n\t }\n\t}\n}"
}
] | import com.comphenix.protocol.ProtocolLibrary;
import com.comphenix.protocol.events.ListenerPriority;
import ink.anh.api.messages.Logger;
import ink.anh.lingo.AnhyLingo;
import ink.anh.lingo.listeners.protocol.server.PacketSystemChat;
import java.util.ArrayList;
import java.util.List; | 3,167 | package ink.anh.lingo.listeners.protocol;
/**
* Manages the registration and removal of packet listeners in the AnhyLingo plugin.
* This class handles the initialization of packet listeners with their respective priority
* and the addition or removal of these listeners from the ProtocolLibrary.
*/
public class PacketListenerManager {
private ListenerPriority listenerPriority;
/**
* Gets the current listener priority for packet listeners.
*
* @return The listener priority.
*/
public ListenerPriority getListenerPriority() {
return listenerPriority;
}
/**
* Initializes the PacketListenerManager, determining the listener priority and adding listeners.
*/
public void initialize() {
listenerPriority = determineListenerPriority();
addListeners();
}
/**
* Determines the listener priority for packet listeners.
* Custom logic can be implemented here to dynamically set the priority.
*
* @return The determined ListenerPriority.
*/
private ListenerPriority determineListenerPriority() {
// Тут можна додати логіку визначення пріоритету слухача.
// Наразі за замовчуванням встановлюється HIGHEST.
return ListenerPriority.HIGHEST;
}
/**
* Adds all defined packet listeners to the ProtocolLibrary.
* Registers each listener with the determined priority.
*/
public void addListeners() {
List<AbstractPacketListener> listeners = new ArrayList<>();
//listeners.add(new PacketChat()); | package ink.anh.lingo.listeners.protocol;
/**
* Manages the registration and removal of packet listeners in the AnhyLingo plugin.
* This class handles the initialization of packet listeners with their respective priority
* and the addition or removal of these listeners from the ProtocolLibrary.
*/
public class PacketListenerManager {
private ListenerPriority listenerPriority;
/**
* Gets the current listener priority for packet listeners.
*
* @return The listener priority.
*/
public ListenerPriority getListenerPriority() {
return listenerPriority;
}
/**
* Initializes the PacketListenerManager, determining the listener priority and adding listeners.
*/
public void initialize() {
listenerPriority = determineListenerPriority();
addListeners();
}
/**
* Determines the listener priority for packet listeners.
* Custom logic can be implemented here to dynamically set the priority.
*
* @return The determined ListenerPriority.
*/
private ListenerPriority determineListenerPriority() {
// Тут можна додати логіку визначення пріоритету слухача.
// Наразі за замовчуванням встановлюється HIGHEST.
return ListenerPriority.HIGHEST;
}
/**
* Adds all defined packet listeners to the ProtocolLibrary.
* Registers each listener with the determined priority.
*/
public void addListeners() {
List<AbstractPacketListener> listeners = new ArrayList<>();
//listeners.add(new PacketChat()); | listeners.add(new PacketSystemChat()); | 1 | 2023-11-10 00:35:39+00:00 | 4k |
Oselan/ExcelUtils | src/main/java/com/oselan/excelexporter/ExcelExporter.java | [
{
"identifier": "ConflictException",
"path": "src/main/java/com/oselan/commons/exceptions/ConflictException.java",
"snippet": "public class ConflictException extends BaseException {\n\tprivate static final long serialVersionUID = -8596472890741536409L;\n \n private static final String DEFAULT_ERROR_CODE = \"UNEXPECTED_CONFLICT\";\n\t\n\tpublic ConflictException() {\n super(\"Unexpected data situation occurred.\", DEFAULT_ERROR_CODE);\n\n\t}\n\n\tpublic ConflictException(String message, Throwable cause) {\n super(message, DEFAULT_ERROR_CODE, cause);\n\t}\n\n\tpublic ConflictException(String message) {\n super(message, DEFAULT_ERROR_CODE);\n\t}\n\n public ConflictException(String message, String errorCode, Throwable cause) {\n super(message, errorCode, cause);\n\t}\n\n public ConflictException(String message, String errorCode) {\n super(message, errorCode);\n\t}\n}"
},
{
"identifier": "NotFoundException",
"path": "src/main/java/com/oselan/commons/exceptions/NotFoundException.java",
"snippet": "public class NotFoundException extends BaseException {\n\tprivate static final long serialVersionUID = -8596472890741536409L;\n \n\tprivate static final String DEFAULT_ERROR_CODE = \"NOT_FOUND\";\n\t\n\t\n\tpublic NotFoundException() {\n super(\"Expected item not found\", DEFAULT_ERROR_CODE);\n\t\t\n\t}\n\n\tpublic NotFoundException(String message, Throwable cause) {\n super(message, DEFAULT_ERROR_CODE, cause);\n\t}\n\n\tpublic NotFoundException(String message) {\n super(message, DEFAULT_ERROR_CODE);\n\t}\n\n public NotFoundException(String message, String errorCode, Throwable cause) {\n super(message, errorCode, cause);\n\t}\n\n public NotFoundException(String message, String errorCode) {\n super(message, errorCode);\n\t}\n\n \n\t public NotFoundException(Long id ) {\n\t\tsuper( \"Item not found : \" + id,DEFAULT_ERROR_CODE);\n\t}\n\n\t \n\t \n}"
}
] | import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Slice;
import org.springframework.util.StringUtils;
import com.oselan.commons.exceptions.ConflictException;
import com.oselan.commons.exceptions.NotFoundException;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j; | 2,475 | package com.oselan.excelexporter;
/***
* A performance oriented non-blocking excel exporter, records are added to a
* queue and exporting reads from the queue to build the workbook report.
* Finally the workbook is written to a stream.
*
* @author Ahmad Hamid
*
* @param <T>
*/
@Slf4j
public class ExcelExporter<T> implements AutoCloseable {
private Workbook workbook = null;
/***
* Sheet to write to
*/
private Sheet activeSheet;
private OutputStream stream;
private ConcurrentLinkedQueue<T> dataRecordsQueue = new ConcurrentLinkedQueue<T>();
private List<ColumnDefinition> columns;
/***
* Report name
*/
private String sheetName = "Report";
// used by POI excel to keep window of records in memory
private static final int DEFAULT_BATCH_SIZE = 100;
// used when calling the data provider to fetch data
private static final int DEFAULT_DATA_FETCH_SIZE = 2000;
// Excel has a limit of 1,048,576 rows
private static final int DEFAULT_MAX_ROWS_PER_SHEET = 1048575;
// Max size of queue so not to consume too much memory
private static final int DEFAULT_MAX_QUEUE_SIZE = 10000;
// wait 5mins for data before timeout.
private static final long DEFAULT_DATA_WAIT_TIMEOUT = 5 * 60 * 1000;
private int maxRowsPerSheet = DEFAULT_MAX_ROWS_PER_SHEET;
private long dataWaitTimeout = DEFAULT_DATA_WAIT_TIMEOUT;
private int maxQueueSize = DEFAULT_MAX_QUEUE_SIZE;
private int dataFetchSize = DEFAULT_DATA_FETCH_SIZE;
/***
*
* @return The number of rows per sheet
*/
public int getMaxRowsPerSheet() {
return maxRowsPerSheet;
}
/***
* Excel has a max rows per sheet of 1,048,576 (Default) This allows controlling
* number of rows per sheet. New sheets are created on the fly.
*
* @param maxRowsPerSheet
*/
public void setMaxRowsPerSheet(int maxRowsPerSheet) {
this.maxRowsPerSheet = maxRowsPerSheet;
}
/***
* @return The time to wait for slow queries in millseconds
*/
public long getDataWaitTimeout() {
return dataWaitTimeout;
}
/**
* The time to wait for slow queries in millseconds Default is 5 x 60 x 1000 = 5
* mins
*
* @param dataWaitTimeout
*/
public void setDataWaitTimeout(long dataWaitTimeout) {
this.dataWaitTimeout = dataWaitTimeout;
}
/***
* @return The number of records to keep in queue before fetching new data
*/
public int getMaxQueueSize() {
return maxQueueSize;
}
/***
* Control the number of records to keep in queue before fetching new data
* Default is 10000
*
* @param maxQueueSize
*/
public void setMaxQueueSize(int maxQueueSize) {
this.maxQueueSize = maxQueueSize;
}
/***
*
* @return Page size of date fetched from db.
*/
public int getDataFetchSize() {
return dataFetchSize;
}
/***
* The size of the page to fetch from the database. Default is 2000
* Larger pages will take more time and memory
* @param dataFetchSize
*/
public void setDataFetchSize(int dataFetchSize) {
this.dataFetchSize = dataFetchSize;
}
/***
* Flag to indicate the no more records are read from the data provider.
*/
private AtomicBoolean isEndOfData = new AtomicBoolean();
/***
* Flag to indicate exporting to the stream completed
*/
private AtomicBoolean isWritingCompleted = new AtomicBoolean();
/***
*
* @param stream output stream to write to
* @param headers optional ordered list of headers to add to the sheet.
* @param ordered list of column definitions
*/
public ExcelExporter(OutputStream stream, List<ColumnDefinition> columns) {
this.stream = stream;
this.columns = columns;
this.columns.sort(new Comparator<ColumnDefinition>() {
@Override
public int compare(ColumnDefinition o1, ColumnDefinition o2) {
return o1.getIndex().compareTo(o2.getIndex());
}
});
}
/***
*
* @param stream
* @param columns
* @param sheetName
*/
public ExcelExporter(OutputStream stream, List<ColumnDefinition> columns, String sheetName) {
this(stream, columns);
this.sheetName = sheetName;
}
/***
* Adds a list of data records to the queue to be exported to the excel sheet.
*
* @param dataRecords
* @throws IOException
*/
public void addRecords(List<T> dataRecords) throws IOException {
addRecords(dataRecords, false);
}
/**
* Adds a list of data records to the queue and signals that there are more data
*
* @param dataRecords
* @param isEndOfData true if no more records available false otherwise.
* @throws IOException
*/
@SneakyThrows(InterruptedException.class)
public void addRecords(List<T> dataRecords, boolean isEndOfData) throws IOException {
if (!isOpen())
throw new IOException("Exporter not open - call open() before attempting to send data ");
if (this.isEndOfData.get() || this.isWritingCompleted.get())
throw new IOException("Attempting to add data after exporter was closed");
// mem-safte wait until queue size goes belo max-queue-size
while (dataRecordsQueue.size() + dataRecords.size() > maxQueueSize) {
log.info("Waiting for queue to be written to excel.");
TimeUnit.MILLISECONDS.sleep(100);
}
log.info("Adding data records, size {}", dataRecordsQueue.size());
dataRecordsQueue.addAll(dataRecords);
if (isEndOfData)
closeData();
}
/**
* Indicate that no more data are available
*/
public void closeData() {
this.isEndOfData.compareAndSet(false, true);
}
/***
* Create a cell
*
* @param row
* @param columnCount
* @param value
* @param style
*/
private void createCell(Row row, int columnCount, Object value, CellStyle style) {
Cell cell = row.createCell(columnCount);
if (value instanceof Integer) {
cell.setCellValue((Integer) value);
} else if (value instanceof Boolean) {
cell.setCellValue((Boolean) value);
} else if (value instanceof Double) {
cell.setCellValue((Double) value);
} else {
cell.setCellValue((String) value);
}
cell.setCellStyle(style);
}
/***
* Create a cell in a specific row , column with a value
*
* @param row
* @param columnCount
* @param value
*/
private void createCell(Row row, int columnCount, Object value) {
Cell cell = row.createCell(columnCount);
if (value instanceof Integer) {
cell.setCellValue((Integer) value);
} else if (value instanceof Boolean) {
cell.setCellValue((Boolean) value);
} else if (value instanceof Double) {
cell.setCellValue((Double) value);
} else if (value instanceof Long) {
cell.setCellValue((Long) value);
} else if (value instanceof String) {
cell.setCellValue((String) value);
} else if (value != null) {
cell.setCellValue(value.toString());
}
}
/***
* Creates a header if headers list is found and has values
*
* @param sheet
*/
private void writeHeaderLine(Sheet sheet) {
Row row = sheet.createRow(0);
int c = 0;
for (ColumnDefinition colDef : columns) {
createCell(row, c++, colDef.getHeader());
}
}
/***
* Blocks until excel data is available or timeout Starts writing to the excel
* sheet When done writes the workbook to the output stream and signals
* completion.
*
* @throws IOException
* @throws ConflictException
* @throws InterruptedException
* @throws NotFoundException
*/
@SneakyThrows(InterruptedException.class) | package com.oselan.excelexporter;
/***
* A performance oriented non-blocking excel exporter, records are added to a
* queue and exporting reads from the queue to build the workbook report.
* Finally the workbook is written to a stream.
*
* @author Ahmad Hamid
*
* @param <T>
*/
@Slf4j
public class ExcelExporter<T> implements AutoCloseable {
private Workbook workbook = null;
/***
* Sheet to write to
*/
private Sheet activeSheet;
private OutputStream stream;
private ConcurrentLinkedQueue<T> dataRecordsQueue = new ConcurrentLinkedQueue<T>();
private List<ColumnDefinition> columns;
/***
* Report name
*/
private String sheetName = "Report";
// used by POI excel to keep window of records in memory
private static final int DEFAULT_BATCH_SIZE = 100;
// used when calling the data provider to fetch data
private static final int DEFAULT_DATA_FETCH_SIZE = 2000;
// Excel has a limit of 1,048,576 rows
private static final int DEFAULT_MAX_ROWS_PER_SHEET = 1048575;
// Max size of queue so not to consume too much memory
private static final int DEFAULT_MAX_QUEUE_SIZE = 10000;
// wait 5mins for data before timeout.
private static final long DEFAULT_DATA_WAIT_TIMEOUT = 5 * 60 * 1000;
private int maxRowsPerSheet = DEFAULT_MAX_ROWS_PER_SHEET;
private long dataWaitTimeout = DEFAULT_DATA_WAIT_TIMEOUT;
private int maxQueueSize = DEFAULT_MAX_QUEUE_SIZE;
private int dataFetchSize = DEFAULT_DATA_FETCH_SIZE;
/***
*
* @return The number of rows per sheet
*/
public int getMaxRowsPerSheet() {
return maxRowsPerSheet;
}
/***
* Excel has a max rows per sheet of 1,048,576 (Default) This allows controlling
* number of rows per sheet. New sheets are created on the fly.
*
* @param maxRowsPerSheet
*/
public void setMaxRowsPerSheet(int maxRowsPerSheet) {
this.maxRowsPerSheet = maxRowsPerSheet;
}
/***
* @return The time to wait for slow queries in millseconds
*/
public long getDataWaitTimeout() {
return dataWaitTimeout;
}
/**
* The time to wait for slow queries in millseconds Default is 5 x 60 x 1000 = 5
* mins
*
* @param dataWaitTimeout
*/
public void setDataWaitTimeout(long dataWaitTimeout) {
this.dataWaitTimeout = dataWaitTimeout;
}
/***
* @return The number of records to keep in queue before fetching new data
*/
public int getMaxQueueSize() {
return maxQueueSize;
}
/***
* Control the number of records to keep in queue before fetching new data
* Default is 10000
*
* @param maxQueueSize
*/
public void setMaxQueueSize(int maxQueueSize) {
this.maxQueueSize = maxQueueSize;
}
/***
*
* @return Page size of date fetched from db.
*/
public int getDataFetchSize() {
return dataFetchSize;
}
/***
* The size of the page to fetch from the database. Default is 2000
* Larger pages will take more time and memory
* @param dataFetchSize
*/
public void setDataFetchSize(int dataFetchSize) {
this.dataFetchSize = dataFetchSize;
}
/***
* Flag to indicate the no more records are read from the data provider.
*/
private AtomicBoolean isEndOfData = new AtomicBoolean();
/***
* Flag to indicate exporting to the stream completed
*/
private AtomicBoolean isWritingCompleted = new AtomicBoolean();
/***
*
* @param stream output stream to write to
* @param headers optional ordered list of headers to add to the sheet.
* @param ordered list of column definitions
*/
public ExcelExporter(OutputStream stream, List<ColumnDefinition> columns) {
this.stream = stream;
this.columns = columns;
this.columns.sort(new Comparator<ColumnDefinition>() {
@Override
public int compare(ColumnDefinition o1, ColumnDefinition o2) {
return o1.getIndex().compareTo(o2.getIndex());
}
});
}
/***
*
* @param stream
* @param columns
* @param sheetName
*/
public ExcelExporter(OutputStream stream, List<ColumnDefinition> columns, String sheetName) {
this(stream, columns);
this.sheetName = sheetName;
}
/***
* Adds a list of data records to the queue to be exported to the excel sheet.
*
* @param dataRecords
* @throws IOException
*/
public void addRecords(List<T> dataRecords) throws IOException {
addRecords(dataRecords, false);
}
/**
* Adds a list of data records to the queue and signals that there are more data
*
* @param dataRecords
* @param isEndOfData true if no more records available false otherwise.
* @throws IOException
*/
@SneakyThrows(InterruptedException.class)
public void addRecords(List<T> dataRecords, boolean isEndOfData) throws IOException {
if (!isOpen())
throw new IOException("Exporter not open - call open() before attempting to send data ");
if (this.isEndOfData.get() || this.isWritingCompleted.get())
throw new IOException("Attempting to add data after exporter was closed");
// mem-safte wait until queue size goes belo max-queue-size
while (dataRecordsQueue.size() + dataRecords.size() > maxQueueSize) {
log.info("Waiting for queue to be written to excel.");
TimeUnit.MILLISECONDS.sleep(100);
}
log.info("Adding data records, size {}", dataRecordsQueue.size());
dataRecordsQueue.addAll(dataRecords);
if (isEndOfData)
closeData();
}
/**
* Indicate that no more data are available
*/
public void closeData() {
this.isEndOfData.compareAndSet(false, true);
}
/***
* Create a cell
*
* @param row
* @param columnCount
* @param value
* @param style
*/
private void createCell(Row row, int columnCount, Object value, CellStyle style) {
Cell cell = row.createCell(columnCount);
if (value instanceof Integer) {
cell.setCellValue((Integer) value);
} else if (value instanceof Boolean) {
cell.setCellValue((Boolean) value);
} else if (value instanceof Double) {
cell.setCellValue((Double) value);
} else {
cell.setCellValue((String) value);
}
cell.setCellStyle(style);
}
/***
* Create a cell in a specific row , column with a value
*
* @param row
* @param columnCount
* @param value
*/
private void createCell(Row row, int columnCount, Object value) {
Cell cell = row.createCell(columnCount);
if (value instanceof Integer) {
cell.setCellValue((Integer) value);
} else if (value instanceof Boolean) {
cell.setCellValue((Boolean) value);
} else if (value instanceof Double) {
cell.setCellValue((Double) value);
} else if (value instanceof Long) {
cell.setCellValue((Long) value);
} else if (value instanceof String) {
cell.setCellValue((String) value);
} else if (value != null) {
cell.setCellValue(value.toString());
}
}
/***
* Creates a header if headers list is found and has values
*
* @param sheet
*/
private void writeHeaderLine(Sheet sheet) {
Row row = sheet.createRow(0);
int c = 0;
for (ColumnDefinition colDef : columns) {
createCell(row, c++, colDef.getHeader());
}
}
/***
* Blocks until excel data is available or timeout Starts writing to the excel
* sheet When done writes the workbook to the output stream and signals
* completion.
*
* @throws IOException
* @throws ConflictException
* @throws InterruptedException
* @throws NotFoundException
*/
@SneakyThrows(InterruptedException.class) | public void export() throws ConflictException { | 0 | 2023-11-03 20:17:51+00:00 | 4k |
BaderTim/minecraft-measurement-mod | src/main/java/io/github/mmm/measurement/survey/SurveyController.java | [
{
"identifier": "MMM",
"path": "src/main/java/io/github/mmm/MMM.java",
"snippet": "@Mod(MMM.MODID)\npublic class MMM {\n // Define mod id in a common place for everything to reference\n public static final String MODID = \"mmm\";\n // Directly reference a slf4j logger\n public static final Logger LOGGER = LogUtils.getLogger();\n // Set file path\n public static final String MMM_ROOT_PATH = Minecraft.getInstance().gameDirectory.getPath() + \"/mmm_data/\";\n\n // Create Device Controller object\n public static final DeviceController DEVICE_CONTROLLER = new DeviceController();\n // Create Survey Controller object\n public static final SurveyController SURVEY_CONTROLLER = new SurveyController();\n\n // Always start with the device config gui\n public static ConfigGUIType latestConfigGUI = ConfigGUIType.DEVICE;\n public static enum ConfigGUIType {\n SURVEY,\n DEVICE\n };\n\n public MMM() {\n // Register Config\n ModLoadingContext.get().registerConfig(ModConfig.Type.CLIENT, Config.SPEC, \"mmm-client-config.toml\");\n\n // Register ourselves for server and other game events we are interested in\n MinecraftForge.EVENT_BUS.register(this);\n\n // Create directory for data\n try {\n System.out.println(\"Creating directory: \" + MMM_ROOT_PATH);\n Files.createDirectories(Paths.get(MMM_ROOT_PATH));\n } catch (Exception e) {\n System.out.println(\"Error creating directory: \" + e.getMessage());\n }\n }\n\n @SubscribeEvent\n public void entityJoinLevelEvent(EntityJoinLevelEvent event) {\n // Initialize devices\n DEVICE_CONTROLLER.initDevices();\n }\n\n}"
},
{
"identifier": "Survey",
"path": "src/main/java/io/github/mmm/measurement/survey/objects/Survey.java",
"snippet": "public class Survey {\n\n private ArrayList<Edge> edges;\n private ArrayList<Vertex> vertices;\n\n private int positionVertexIndex;\n\n public Survey() {\n edges = new ArrayList<>();\n vertices = new ArrayList<>();\n positionVertexIndex = 0;\n }\n\n public void addEdge(Edge edge) {\n edges.add(edge);\n }\n\n public void addVertex(Vertex vertex) {\n vertices.add(vertex);\n }\n\n public ArrayList<Edge> getEdges() {\n return edges;\n }\n\n public Edge getEdge(int index) {\n return edges.get(index);\n }\n\n public ArrayList<Vertex> getVertices() {\n return vertices;\n }\n\n public Vertex getVertex(int index) {\n return vertices.get(index);\n }\n\n public int getPositionVertexIndex() {\n return positionVertexIndex;\n }\n\n public void setPositionVertexIndex(int index) {\n positionVertexIndex = index;\n }\n\n}"
},
{
"identifier": "Edge",
"path": "src/main/java/io/github/mmm/measurement/survey/objects/graph/Edge.java",
"snippet": "public class Edge {\n\n private Vertex startVertex;\n private Vertex endVertex;\n private int index;\n\n public Edge(Vertex startVertex, Vertex endVertex, int index) {\n this.startVertex = startVertex;\n this.endVertex = endVertex;\n this.index = index;\n }\n\n public Vertex getStartVertex() {\n return startVertex;\n }\n\n public Vertex getEndVertex() {\n return endVertex;\n }\n\n public int getIndex() {\n return index;\n }\n}"
},
{
"identifier": "Vertex",
"path": "src/main/java/io/github/mmm/measurement/survey/objects/graph/Vertex.java",
"snippet": "public class Vertex {\n\n private Vector3f position;\n private int index;\n\n public Vertex(Vector3f vec, int index) {\n this.position = vec;\n this.index = index;\n }\n\n public Vector3f getPosition() {\n return position;\n }\n\n public int getIndex() {\n return index;\n }\n}"
},
{
"identifier": "MMM_ROOT_PATH",
"path": "src/main/java/io/github/mmm/MMM.java",
"snippet": "public static final String MMM_ROOT_PATH = Minecraft.getInstance().gameDirectory.getPath() + \"/mmm_data/\";"
},
{
"identifier": "saveStringToFile",
"path": "src/main/java/io/github/mmm/Utils.java",
"snippet": "public static void saveStringToFile(String newData, String savePath, String fileName) {\n final String finalSavePath = MMM_ROOT_PATH + savePath + \"/\" + fileName;\n try {\n // Open the file in \"rw\" mode (read and write)\n RandomAccessFile file = new RandomAccessFile(finalSavePath, \"rw\");\n // Move the file pointer to the end of the file\n file.seek(file.length());\n // Write the data to the end of the file\n file.writeBytes(newData);\n // Close the file\n file.close();\n } catch (Exception e) {\n System.out.println(\"Error writing file: \" + e.getMessage());\n }\n}"
}
] | import io.github.mmm.MMM;
import io.github.mmm.measurement.survey.objects.Survey;
import io.github.mmm.measurement.survey.objects.graph.Edge;
import io.github.mmm.measurement.survey.objects.graph.Vertex;
import net.minecraft.client.Minecraft;
import net.minecraft.network.chat.Component;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.level.ClipContext;
import net.minecraft.world.level.Level;
import net.minecraft.world.phys.Vec3;
import org.joml.Vector3f;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import static io.github.mmm.MMM.MMM_ROOT_PATH;
import static io.github.mmm.Utils.saveStringToFile; | 1,774 | package io.github.mmm.measurement.survey;
public class SurveyController {
private Boolean currentlySurveying;
private String savePath;
private Survey survey;
public SurveyController() {
this.currentlySurveying = false;
}
public void startSurvey() {
this.survey = new Survey();
String startTime = DateTimeFormatter.ofPattern("yyyy-MM-dd_HH-mm-ss").format(LocalDateTime.now());
this.savePath = "survey_measurements/" + startTime;
try {
Files.createDirectories(Paths.get(MMM_ROOT_PATH + this.savePath));
} catch (Exception e) {
System.out.println("Error creating directory: " + e.getMessage());
}
saveStringToFile("index;xPosition;yPosition;zPosition\n", this.savePath, "vertices.csv");
saveStringToFile("index;startVertexIndex;endVertexIndex\n", this.savePath, "edges.csv");
Minecraft.getInstance().player.displayClientMessage(Component.translatable("chat." + MMM.MODID + ".survey.start"), false);
this.currentlySurveying = true;
}
public void stopSurvey() {
saveSurvey();
this.survey = null;
Minecraft.getInstance().player.displayClientMessage(Component.translatable("chat." + MMM.MODID + ".survey.stop"), false);
this.currentlySurveying = false;
}
public void measure() {
if (!this.currentlySurveying) return;
Player player = Minecraft.getInstance().player;
Level level = Minecraft.getInstance().level;
assert level != null && player != null;
Vec3 startPos = player.getEyePosition();
Vec3 endPos = startPos.add(player.getLookAngle().scale(256));
ClipContext context = new ClipContext(
startPos,
endPos,
ClipContext.Block.OUTLINE, // check block outlines
ClipContext.Fluid.NONE, // ignore fluids
player
);
Vector3f targetPosition = level.clip(context).getLocation().toVector3f();
Vertex newVertex = new Vertex(targetPosition, this.survey.getVertices().size());
this.survey.addVertex(newVertex);
if (!this.survey.getVertices().isEmpty()) { // if not first vertex
Vertex positionVertex = this.survey.getVertices().get(this.survey.getPositionVertexIndex()); | package io.github.mmm.measurement.survey;
public class SurveyController {
private Boolean currentlySurveying;
private String savePath;
private Survey survey;
public SurveyController() {
this.currentlySurveying = false;
}
public void startSurvey() {
this.survey = new Survey();
String startTime = DateTimeFormatter.ofPattern("yyyy-MM-dd_HH-mm-ss").format(LocalDateTime.now());
this.savePath = "survey_measurements/" + startTime;
try {
Files.createDirectories(Paths.get(MMM_ROOT_PATH + this.savePath));
} catch (Exception e) {
System.out.println("Error creating directory: " + e.getMessage());
}
saveStringToFile("index;xPosition;yPosition;zPosition\n", this.savePath, "vertices.csv");
saveStringToFile("index;startVertexIndex;endVertexIndex\n", this.savePath, "edges.csv");
Minecraft.getInstance().player.displayClientMessage(Component.translatable("chat." + MMM.MODID + ".survey.start"), false);
this.currentlySurveying = true;
}
public void stopSurvey() {
saveSurvey();
this.survey = null;
Minecraft.getInstance().player.displayClientMessage(Component.translatable("chat." + MMM.MODID + ".survey.stop"), false);
this.currentlySurveying = false;
}
public void measure() {
if (!this.currentlySurveying) return;
Player player = Minecraft.getInstance().player;
Level level = Minecraft.getInstance().level;
assert level != null && player != null;
Vec3 startPos = player.getEyePosition();
Vec3 endPos = startPos.add(player.getLookAngle().scale(256));
ClipContext context = new ClipContext(
startPos,
endPos,
ClipContext.Block.OUTLINE, // check block outlines
ClipContext.Fluid.NONE, // ignore fluids
player
);
Vector3f targetPosition = level.clip(context).getLocation().toVector3f();
Vertex newVertex = new Vertex(targetPosition, this.survey.getVertices().size());
this.survey.addVertex(newVertex);
if (!this.survey.getVertices().isEmpty()) { // if not first vertex
Vertex positionVertex = this.survey.getVertices().get(this.survey.getPositionVertexIndex()); | Edge newEdge = new Edge(positionVertex, newVertex, this.survey.getEdges().size()); | 2 | 2023-11-06 16:56:46+00:00 | 4k |
KilianCollins/road-runner-quickstart-master | TeamCode/src/main/java/org/firstinspires/ftc/teamcode/drive/opmode/ManualFeedforwardTuner.java | [
{
"identifier": "MAX_ACCEL",
"path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/drive/DriveConstants.java",
"snippet": "public static double MAX_ACCEL = 73.17330064499293;"
},
{
"identifier": "MAX_VEL",
"path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/drive/DriveConstants.java",
"snippet": "public static double MAX_VEL = 73.17330064499293;"
},
{
"identifier": "RUN_USING_ENCODER",
"path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/drive/DriveConstants.java",
"snippet": "public static final boolean RUN_USING_ENCODER = false;"
},
{
"identifier": "kA",
"path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/drive/DriveConstants.java",
"snippet": "public static double kA = 0;"
},
{
"identifier": "kStatic",
"path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/drive/DriveConstants.java",
"snippet": "public static double kStatic = 0;"
},
{
"identifier": "kV",
"path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/drive/DriveConstants.java",
"snippet": "public static double kV = 1.0 / rpmToVelocity(MAX_RPM);"
},
{
"identifier": "SampleMecanumDrive",
"path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/drive/SampleMecanumDrive.java",
"snippet": "@Config\n//@TeleOp(name=\"sample mechna drive \", group=\"Linear OpMode\")\npublic class SampleMecanumDrive extends MecanumDrive {\n public static PIDCoefficients TRANSLATIONAL_PID = new PIDCoefficients(0, 0, 0);\n public static PIDCoefficients HEADING_PID = new PIDCoefficients(0, 0, 0);\n\n public static double LATERAL_MULTIPLIER = .4;\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 IMU imu;\n private VoltageSensor batteryVoltageSensor;\n\n private List<Integer> lastEncPositions = new ArrayList<>();\n private List<Integer> lastEncVels = new ArrayList<>();\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\n\n\n //current functioning rr as of 10/21//\n////////////////////////////////////////////////////////////////////////////////////////////////////\n // TODO: adjust the names of the following hardware devices to match your configuration\n// imu = hardwareMap.get(IMU.class, \"imu\");\n// IMU.Parameters parameters = new IMU.Parameters(new RevHubOrientationOnRobot(\n// DriveConstants.LOGO_FACING_DIR, DriveConstants.USB_FACING_DIR));\n// imu.initialize(parameters);\n\n leftFront = hardwareMap.get(DcMotorEx.class, \"leftFront\");\n leftRear = hardwareMap.get(DcMotorEx.class, \"leftRear\");\n rightRear = hardwareMap.get(DcMotorEx.class, \"rightRear\");\n rightFront = hardwareMap.get(DcMotorEx.class, \"rightFront\");\n\n leftRear.setDirection(DcMotorSimple.Direction.REVERSE);\n leftFront.setDirection(DcMotorSimple.Direction.REVERSE);\n rightFront.setDirection(DcMotorSimple.Direction.FORWARD);\n rightRear.setDirection(DcMotorSimple.Direction.FORWARD);\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 // TODO: reverse any motors using DcMotor.setDirection()\n\n List<Integer> lastTrackingEncPositions = new ArrayList<>();\n List<Integer> lastTrackingEncVels = new ArrayList<>();\n\n // TODO: if desired, use setLocalizer() to change the localization method\n setLocalizer(new StandardTrackingWheelLocalizer(hardwareMap, lastTrackingEncPositions, lastTrackingEncVels));\n //setLocalizer(new StandardTrackingWheelLocalizer(hardwareMap));\n\n trajectorySequenceRunner = new TrajectorySequenceRunner(\n follower, HEADING_PID, batteryVoltageSensor,\n lastEncPositions, lastEncVels, lastTrackingEncPositions, lastTrackingEncVels\n );\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 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 lastEncPositions.clear();\n\n List<Double> wheelPositions = new ArrayList<>();\n for (DcMotorEx motor : motors) {\n int position = motor.getCurrentPosition();\n lastEncPositions.add(position);\n wheelPositions.add(encoderTicksToInches(position));\n }\n return wheelPositions;\n }\n\n @Override\n public List<Double> getWheelVelocities() {\n lastEncVels.clear();\n\n List<Double> wheelVelocities = new ArrayList<>();\n for (DcMotorEx motor : motors) {\n int vel = (int) motor.getVelocity();\n lastEncVels.add(vel);\n wheelVelocities.add(encoderTicksToInches(vel));\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 0.0;\n }\n\n @Override\n public Double getExternalHeadingVelocity() {\n return 0.0;\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}"
}
] | import static org.firstinspires.ftc.teamcode.drive.DriveConstants.MAX_ACCEL;
import static org.firstinspires.ftc.teamcode.drive.DriveConstants.MAX_VEL;
import static org.firstinspires.ftc.teamcode.drive.DriveConstants.RUN_USING_ENCODER;
import static org.firstinspires.ftc.teamcode.drive.DriveConstants.kA;
import static org.firstinspires.ftc.teamcode.drive.DriveConstants.kStatic;
import static org.firstinspires.ftc.teamcode.drive.DriveConstants.kV;
import com.acmerobotics.dashboard.FtcDashboard;
import com.acmerobotics.dashboard.config.Config;
import com.acmerobotics.dashboard.telemetry.MultipleTelemetry;
import com.acmerobotics.roadrunner.geometry.Pose2d;
import com.acmerobotics.roadrunner.kinematics.Kinematics;
import com.acmerobotics.roadrunner.profile.MotionProfile;
import com.acmerobotics.roadrunner.profile.MotionProfileGenerator;
import com.acmerobotics.roadrunner.profile.MotionState;
import com.acmerobotics.roadrunner.util.NanoClock;
import com.qualcomm.robotcore.eventloop.opmode.Autonomous;
import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;
import com.qualcomm.robotcore.hardware.VoltageSensor;
import com.qualcomm.robotcore.util.RobotLog;
import org.firstinspires.ftc.robotcore.external.Telemetry;
import org.firstinspires.ftc.teamcode.drive.SampleMecanumDrive;
import java.util.Objects; | 3,519 | package org.firstinspires.ftc.teamcode.drive.opmode;
/*
* This routine is designed to tune the open-loop feedforward coefficients. Although it may seem unnecessary,
* tuning these coefficients is just as important as the positional parameters. Like the other
* manual tuning routines, this op mode relies heavily upon the dashboard. To access the dashboard,
* connect your computer to the RC's WiFi network. In your browser, navigate to
* https://192.168.49.1:8080/dash if you're using the RC phone or https://192.168.43.1:8080/dash if
* you are using the Control Hub. Once you've successfully connected, start the program, and your
* robot will begin moving forward and backward according to a motion profile. Your job is to graph
* the velocity errors over time and adjust the feedforward coefficients. Once you've found a
* satisfactory set of gains, add them to the appropriate fields in the DriveConstants.java file.
*
* Pressing Y/Δ (Xbox/PS4) will pause the tuning process and enter driver override, allowing the
* user to reset the position of the bot in the event that it drifts off the path.
* Pressing B/O (Xbox/PS4) will cede control back to the tuning process.
*/
@Config
@Autonomous(group = "drive")
public class ManualFeedforwardTuner extends LinearOpMode {
public static double DISTANCE = 72; // in
private FtcDashboard dashboard = FtcDashboard.getInstance();
private SampleMecanumDrive drive;
enum Mode {
DRIVER_MODE,
TUNING_MODE
}
private Mode mode;
private static MotionProfile generateProfile(boolean movingForward) {
MotionState start = new MotionState(movingForward ? 0 : DISTANCE, 0, 0, 0);
MotionState goal = new MotionState(movingForward ? DISTANCE : 0, 0, 0, 0);
return MotionProfileGenerator.generateSimpleMotionProfile(start, goal, MAX_VEL, MAX_ACCEL);
}
@Override
public void runOpMode() { | package org.firstinspires.ftc.teamcode.drive.opmode;
/*
* This routine is designed to tune the open-loop feedforward coefficients. Although it may seem unnecessary,
* tuning these coefficients is just as important as the positional parameters. Like the other
* manual tuning routines, this op mode relies heavily upon the dashboard. To access the dashboard,
* connect your computer to the RC's WiFi network. In your browser, navigate to
* https://192.168.49.1:8080/dash if you're using the RC phone or https://192.168.43.1:8080/dash if
* you are using the Control Hub. Once you've successfully connected, start the program, and your
* robot will begin moving forward and backward according to a motion profile. Your job is to graph
* the velocity errors over time and adjust the feedforward coefficients. Once you've found a
* satisfactory set of gains, add them to the appropriate fields in the DriveConstants.java file.
*
* Pressing Y/Δ (Xbox/PS4) will pause the tuning process and enter driver override, allowing the
* user to reset the position of the bot in the event that it drifts off the path.
* Pressing B/O (Xbox/PS4) will cede control back to the tuning process.
*/
@Config
@Autonomous(group = "drive")
public class ManualFeedforwardTuner extends LinearOpMode {
public static double DISTANCE = 72; // in
private FtcDashboard dashboard = FtcDashboard.getInstance();
private SampleMecanumDrive drive;
enum Mode {
DRIVER_MODE,
TUNING_MODE
}
private Mode mode;
private static MotionProfile generateProfile(boolean movingForward) {
MotionState start = new MotionState(movingForward ? 0 : DISTANCE, 0, 0, 0);
MotionState goal = new MotionState(movingForward ? DISTANCE : 0, 0, 0, 0);
return MotionProfileGenerator.generateSimpleMotionProfile(start, goal, MAX_VEL, MAX_ACCEL);
}
@Override
public void runOpMode() { | if (RUN_USING_ENCODER) { | 2 | 2023-11-04 04:11:26+00:00 | 4k |
Guzz-drk/api_gestao_vagas | src/test/java/br/com/guzz/gestao_vagas/modules/candidate/useCases/ApplyJobCandidateUserCaseTest.java | [
{
"identifier": "JobNotFoundException",
"path": "src/main/java/br/com/guzz/gestao_vagas/exceptions/JobNotFoundException.java",
"snippet": "public class JobNotFoundException extends RuntimeException{\n \n public JobNotFoundException(String msg){\n super(msg);\n }\n}"
},
{
"identifier": "UserNotFoundException",
"path": "src/main/java/br/com/guzz/gestao_vagas/exceptions/UserNotFoundException.java",
"snippet": "public class UserNotFoundException extends RuntimeException{\n \n public UserNotFoundException(String msg){\n super(msg);\n }\n}"
},
{
"identifier": "ApplyJobEntity",
"path": "src/main/java/br/com/guzz/gestao_vagas/modules/candidate/entity/ApplyJobEntity.java",
"snippet": "@Data\n@AllArgsConstructor\n@NoArgsConstructor\n@Builder\n\n@Entity(name = \"aaply_jobs\")\npublic class ApplyJobEntity {\n \n @Id\n @GeneratedValue(strategy = GenerationType.UUID)\n private UUID id;\n\n @ManyToOne\n @JoinColumn(name = \"candidate_id\", insertable = false, updatable = false)\n private CandidateEntity candidateEntity;\n\n @ManyToOne\n @JoinColumn(name = \"job_id\", insertable = false, updatable = false)\n private JobEntity jobEntity;\n\n @Column(name = \"candidate_id\")\n private UUID candidateId;\n\n @Column(name = \"job_id\")\n private UUID jobId;\n\n @CreationTimestamp\n private LocalDateTime createdAt;\n}"
},
{
"identifier": "CandidateEntity",
"path": "src/main/java/br/com/guzz/gestao_vagas/modules/candidate/entity/CandidateEntity.java",
"snippet": "@Data\n@AllArgsConstructor\n@NoArgsConstructor\n\n@Entity(name = \"candidate\")\npublic class CandidateEntity {\n\n @Id\n @GeneratedValue(strategy = GenerationType.UUID)\n private UUID id;\n\n @Schema(example = \"Gustavo\", description = \"Nome do candidato\")\n private String name;\n\n @NotBlank\n @Pattern(regexp = \"\\\\S+\", message = \"O campo [username] não deve conter espaço\")\n @Schema(example = \"guzz-drk\", description = \"Username do candidato\")\n private String username;\n\n @Email(message = \"O campo [email] deve conter um e-mail válido\")\n @Schema(example = \"[email protected]\", description = \"E-mail do candidato\")\n private String email;\n\n @Length(min = 5, max = 100, message = \"O campo [password] deve conter entre (5) e (100) caracteres\")\n @Schema(example = \"@@@adfsa#$##\", minLength = 5, maxLength = 100, requiredMode = RequiredMode.REQUIRED, description = \"Senha do candidato\")\n private String password;\n\n @Schema(example = \"Amante de programação\", description = \"Descrição do candidato\")\n private String description;\n\n private String curriculum;\n\n @CreationTimestamp\n private LocalDateTime createdAt;\n}"
},
{
"identifier": "ApplyJobRepository",
"path": "src/main/java/br/com/guzz/gestao_vagas/modules/candidate/repository/ApplyJobRepository.java",
"snippet": "public interface ApplyJobRepository extends JpaRepository<ApplyJobEntity, UUID> {\n\n}"
},
{
"identifier": "CandidateRepository",
"path": "src/main/java/br/com/guzz/gestao_vagas/modules/candidate/repository/CandidateRepository.java",
"snippet": "public interface CandidateRepository extends JpaRepository<CandidateEntity, UUID> {\n\n Optional<CandidateEntity> findByUsernameOrEmail(String username, String email);\n Optional<CandidateEntity> findByUsername(String username);\n}"
},
{
"identifier": "JobEntity",
"path": "src/main/java/br/com/guzz/gestao_vagas/modules/company/entity/JobEntity.java",
"snippet": "@Data\n@AllArgsConstructor\n@NoArgsConstructor\n@Builder\n\n@Entity(name = \"job\")\npublic class JobEntity {\n \n @Id\n @GeneratedValue(strategy = GenerationType.UUID)\n private UUID id;\n\n @Schema(example = \"Vaga para Design\")\n private String description;\n\n @Schema(example = \"Gympass\")\n private String benefits;\n\n @NotBlank(message = \"O campo [level] é obrigatório\")\n @Schema(example = \"Senior\")\n private String level;\n\n @ManyToOne()\n @JoinColumn(name = \"company_id\", insertable = false, updatable = false)\n private CompanyEntity companyEntity;\n\n @Column(name = \"company_id\", nullable = false)\n private UUID companyId;\n\n @CreationTimestamp\n private LocalDateTime createdAt;\n}"
},
{
"identifier": "JobRepository",
"path": "src/main/java/br/com/guzz/gestao_vagas/modules/company/repository/JobRepository.java",
"snippet": "public interface JobRepository extends JpaRepository<JobEntity, UUID>{\n \n List<JobEntity> findByDescriptionContainingIgnoreCase(String filter);\n\n}"
}
] | 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.junit.jupiter.MockitoExtension;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.mockito.Mockito.when;
import java.util.Optional;
import java.util.UUID;
import org.assertj.core.api.Assertions;
import br.com.guzz.gestao_vagas.exceptions.JobNotFoundException;
import br.com.guzz.gestao_vagas.exceptions.UserNotFoundException;
import br.com.guzz.gestao_vagas.modules.candidate.entity.ApplyJobEntity;
import br.com.guzz.gestao_vagas.modules.candidate.entity.CandidateEntity;
import br.com.guzz.gestao_vagas.modules.candidate.repository.ApplyJobRepository;
import br.com.guzz.gestao_vagas.modules.candidate.repository.CandidateRepository;
import br.com.guzz.gestao_vagas.modules.company.entity.JobEntity;
import br.com.guzz.gestao_vagas.modules.company.repository.JobRepository; | 1,661 | package br.com.guzz.gestao_vagas.modules.candidate.useCases;
@ExtendWith(MockitoExtension.class)
public class ApplyJobCandidateUserCaseTest {
@InjectMocks
private ApplyJobCandidateUserCase applyJobCandidateUserCase;
@Mock
private CandidateRepository candidateRepository;
@Mock
private JobRepository jobRepository;
@Mock
private ApplyJobRepository applyJobRepository;
@Test
@DisplayName("Should Not Be Able To Apply Job With Candidate Not Found")
public void shouldNotBeAbleToApplyJobWithCandidateNotFound() {
try {
applyJobCandidateUserCase.execute(null, null);
} catch (Exception e) {
Assertions.assertThat(e).isInstanceOf(UserNotFoundException.class);
}
}
@Test
@DisplayName("Should Not Be Able To Apply Job With Job Not Found")
public void shouldNotBeAbleToApplyJobWithJobNotFound(){
var idCandidate = UUID.randomUUID();
var candidate = new CandidateEntity();
candidate.setId(idCandidate);
when(candidateRepository.findById(idCandidate)).thenReturn(Optional.of(candidate));
try {
applyJobCandidateUserCase.execute(idCandidate, null);
} catch (Exception e) {
Assertions.assertThat(e).isInstanceOf(JobNotFoundException.class);
}
}
@Test
@DisplayName("Should Be Able To Create A New Apply Job")
public void shouldBeAbleToCreateANewApplyJob(){
var idCandidate = UUID.randomUUID();
var idJob = UUID.randomUUID();
var applyJob = ApplyJobEntity.builder().candidateId(idCandidate).jobId(idJob).build();
var applyJobCreated = ApplyJobEntity.builder().id(UUID.randomUUID()).build();
when(candidateRepository.findById(idCandidate)).thenReturn(Optional.of(new CandidateEntity()));
| package br.com.guzz.gestao_vagas.modules.candidate.useCases;
@ExtendWith(MockitoExtension.class)
public class ApplyJobCandidateUserCaseTest {
@InjectMocks
private ApplyJobCandidateUserCase applyJobCandidateUserCase;
@Mock
private CandidateRepository candidateRepository;
@Mock
private JobRepository jobRepository;
@Mock
private ApplyJobRepository applyJobRepository;
@Test
@DisplayName("Should Not Be Able To Apply Job With Candidate Not Found")
public void shouldNotBeAbleToApplyJobWithCandidateNotFound() {
try {
applyJobCandidateUserCase.execute(null, null);
} catch (Exception e) {
Assertions.assertThat(e).isInstanceOf(UserNotFoundException.class);
}
}
@Test
@DisplayName("Should Not Be Able To Apply Job With Job Not Found")
public void shouldNotBeAbleToApplyJobWithJobNotFound(){
var idCandidate = UUID.randomUUID();
var candidate = new CandidateEntity();
candidate.setId(idCandidate);
when(candidateRepository.findById(idCandidate)).thenReturn(Optional.of(candidate));
try {
applyJobCandidateUserCase.execute(idCandidate, null);
} catch (Exception e) {
Assertions.assertThat(e).isInstanceOf(JobNotFoundException.class);
}
}
@Test
@DisplayName("Should Be Able To Create A New Apply Job")
public void shouldBeAbleToCreateANewApplyJob(){
var idCandidate = UUID.randomUUID();
var idJob = UUID.randomUUID();
var applyJob = ApplyJobEntity.builder().candidateId(idCandidate).jobId(idJob).build();
var applyJobCreated = ApplyJobEntity.builder().id(UUID.randomUUID()).build();
when(candidateRepository.findById(idCandidate)).thenReturn(Optional.of(new CandidateEntity()));
| when(jobRepository.findById(idJob)).thenReturn(Optional.of(new JobEntity())); | 6 | 2023-11-05 13:45:16+00:00 | 4k |
alejandalb/metaIoT-operation-manager-service | src/main/java/com/upv/alalca3/metaIoT/operationmanager/service/impl/MqttService.java | [
{
"identifier": "Message",
"path": "src/main/java/com/upv/alalca3/metaIoT/operationmanager/model/Message.java",
"snippet": "@Entity\npublic class Message {\n\t@Id\n\t@GeneratedValue(strategy = GenerationType.IDENTITY)\n\tprivate Long id;\n\n\t@ManyToOne(cascade = CascadeType.MERGE)\n\t@JoinColumn(name = \"operation_id\")\n\tprivate Operation operation;\n\n\t@ManyToOne(cascade = { CascadeType.PERSIST, CascadeType.MERGE })\n\t@JoinColumn(name = \"device_id\")\n\tprivate Device device;\n\n\tprivate String content;\n\tprivate String type;\n\n\t/**\n\t * @return the id\n\t */\n\tpublic Long getId() {\n\t\treturn id;\n\t}\n\n\t/**\n\t * @param id the id to set\n\t */\n\tpublic void setId(Long id) {\n\t\tthis.id = id;\n\t}\n\n\t/**\n\t * @return the operation\n\t */\n\tpublic Operation getOperation() {\n\t\treturn operation;\n\t}\n\n\t/**\n\t * @param operation the operation to set\n\t */\n\tpublic void setOperation(Operation operation) {\n\t\tthis.operation = operation;\n\t}\n\n\t/**\n\t * @return the device\n\t */\n\tpublic Device getDevice() {\n\t\treturn device;\n\t}\n\n\t/**\n\t * @param device the device to set\n\t */\n\tpublic void setDevice(Device device) {\n\t\tthis.device = device;\n\t}\n\n\t/**\n\t * @return the content\n\t */\n\tpublic String getContent() {\n\t\treturn content;\n\t}\n\n\t/**\n\t * @param content the content to set\n\t */\n\tpublic void setContent(String content) {\n\t\tthis.content = content;\n\t}\n\n\t/**\n\t * @return the type\n\t */\n\tpublic String getType() {\n\t\treturn type;\n\t}\n\n\t/**\n\t * @param type the type to set\n\t */\n\tpublic void setType(String type) {\n\t\tthis.type = type;\n\t}\n\n}"
},
{
"identifier": "MessageRepository",
"path": "src/main/java/com/upv/alalca3/metaIoT/operationmanager/model/jpa/MessageRepository.java",
"snippet": "public interface MessageRepository extends CrudRepository<Message, Long> {\n}"
},
{
"identifier": "MqttGateway",
"path": "src/main/java/com/upv/alalca3/metaIoT/operationmanager/mqtt/MqttGateway.java",
"snippet": "@Component\npublic class MqttGateway {\n\n\tprivate MqttClient client;\n\n\tprivate final MqttProperties mqttProperties;\n\n\t/**\n\t * Default constructor\n\t * \n\t * @param mqttProperties Mqtt functionality properties\n\t */\n\t@Autowired\n\tpublic MqttGateway(MqttProperties mqttProperties) {\n\t\tthis.mqttProperties = mqttProperties;\n\t\ttry {\n\n\t\t\tthis.client = new MqttClient(this.mqttProperties.getBroker().getUrl(),\n\t\t\t\t\tthis.mqttProperties.getClient().getId());\n\t\t\tMqttConnectOptions options = new MqttConnectOptions();\n\t\t\toptions.setUserName(this.mqttProperties.getUsername());\n\t\t\toptions.setPassword(this.mqttProperties.getPassword().toCharArray());\n\t\t\toptions.setAutomaticReconnect(this.mqttProperties.isAutoReconnect());\n\t\t\tthis.client.connect(options);\n\t\t} catch (MqttException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}\n\n\t/**\n\t * @param topic topic to be subscribed\n\t * @param callback callback method\n\t */\n\tpublic void subscribe(String topic, MqttCallback callback) {\n\t\ttry {\n\t\t\tthis.client.setCallback(callback);\n\t\t\tthis.client.subscribe(topic, this.mqttProperties.getQos());\n\t\t} catch (MqttException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}\n\n\t/**\n\t * @param topic topic to be subscribed\n\t * @param payload message to be published\n\t */\n\tpublic void publish(String topic, String payload) {\n\t\ttry {\n\t\t\tMqttMessage message = new MqttMessage(payload.getBytes());\n\t\t\tmessage.setQos(this.mqttProperties.getQos());\n\t\t\tthis.client.publish(topic, message);\n\t\t} catch (MqttException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}\n}"
},
{
"identifier": "MqttProperties",
"path": "src/main/java/com/upv/alalca3/metaIoT/operationmanager/mqtt/properties/MqttProperties.java",
"snippet": "@Configuration\n@ConfigurationProperties(prefix = \"mqtt\")\n@Validated\npublic class MqttProperties {\n\n\tprivate TopicProperties topics;\n\tprivate BrokerProperties broker;\n\tprivate ClientProperties client;\n\tprivate String username;\n\tprivate String password;\n\tprivate int qos;\n\tprivate boolean autoReconnect;\n\n\t/**\n\t * @return the topics\n\t */\n\tpublic TopicProperties getTopics() {\n\t\treturn this.topics;\n\t}\n\n\t/**\n\t * @param topics the topics to set\n\t */\n\tpublic void setTopics(TopicProperties topics) {\n\t\tthis.topics = topics;\n\t}\n\n\t/**\n\t * @return the broker\n\t */\n\tpublic BrokerProperties getBroker() {\n\t\treturn this.broker;\n\t}\n\n\t/**\n\t * @param broker the broker to set\n\t */\n\tpublic void setBroker(BrokerProperties broker) {\n\t\tthis.broker = broker;\n\t}\n\n\t/**\n\t * @return the client\n\t */\n\tpublic ClientProperties getClient() {\n\t\treturn this.client;\n\t}\n\n\t/**\n\t * @param client the client to set\n\t */\n\tpublic void setClient(ClientProperties client) {\n\t\tthis.client = client;\n\t}\n\n\t/**\n\t * @return the username\n\t */\n\tpublic String getUsername() {\n\t\treturn this.username;\n\t}\n\n\t/**\n\t * @param username the username to set\n\t */\n\tpublic void setUsername(String username) {\n\t\tthis.username = username;\n\t}\n\n\t/**\n\t * @return the password\n\t */\n\tpublic String getPassword() {\n\t\treturn this.password;\n\t}\n\n\t/**\n\t * @param password the password to set\n\t */\n\tpublic void setPassword(String password) {\n\t\tthis.password = password;\n\t}\n\n\t/**\n\t * @return the qos\n\t */\n\tpublic int getQos() {\n\t\treturn this.qos;\n\t}\n\n\t/**\n\t * @param qos the qos to set\n\t */\n\tpublic void setQos(int qos) {\n\t\tthis.qos = qos;\n\t}\n\n\t/**\n\t * @return the autoReconnect\n\t */\n\tpublic boolean isAutoReconnect() {\n\t\treturn this.autoReconnect;\n\t}\n\n\t/**\n\t * @param autoReconnect the autoReconnect to set\n\t */\n\tpublic void setAutoReconnect(boolean autoReconnect) {\n\t\tthis.autoReconnect = autoReconnect;\n\t}\n}"
},
{
"identifier": "IMqttService",
"path": "src/main/java/com/upv/alalca3/metaIoT/operationmanager/service/IMqttService.java",
"snippet": "public interface IMqttService {\n\n\tvoid publishOperation(String additionalPath, String message);\n\n\tvoid subscribeToAckTopic(MqttCallback callback);\n\n\tvoid subscribeToCompletionTopic(MqttCallback callback);\n\n\tvoid subscribeToRejectionTopic(MqttCallback callback);\n\n\t/**\n\t * Subscribes to the specified MQTT topics.\n\t *\n\t * @param topics the topics to subscribe to\n\t */\n\tvoid subscribe();\n\n}"
}
] | import java.nio.charset.StandardCharsets;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttCallbackExtended;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.upv.alalca3.metaIoT.operationmanager.model.Message;
import com.upv.alalca3.metaIoT.operationmanager.model.jpa.MessageRepository;
import com.upv.alalca3.metaIoT.operationmanager.mqtt.MqttGateway;
import com.upv.alalca3.metaIoT.operationmanager.mqtt.properties.MqttProperties;
import com.upv.alalca3.metaIoT.operationmanager.service.IMqttService; | 2,071 | package com.upv.alalca3.metaIoT.operationmanager.service.impl;
@Service
public class MqttService implements IMqttService {
private static final Logger LOGGER = LoggerFactory.getLogger(MqttService.class);
private final MqttProperties mqttProperties;
| package com.upv.alalca3.metaIoT.operationmanager.service.impl;
@Service
public class MqttService implements IMqttService {
private static final Logger LOGGER = LoggerFactory.getLogger(MqttService.class);
private final MqttProperties mqttProperties;
| private final MqttGateway mqttGateway; | 2 | 2023-11-06 18:25:36+00:00 | 4k |
hoffmann-g/trabalho-final-poo | src/main/java/application/Main.java | [
{
"identifier": "InvoiceTab",
"path": "src/main/java/application/tabs/InvoiceTab.java",
"snippet": "public class InvoiceTab {\n\n private CarRental carRental;\n\n private JPanel background;\n\n private final JTextPane plate = new JTextPane();\n\n private String outputQRCodePath;\n\n public InvoiceTab(){\n initUI();\n }\n\n private void initUI(){\n // instantiate\n background = new JPanel();\n JPanel details = new JPanel();\n JPanel buttons = new JPanel();\n JPanel labelPanel = new JPanel();\n JLabel title = new JLabel(\"Invoice\");\n\n // define layouts\n background.setLayout(new BorderLayout());\n details.setLayout(new GridBagLayout());\n buttons.setLayout(new FlowLayout());\n\n // adds\n labelPanel.add(title);\n details.add(plate);\n\n // add to bg\n background.add(labelPanel, BorderLayout.PAGE_START);\n background.add(details, BorderLayout.CENTER);\n background.add(buttons, BorderLayout.PAGE_END);\n\n // color\n background.setBackground(Color.DARK_GRAY);\n buttons.setBackground(Color.white);\n details.setBackground(Color.GRAY);\n plate.setBackground(Color.gray);\n\n // font\n title.setFont(new Font(\"Tahoma\", Font.PLAIN, 16));\n plate.setFont(new Font(\"Serif\", Font.PLAIN, 16));\n //\n\n JButton generateCode = new JButton(\"Generate Code\");\n generateCode.addActionListener(e -> {\n try {\n String message = \"https://payment-link/(value: \" + carRental.getInvoice().totalPayment().toString() + \")\";\n\n QRCodeManager.createQRImage(new File(outputQRCodePath),\n message, 250, \"png\");\n\n System.out.println(\"QR Code created\");\n\n showQRCode(outputQRCodePath);\n } catch (Exception ex) {\n throw new RuntimeException(\"could not create QR code\");\n }\n\n });\n buttons.add(generateCode);\n\n JButton generateFile = new JButton(\"Export\");\n generateFile.addActionListener(e -> {\n try {\n DateTimeFormatter outputformat = DateTimeFormatter.ofPattern(\"dd-MM-yyyy-HH-mm\");\n DateTimeFormatter dtf = DateTimeFormatter.ofPattern(\"dd/MM/yyyy HH:mm\");\n\n FileWriter fw = new FileWriter(carRental.getVehicle().getModel() + \"_\" + carRental.getFinish().format(outputformat) + \".txt\");\n fw.write(\"PLATE: \" + carRental.getVehicle().getModel());\n fw.write(\"\\nstart: \" + carRental.getStart().format(dtf));\n fw.write(\"\\nfinish: \" + carRental.getFinish().format(dtf));\n fw.write(\"\\n\");\n fw.write(\"\\nbasic payment: \" + carRental.getInvoice().getBasicPayment().toString());\n fw.write(\"\\ntax: \" + carRental.getInvoice().getTax().toString());\n fw.write(\"\\nTOTAL: \" + carRental.getInvoice().totalPayment().toString());\n fw.close();\n\n System.out.println(\"file exported\");\n } catch (IOException ex) {\n throw new RuntimeException(ex);\n }\n });\n buttons.add(generateFile);\n\n generateFile.setBackground(Color.white);\n generateCode.setBackground(Color.white);\n }\n\n public void loadInvoice(CarRental carRental){\n this.carRental = carRental;\n\n DateTimeFormatter dtf = DateTimeFormatter.ofPattern(\"dd/MM/yyyy HH:mm:ss\");\n\n //details\n String invoice = \"PLATE: \" + carRental.getVehicle().getModel() +\n \"\\nstart: \" + carRental.getStart().format(dtf) +\n \"\\nfinish: \" + carRental.getFinish().format(dtf) +\n \"\\n\" +\n \"\\nbasic payment: R$\" + carRental.getInvoice().getBasicPayment() +\n \"\\ntax: R$\" + carRental.getInvoice().getTax() +\n \"\\nTOTAL: R$\" + carRental.getInvoice().totalPayment();\n plate.setBackground(Color.white);\n plate.setText(invoice);\n\n }\n\n private void showQRCode(String path) throws IOException {\n JDialog paymentDialog = new JDialog();\n paymentDialog.setTitle(\"QR Code\");\n\n JPanel panel = new JPanel(new BorderLayout());\n\n ImageIcon icon = new ImageIcon(path);\n JLabel imageLabel = new JLabel(icon);\n\n panel.add(imageLabel, BorderLayout.CENTER);\n\n paymentDialog.add(panel);\n\n paymentDialog.setSize(new Dimension(icon.getIconWidth(), icon.getIconHeight()));\n paymentDialog.setLocationRelativeTo(background);\n paymentDialog.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);\n\n paymentDialog.setVisible(true);\n\n Files.delete(Path.of(path));\n }\n\n public JPanel getBackground() {\n return background;\n }\n\n public void setOutputQRCodePath(String outputQRCodePath) {\n this.outputQRCodePath = outputQRCodePath;\n }\n}"
},
{
"identifier": "RentalTab",
"path": "src/main/java/application/tabs/RentalTab.java",
"snippet": "public class RentalTab extends Tab<CarRental>{\n\n private final InvoiceTab invoiceTab;\n\n private final DataAccessObject<CarRental> carRentalDao;\n private final DataAccessObject<Vehicle> vehicleDao;\n private final RentalService rentalService;\n\n private CarRental rental;\n\n public RentalTab(String name, InvoiceTab invoiceTab, DataAccessObject<CarRental> carRentalDao, DataAccessObject<Vehicle> vehicleDao, RentalService rentalService) {\n super(name);\n this.invoiceTab = invoiceTab;\n this.carRentalDao = carRentalDao;\n this.vehicleDao = vehicleDao;\n this.rentalService = rentalService;\n }\n\n public void initUI(){\n for(CarRental cr : carRentalDao.readRows()){\n insertIntoList(cr);\n }\n\n JButton createRental = new JButton(\"+\");\n createRental.addActionListener(e -> {\n\n List<CarRental> carRentalList = carRentalDao.readRows();\n List<Vehicle> vehicles = vehicleDao.readRows();\n\n carRentalList.forEach(x -> vehicles.remove(x.getVehicle()));\n\n System.out.println(\"available vehicles\");\n System.out.println(vehicles);\n\n Vehicle selectedVehicle = (Vehicle) JOptionPane.showInputDialog(\n null,\n null,\n \"Select a vehicle:\",\n JOptionPane.QUESTION_MESSAGE,\n null,\n vehicles.toArray(),\n null\n );\n\n DateTimeFormatter dtf = DateTimeFormatter.ofPattern(\"yyyy/MM/dd HH:mm:ss\");\n String now = LocalDateTime.now().format(dtf);\n\n String selectedTime = (String)JOptionPane.showInputDialog(\n null,\n \"PATTERN: yyyy/MM/dd HH:mm:ss\",\n \"Select start time\",\n JOptionPane.PLAIN_MESSAGE,\n null,\n null,\n now\n );\n\n if (selectedVehicle != null) {\n selectedTime = selectedTime.replaceAll(\"/\", \"-\");\n selectedTime = selectedTime.replaceAll(\" \", \"T\");\n\n CarRental cr1 = new CarRental(LocalDateTime.parse(selectedTime), null, selectedVehicle);\n\n try {\n insertIntoList(cr1);\n carRentalDao.insertRow(cr1);\n } catch (InvalidParameterException ex){\n System.out.println(\"rental already exists\");\n JOptionPane.showMessageDialog(getBackgroundPanel(), \"Rental already exists!\",\n \"Error\", JOptionPane.WARNING_MESSAGE);\n }\n }\n });\n addButton(createRental);\n\n JButton deleteRental = new JButton(\"-\");\n deleteRental.addActionListener(e -> {\n if (getSelectedValue() != null){\n removeFromList(getSelectedValue());\n carRentalDao.deleteRow(getSelectedValue());\n }\n });\n addButton(deleteRental);\n\n JButton finalizeRental = new JButton(\"Process Invoice\");\n finalizeRental.addActionListener(e -> {\n if (getSelectedValue() != null){\n rental = getSelectedValue();\n rental.setFinish(LocalDateTime.now());\n rentalService.processInvoice(rental);\n System.out.println(\"processed\");\n\n invoiceTab.loadInvoice(rental);\n removeFromList(rental);\n carRentalDao.deleteRow(rental);\n }\n });\n addButton(finalizeRental);\n }\n}"
},
{
"identifier": "VehicleTab",
"path": "src/main/java/application/tabs/VehicleTab.java",
"snippet": "public class VehicleTab extends Tab<Vehicle> {\n\n private final DataAccessObject<Vehicle> dao;\n\n public VehicleTab(String name, DataAccessObject<Vehicle> dao) {\n super(name);\n this.dao = dao;\n }\n\n public void initUI(){\n for(Vehicle v : dao.readRows()){\n insertIntoList(v);\n }\n\n JButton createVehicle = new JButton(\"+\");\n createVehicle.addActionListener(e -> {\n String plate = JOptionPane.showInputDialog(\"License plate:\");\n if (plate != null){\n try {\n insertIntoList(new Vehicle(plate.toUpperCase().replaceAll(\" \", \"-\")));\n dao.insertRow(new Vehicle(plate.toUpperCase().replaceAll(\" \", \"-\")));\n } catch (InvalidParameterException ex){\n System.out.println(\"vehicle already exists\");\n JOptionPane.showMessageDialog(getBackgroundPanel(), \"Vehicle already exists!\",\n \"Error\", JOptionPane.WARNING_MESSAGE);\n }\n }\n });\n addButton(createVehicle);\n\n JButton deleteVehicle = new JButton(\"-\");\n deleteVehicle.addActionListener(e -> {\n if (getSelectedValue() != null){\n removeFromList(getSelectedValue());\n dao.deleteRow(getSelectedValue());\n }\n });\n addButton(deleteVehicle);\n }\n}"
},
{
"identifier": "DaoFactory",
"path": "src/main/java/model/dao/DaoFactory.java",
"snippet": "public class DaoFactory {\n\n private static String vehiclePath;\n private static String carRentalPath;\n\n public static DataAccessObject<Vehicle> createVehicleDao(){\n return new VehicleDaoCSV(vehiclePath);\n }\n\n public static DataAccessObject<CarRental> createCarRentalDao(){\n return new CarRentalDaoCSV(carRentalPath);\n }\n\n public static void setCarRentalPath(String path){\n DaoFactory.carRentalPath = path;\n }\n\n public static void setVehiclePath(String path){\n DaoFactory.vehiclePath = path;\n }\n\n}"
},
{
"identifier": "BrazilTaxService",
"path": "src/main/java/model/services/BrazilTaxService.java",
"snippet": "public class BrazilTaxService implements TaxService{\n\n @Override\n public Double tax(Double amount) {\n if(amount > 100){\n return amount * 0.15;\n } else {\n return amount * 0.2;\n }\n }\n}"
},
{
"identifier": "RentalService",
"path": "src/main/java/model/services/RentalService.java",
"snippet": "public class RentalService {\n\n private Double pricePerHour;\n private Double pricePerDay;\n\n private TaxService taxService;\n\n public RentalService(Double pricePerHour, Double pricePerDay, TaxService taxService) {\n this.pricePerHour = pricePerHour;\n this.pricePerDay = pricePerDay;\n this.taxService = taxService;\n }\n\n public void processInvoice(CarRental carRental){\n double minutes = Duration.between(carRental.getStart(), carRental.getFinish()).toMinutes();\n double hours = minutes / 60;\n double basicPayment;\n\n if (hours <= 12){\n basicPayment = pricePerHour * Math.ceil(hours);\n } else {\n basicPayment = pricePerDay * Math.ceil(hours/24);\n }\n\n double tax = taxService.tax(basicPayment);\n carRental.setInvoice(new Invoice(basicPayment, tax));\n }\n}"
}
] | import application.tabs.InvoiceTab;
import application.tabs.RentalTab;
import application.tabs.VehicleTab;
import model.dao.DaoFactory;
import model.services.BrazilTaxService;
import model.services.RentalService;
import javax.swing.*;
import java.awt.*; | 2,849 | package application;
public class Main {
public static void main(String[] args){
RentalService rs = new RentalService(5., 80., new BrazilTaxService());
DaoFactory.setVehiclePath("garage.csv");
DaoFactory.setCarRentalPath("rentals.csv");
InvoiceTab invoiceTab = new InvoiceTab();
VehicleTab vehicleTab = new VehicleTab("Vehicles", DaoFactory.createVehicleDao()); | package application;
public class Main {
public static void main(String[] args){
RentalService rs = new RentalService(5., 80., new BrazilTaxService());
DaoFactory.setVehiclePath("garage.csv");
DaoFactory.setCarRentalPath("rentals.csv");
InvoiceTab invoiceTab = new InvoiceTab();
VehicleTab vehicleTab = new VehicleTab("Vehicles", DaoFactory.createVehicleDao()); | RentalTab carRentalTab = new RentalTab | 1 | 2023-11-08 15:22:05+00:00 | 4k |
InfantinoAndrea00/polimi-software-engineering-project-2022 | src/main/java/it/polimi/ingsw/server/controller/states/AddPlayer.java | [
{
"identifier": "Server",
"path": "src/main/java/it/polimi/ingsw/server/Server.java",
"snippet": "public class Server {\n public static final int PORT = 5555;\n public static ViewObserver viewObserver;\n public static AtomicBoolean creatingGame;\n public static Game game;\n\n public static void main(String[] args) {\n ServerSocket socket;\n creatingGame = new AtomicBoolean(true);\n viewObserver = new ViewObserver();\n try {\n socket = new ServerSocket(PORT);\n } catch (IOException e) {\n System.out.println(\"cannot open server socket\");\n System.exit(1);\n return;\n }\n\n while (true) {\n try {\n Socket client = socket.accept();\n ClientHandler clientHandler = new ClientHandler(client);\n Thread thread = new Thread(clientHandler, \"Eryantis_Server - \" + client.getInetAddress());\n thread.start();\n } catch (IOException e) {\n System.out.println(\"connection dropped\");\n }\n }\n }\n}"
},
{
"identifier": "GameController",
"path": "src/main/java/it/polimi/ingsw/server/controller/GameController.java",
"snippet": "public class GameController {\n private GameControllerState state;\n\n /**\n * constructor\n */\n public GameController() {\n state = new StartGame();\n }\n\n /**\n * request of the state in which the controller is\n * @return current state\n */\n public GameControllerState getState() {\n return state;\n }\n\n /**\n * set the state of the controller\n * @param state state to be set\n */\n public void setState(GameControllerState state) {\n this.state = state;\n }\n\n /**\n * method that sets the next state of the FSA\n */\n public void nextState() {\n state.nextState(this);\n }\n\n /**\n * method that changes the model through the action of every state\n * @param o1 generic object that will be casted\n * @param o2 generic object that will be casted\n */\n public void changeModel(Object o1, Object o2) {\n state.Action(o1, o2);\n }\n\n}"
},
{
"identifier": "GameControllerState",
"path": "src/main/java/it/polimi/ingsw/server/controller/GameControllerState.java",
"snippet": "public interface GameControllerState {\n void nextState(GameController g);\n void Action(Object o1, Object o2);\n\n}"
},
{
"identifier": "Player",
"path": "src/main/java/it/polimi/ingsw/server/model/Player.java",
"snippet": "public class Player {\n private String name;\n private int id;\n private List<AssistantCard> deck;\n private School school;\n\n /**\n * Check if the deck of a particular player is empty\n * @return true if the deck is empty\n */\n public boolean emptyDeck(){\n return deck.isEmpty();\n }\n\n /**\n * Class Player constructor\n * @param id player Id\n * @param name player nickname\n */\n public Player(int id, String name){\n this.id = id;\n this.name = name;\n deck = new ArrayList<>();\n for (int i = 1; i < 11; i++)\n deck.add(new AssistantCard(i));\n school = new School(id);\n }\n\n /**\n * Request for the player name (nickname)\n * @return player nickname\n */\n public String getName(){\n return name;\n }\n\n /**\n * Request for the player Id\n * @return player Id\n */\n public int getId(){\n return id;\n }\n\n /**\n * Request for the assistant cards list\n * @return deck made of assistant cards\n */\n public List<AssistantCard> getDeck(){\n return deck;\n }\n\n /**\n * Request for a particular assistant card by its speed value\n * @param speedValue related to a particular assistant card\n * @return Assistant card corresponding to that speed value\n */\n public AssistantCard getAssistantCardBySpeedValue(int speedValue){\n for(AssistantCard ac : deck)\n if (ac.getSpeedValue() == speedValue)\n return ac;\n return null;\n }\n\n /**\n * Request for remove an assistant card\n * @param speedValue the value on the top of the assistant card\n */\n public void removeAssistantCard(int speedValue) {\n deck.removeIf(a -> a.getSpeedValue() == speedValue);\n }\n\n /**\n * Request for the current player school\n * @return current player school\n */\n public School getSchool(){\n return school;\n }\n}"
},
{
"identifier": "Team",
"path": "src/main/java/it/polimi/ingsw/server/model/Team.java",
"snippet": "public class Team {\n private List<Integer> players;\n private int id;\n public TowerColor towerColor;\n public int towers;\n\n /**\n * Class Team first constructor (2 or 3 players mode)\n * @param playerId player Id of a player who is part of that team\n * @param id that is the team identifier\n * @param playerNumber player numbers is playing in that game\n */\n public Team(int playerId, int id, int playerNumber){\n this.id = id;\n players = new ArrayList<>();\n towerColor = TowerColor.values()[id];\n players.add(playerId);\n if (playerNumber == 2 || playerNumber == 4)\n this.towers = 8;\n else\n this.towers = 6;\n }\n\n /**\n * Class Team second constructor (4 players mode)\n * @param id that is the team identifier\n */\n public Team(int id){\n this.id = id;\n players = new ArrayList<>();\n towerColor = TowerColor.values()[id];\n this.towers = 8;\n }\n\n /**\n * Request for add a palyer in that team\n * @param playerId of the new player to add\n */\n public void addPlayer(int playerId){\n players.add(playerId);\n }\n\n /**\n * Request for the list of the players in that team\n * @return players of that team\n */\n public List<Integer> getPlayers(){\n return players;\n }\n\n /**\n * Request for the team id\n * @return team id\n */\n public int getId(){\n return id;\n }\n\n /**\n * Check if all towers are placed\n * @return true if all towers of that team have been placed\n */\n public boolean allTowersPlaced(){\n return this.towers == 0;\n }\n}"
},
{
"identifier": "ExpertPlayer",
"path": "src/main/java/it/polimi/ingsw/server/model/expert/ExpertPlayer.java",
"snippet": "public class ExpertPlayer extends Player {\n private int coins;\n\n /**\n * Request for the coins held by that expert player\n * @return coins held by that player\n */\n public int getCoins(){\n return coins;\n }\n\n /**\n * Request to add a coin to that expert player\n */\n public void addCoin(){\n this.coins++;\n }\n\n /**\n * Request to remove coins from that expert player\n * @param numberOfCoins that represent coins held by that player\n */\n public void removeCoins(int numberOfCoins){\n this.coins -= numberOfCoins;\n }\n\n /**\n * Class ExpertPlayer constructor\n * @param id that is the expert player Id\n * @param name that is the expert player nickname\n */\n public ExpertPlayer(int id, String name){\n super(id, name);\n coins = 1;\n }\n}"
}
] | import it.polimi.ingsw.server.Server;
import it.polimi.ingsw.server.controller.GameController;
import it.polimi.ingsw.server.controller.GameControllerState;
import it.polimi.ingsw.server.model.Player;
import it.polimi.ingsw.server.model.Team;
import it.polimi.ingsw.server.model.expert.ExpertPlayer; | 1,964 | package it.polimi.ingsw.server.controller.states;
public class AddPlayer implements GameControllerState {
@Override
public void nextState(GameController g) { | package it.polimi.ingsw.server.controller.states;
public class AddPlayer implements GameControllerState {
@Override
public void nextState(GameController g) { | if(Server.game.getPlayerNumber() == 2 || Server.game.getPlayerNumber() == 3) | 0 | 2023-11-06 00:50:18+00:00 | 4k |
Space-shooter-III/game | game/src/main/java/com/github/spaceshooteriii/game/state/GameState.java | [
{
"identifier": "Drawable",
"path": "game/src/main/java/com/github/spaceshooteriii/game/Drawable.java",
"snippet": "public interface Drawable {\n\n public void draw(Graphics2D g2d);\n\n}"
},
{
"identifier": "Updatable",
"path": "game/src/main/java/com/github/spaceshooteriii/game/Updatable.java",
"snippet": "public interface Updatable {\n\n public void update();\n\n}"
},
{
"identifier": "GameStateClassicManager",
"path": "game/src/main/java/com/github/spaceshooteriii/game/state/data/GameStateClassicManager.java",
"snippet": "public class GameStateClassicManager extends GameStateModeManager {\n\n private @Getter EntityHandler entityHandler;\n\n @Override\n public void draw(Graphics2D g2d) {\n this.entityHandler.draw(g2d);\n }\n\n @Override\n public void update() {\n this.entityHandler.update();\n }\n\n @Override\n public String save() {\n return \"{}\";\n }\n\n @Override\n public void load(String data) {}\n\n @Override\n public void init() {\n this.entityHandler = new EntityHandler();\n this.entityHandler.add(new Player((float) Game.WIDTH / 2 - 32, (float) Game.WIDTH / 2 - 32, 64, 64));\n }\n\n @Override\n public void keyTyped(KeyEvent e) {\n\n }\n\n @Override\n public void keyPressed(KeyEvent e) {\n\n }\n\n @Override\n public void keyReleased(KeyEvent e) {\n\n }\n\n @Override\n public void mouseClicked(MouseEvent e) {\n\n }\n\n @Override\n public void mousePressed(MouseEvent e) {\n\n }\n\n @Override\n public void mouseReleased(MouseEvent e) {\n // ! TESTING CODE START\n\n Game.getState().switchMode(GameMode.HOME_SCREEN);\n\n // ! TESTING CODE END\n }\n\n @Override\n public void mouseEntered(MouseEvent e) {\n\n }\n\n @Override\n public void mouseExited(MouseEvent e) {\n\n }\n\n @Override\n public void mouseDragged(MouseEvent e) {\n\n }\n\n @Override\n public void mouseMoved(MouseEvent e) {\n\n }\n\n @Override\n public void mouseWheelMoved(MouseWheelEvent e) {\n\n }\n}"
},
{
"identifier": "GameStateHomeManager",
"path": "game/src/main/java/com/github/spaceshooteriii/game/state/data/GameStateHomeManager.java",
"snippet": "public class GameStateHomeManager extends GameStateModeManager {\n\n private BufferedImage skyImage;\n private BufferedImage titleImage;\n private BufferedImage playButtonImage;\n private BufferedImage activePlayButtonImage;\n\n private boolean playButtonActive;\n\n @Override\n public void draw(Graphics2D g2d) {\n\n // Draw background\n\n int x = 0;\n int y = 0;\n final int size = 64;\n\n for (int i = 0; i < Math.ceil((double) Game.HEIGHT / size) + 1; i++) {\n for (int j = 0; j < Math.ceil((double) Game.HEIGHT / size) + 1; j++) {\n g2d.drawImage(this.skyImage, x, y, size, size, null);\n x += size;\n }\n y += size;\n x = 0;\n }\n\n // Draw title\n\n g2d.drawImage(this.titleImage, ((Game.WIDTH / 2) - (96 * 6) / 2), 16, 96 * 6, 32 * 6, null);\n\n // Draw buttons\n\n if (this.playButtonActive) {\n g2d.drawImage(this.activePlayButtonImage, ((Game.WIDTH / 2) - (64 * 4) / 2), Game.HEIGHT / 3 * 2 - 16 * 4, 64 * 4, 16 * 4, null);\n } else {\n g2d.drawImage(this.playButtonImage, ((Game.WIDTH / 2) - (64 * 4) / 2), Game.HEIGHT / 3 * 2 - 16 * 4, 64 * 4, 16 * 4, null);\n }\n\n }\n\n @Override\n public void update() {\n\n }\n\n @Override\n public String save() {\n return null;\n }\n\n @Override\n public void load(String data) {\n\n }\n\n @Override\n public void init() {\n this.skyImage = Game.TEXTRA_ALICE.getImageFrom(0, 0, 16, 16);\n this.titleImage = Game.TEXTRA_ALICE.getImageFrom(16, 0, 96, 32);\n this.playButtonImage = Game.TEXTRA_ALICE.getImageFrom(112, 0, 64, 16);\n this.activePlayButtonImage = Game.TEXTRA_ALICE.getImageFrom(112, 16, 64, 16);\n\n this.playButtonActive = false;\n\n }\n\n @Override\n public void keyTyped(KeyEvent e) {\n\n }\n\n @Override\n public void keyPressed(KeyEvent e) {\n\n }\n\n @Override\n public void keyReleased(KeyEvent e) {\n\n }\n\n @Override\n public void mouseClicked(MouseEvent e) {\n\n }\n\n @Override\n public void mousePressed(MouseEvent e) {\n\n }\n\n @Override\n public void mouseReleased(MouseEvent e) {\n Rectangle playButtonBox = new Rectangle(((Game.WIDTH / 2) - (64 * 4) / 2), Game.HEIGHT / 3 * 2 - 16 * 4, 64 * 4, 16 * 4);\n\n if (playButtonBox.contains(e.getX(), e.getY())) {\n Game.getState().switchMode(GameMode.PLAYING_CLASSIC);\n }\n\n }\n\n @Override\n public void mouseEntered(MouseEvent e) {\n\n }\n\n @Override\n public void mouseExited(MouseEvent e) {\n\n }\n\n @Override\n public void mouseDragged(MouseEvent e) {\n\n }\n\n @Override\n public void mouseMoved(MouseEvent e) {\n Rectangle playButtonBox = new Rectangle(((Game.WIDTH / 2) - (64 * 4) / 2), Game.HEIGHT / 3 * 2 - 16 * 4, 64 * 4, 16 * 4);\n\n this.playButtonActive = playButtonBox.contains(e.getX(), e.getY());\n\n }\n\n @Override\n public void mouseWheelMoved(MouseWheelEvent e) {\n\n }\n}"
},
{
"identifier": "GameStateLoadingManager",
"path": "game/src/main/java/com/github/spaceshooteriii/game/state/data/GameStateLoadingManager.java",
"snippet": "public class GameStateLoadingManager extends GameStateModeManager {\n\n private static Logger LOGGER = LogManager.getLogger(\"GameStateLoadingManager\");\n\n private class LoadingThread implements Runnable {\n private @Getter boolean loading;\n\n private static Logger LOGGER = LogManager.getLogger(\"LoadingThread\");\n\n public LoadingThread() {\n this.loading = true;\n }\n\n @Override\n public void run() {\n LoadingThread.LOGGER.info(\"Loading all assets\");\n\n Game.TEXTRA_ALICE_LOADER = new BufferedImageLoader(\"/assets/images/textra-alice.png\");\n Game.TEXTRA_ALICE = new TextraAlice(Game.TEXTRA_ALICE_LOADER.getImage());\n\n GameStateLoadingManager.LOGGER.info(\"Loaded textra-alice\");\n\n this.loading = false;\n LoadingThread.LOGGER.info(\"Loaded all assets\");\n }\n }\n\n private LoadingThread loadingThread;\n\n @Override\n public void draw(Graphics2D g2d) {\n\n // Draw background\n\n g2d.setColor(new Color(0xf74040));\n g2d.fillRect(0, 0, Game.WIDTH, Game.HEIGHT);\n\n g2d.setFont(Game.GAME_FONT.deriveFont(Font.PLAIN, 50f));\n g2d.setColor(new Color(0xffffff));\n g2d.drawString(\"Loading...\", Game.WIDTH / 2 - 100, Game.HEIGHT / 2);\n g2d.setFont(Game.GAME_FONT.deriveFont(Font.PLAIN, 25f));\n g2d.drawString(\"This should be fast\", Game.WIDTH / 2 - 100, Game.HEIGHT / 2 + 50);\n\n }\n\n @Override\n public void update() {\n\n if (!this.loadingThread.isLoading()) {\n Game.getState().switchMode(GameMode.HOME_SCREEN);\n }\n\n }\n\n @Override\n public void init() {\n\n try {\n Game.GAME_FONT = Font.createFont(Font.TRUETYPE_FONT, this.getClass().getResourceAsStream(\"/assets/fonts/Roboto-Regular.ttf\"));\n } catch (Exception e) {\n GameStateLoadingManager.LOGGER.error(\"Cannot load Roboto font failed with error: {}\", \"/assets/fonts/Roboto-Regular.ttf\");\n }\n\n GameStateLoadingManager.LOGGER.info(\"Loaded Roboto font\");\n\n this.loadingThread = new LoadingThread();\n\n Thread loaddingThread = new Thread(loadingThread);\n\n loaddingThread.setDaemon(false);\n loaddingThread.setName(\"loading-thread\");\n\n loaddingThread.start();\n\n }\n\n @Override\n public String save() {\n return null;\n }\n\n @Override\n public void load(String data) {\n\n }\n\n @Override\n public void keyTyped(KeyEvent e) {\n\n }\n\n @Override\n public void keyPressed(KeyEvent e) {\n\n }\n\n @Override\n public void keyReleased(KeyEvent e) {\n\n }\n\n @Override\n public void mouseClicked(MouseEvent e) {\n\n }\n\n @Override\n public void mousePressed(MouseEvent e) {\n\n }\n\n @Override\n public void mouseReleased(MouseEvent e) {\n\n }\n\n @Override\n public void mouseEntered(MouseEvent e) {\n\n }\n\n @Override\n public void mouseExited(MouseEvent e) {\n\n }\n\n @Override\n public void mouseDragged(MouseEvent e) {\n\n }\n\n @Override\n public void mouseMoved(MouseEvent e) {\n\n }\n\n @Override\n public void mouseWheelMoved(MouseWheelEvent e) {\n\n }\n}"
}
] | import com.github.spaceshooteriii.game.Drawable;
import com.github.spaceshooteriii.game.Updatable;
import com.github.spaceshooteriii.game.state.data.GameStateClassicManager;
import com.github.spaceshooteriii.game.state.data.GameStateHomeManager;
import com.github.spaceshooteriii.game.state.data.GameStateLoadingManager;
import lombok.Getter;
import lombok.NonNull;
import lombok.Setter;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.awt.Graphics2D; | 2,837 | package com.github.spaceshooteriii.game.state;
public class GameState implements Drawable, Updatable {
private @Getter @Setter @NonNull GameMode mode;
private @Getter @Setter @NonNull GameStateModeManager gameStateModeManager;
private static Logger LOGGER = LogManager.getLogger("GameState");
public GameState() {
this.mode = GameMode.LOADING_SCREEN;
this.gameStateModeManager = new GameStateLoadingManager();
GameState.LOGGER.info("Running init for game mode: {}", this.mode);
this.gameStateModeManager.init();
}
public void switchMode(GameMode mode) {
GameState.LOGGER.info("Switching game modes: {}", mode);
switch (mode) {
case HOME_SCREEN:
this.gameStateModeManager = new GameStateHomeManager();
break;
case PLAYING_CLASSIC: | package com.github.spaceshooteriii.game.state;
public class GameState implements Drawable, Updatable {
private @Getter @Setter @NonNull GameMode mode;
private @Getter @Setter @NonNull GameStateModeManager gameStateModeManager;
private static Logger LOGGER = LogManager.getLogger("GameState");
public GameState() {
this.mode = GameMode.LOADING_SCREEN;
this.gameStateModeManager = new GameStateLoadingManager();
GameState.LOGGER.info("Running init for game mode: {}", this.mode);
this.gameStateModeManager.init();
}
public void switchMode(GameMode mode) {
GameState.LOGGER.info("Switching game modes: {}", mode);
switch (mode) {
case HOME_SCREEN:
this.gameStateModeManager = new GameStateHomeManager();
break;
case PLAYING_CLASSIC: | this.gameStateModeManager = new GameStateClassicManager(); | 2 | 2023-11-03 11:18:00+00:00 | 4k |
conductor-oss/conductor | awssqs-event-queue/src/main/java/com/netflix/conductor/sqs/config/SQSEventQueueProvider.java | [
{
"identifier": "EventQueueProvider",
"path": "core/src/main/java/com/netflix/conductor/core/events/EventQueueProvider.java",
"snippet": "public interface EventQueueProvider {\n\n String getQueueType();\n\n /**\n * Creates or reads the {@link ObservableQueue} for the given <code>queueURI</code>.\n *\n * @param queueURI The URI of the queue.\n * @return The {@link ObservableQueue} implementation for the <code>queueURI</code>.\n * @throws IllegalArgumentException thrown when an {@link ObservableQueue} can not be created\n * for the <code>queueURI</code>.\n */\n @NonNull\n ObservableQueue getQueue(String queueURI) throws IllegalArgumentException;\n}"
},
{
"identifier": "ObservableQueue",
"path": "core/src/main/java/com/netflix/conductor/core/events/queue/ObservableQueue.java",
"snippet": "public interface ObservableQueue extends Lifecycle {\n\n /**\n * @return An observable for the given queue\n */\n Observable<Message> observe();\n\n /**\n * @return Type of the queue\n */\n String getType();\n\n /**\n * @return Name of the queue\n */\n String getName();\n\n /**\n * @return URI identifier for the queue.\n */\n String getURI();\n\n /**\n * @param messages to be ack'ed\n * @return the id of the ones which could not be ack'ed\n */\n List<String> ack(List<Message> messages);\n\n /**\n * @param messages to be Nack'ed\n */\n default void nack(List<Message> messages) {}\n\n /**\n * @param messages Messages to be published\n */\n void publish(List<Message> messages);\n\n /**\n * Used to determine if the queue supports unack/visibility timeout such that the messages will\n * re-appear on the queue after a specific period and are available to be picked up again and\n * retried.\n *\n * @return - false if the queue message need not be re-published to the queue for retriability -\n * true if the message must be re-published to the queue for retriability\n */\n default boolean rePublishIfNoAck() {\n return false;\n }\n\n /**\n * Extend the lease of the unacknowledged message for longer period.\n *\n * @param message Message for which the timeout has to be changed\n * @param unackTimeout timeout in milliseconds for which the unack lease should be extended.\n * (replaces the current value with this value)\n */\n void setUnackTimeout(Message message, long unackTimeout);\n\n /**\n * @return Size of the queue - no. messages pending. Note: Depending upon the implementation,\n * this can be an approximation\n */\n long size();\n\n /** Used to close queue instance prior to remove from queues */\n default void close() {}\n}"
},
{
"identifier": "SQSObservableQueue",
"path": "awssqs-event-queue/src/main/java/com/netflix/conductor/sqs/eventqueue/SQSObservableQueue.java",
"snippet": "public class SQSObservableQueue implements ObservableQueue {\n\n private static final Logger LOGGER = LoggerFactory.getLogger(SQSObservableQueue.class);\n private static final String QUEUE_TYPE = \"sqs\";\n\n private final String queueName;\n private final int visibilityTimeoutInSeconds;\n private final int batchSize;\n private final AmazonSQS client;\n private final long pollTimeInMS;\n private final String queueURL;\n private final Scheduler scheduler;\n private volatile boolean running;\n\n private SQSObservableQueue(\n String queueName,\n AmazonSQS client,\n int visibilityTimeoutInSeconds,\n int batchSize,\n long pollTimeInMS,\n List<String> accountsToAuthorize,\n Scheduler scheduler) {\n this.queueName = queueName;\n this.client = client;\n this.visibilityTimeoutInSeconds = visibilityTimeoutInSeconds;\n this.batchSize = batchSize;\n this.pollTimeInMS = pollTimeInMS;\n this.queueURL = getOrCreateQueue();\n this.scheduler = scheduler;\n addPolicy(accountsToAuthorize);\n }\n\n @Override\n public Observable<Message> observe() {\n OnSubscribe<Message> subscriber = getOnSubscribe();\n return Observable.create(subscriber);\n }\n\n @Override\n public List<String> ack(List<Message> messages) {\n return delete(messages);\n }\n\n @Override\n public void publish(List<Message> messages) {\n publishMessages(messages);\n }\n\n @Override\n public long size() {\n GetQueueAttributesResult attributes =\n client.getQueueAttributes(\n queueURL, Collections.singletonList(\"ApproximateNumberOfMessages\"));\n String sizeAsStr = attributes.getAttributes().get(\"ApproximateNumberOfMessages\");\n try {\n return Long.parseLong(sizeAsStr);\n } catch (Exception e) {\n return -1;\n }\n }\n\n @Override\n public void setUnackTimeout(Message message, long unackTimeout) {\n int unackTimeoutInSeconds = (int) (unackTimeout / 1000);\n ChangeMessageVisibilityRequest request =\n new ChangeMessageVisibilityRequest(\n queueURL, message.getReceipt(), unackTimeoutInSeconds);\n client.changeMessageVisibility(request);\n }\n\n @Override\n public String getType() {\n return QUEUE_TYPE;\n }\n\n @Override\n public String getName() {\n return queueName;\n }\n\n @Override\n public String getURI() {\n return queueURL;\n }\n\n public long getPollTimeInMS() {\n return pollTimeInMS;\n }\n\n public int getBatchSize() {\n return batchSize;\n }\n\n public int getVisibilityTimeoutInSeconds() {\n return visibilityTimeoutInSeconds;\n }\n\n @Override\n public void start() {\n LOGGER.info(\"Started listening to {}:{}\", getClass().getSimpleName(), queueName);\n running = true;\n }\n\n @Override\n public void stop() {\n LOGGER.info(\"Stopped listening to {}:{}\", getClass().getSimpleName(), queueName);\n running = false;\n }\n\n @Override\n public boolean isRunning() {\n return running;\n }\n\n public static class Builder {\n\n private String queueName;\n private int visibilityTimeout = 30; // seconds\n private int batchSize = 5;\n private long pollTimeInMS = 100;\n private AmazonSQS client;\n private List<String> accountsToAuthorize = new LinkedList<>();\n private Scheduler scheduler;\n\n public Builder withQueueName(String queueName) {\n this.queueName = queueName;\n return this;\n }\n\n /**\n * @param visibilityTimeout Visibility timeout for the message in SECONDS\n * @return builder instance\n */\n public Builder withVisibilityTimeout(int visibilityTimeout) {\n this.visibilityTimeout = visibilityTimeout;\n return this;\n }\n\n public Builder withBatchSize(int batchSize) {\n this.batchSize = batchSize;\n return this;\n }\n\n public Builder withClient(AmazonSQS client) {\n this.client = client;\n return this;\n }\n\n public Builder withPollTimeInMS(long pollTimeInMS) {\n this.pollTimeInMS = pollTimeInMS;\n return this;\n }\n\n public Builder withAccountsToAuthorize(List<String> accountsToAuthorize) {\n this.accountsToAuthorize = accountsToAuthorize;\n return this;\n }\n\n public Builder addAccountToAuthorize(String accountToAuthorize) {\n this.accountsToAuthorize.add(accountToAuthorize);\n return this;\n }\n\n public Builder withScheduler(Scheduler scheduler) {\n this.scheduler = scheduler;\n return this;\n }\n\n public SQSObservableQueue build() {\n return new SQSObservableQueue(\n queueName,\n client,\n visibilityTimeout,\n batchSize,\n pollTimeInMS,\n accountsToAuthorize,\n scheduler);\n }\n }\n\n // Private methods\n String getOrCreateQueue() {\n List<String> queueUrls = listQueues(queueName);\n if (queueUrls == null || queueUrls.isEmpty()) {\n CreateQueueRequest createQueueRequest =\n new CreateQueueRequest().withQueueName(queueName);\n CreateQueueResult result = client.createQueue(createQueueRequest);\n return result.getQueueUrl();\n } else {\n return queueUrls.get(0);\n }\n }\n\n private String getQueueARN() {\n GetQueueAttributesResult response =\n client.getQueueAttributes(queueURL, Collections.singletonList(\"QueueArn\"));\n return response.getAttributes().get(\"QueueArn\");\n }\n\n private void addPolicy(List<String> accountsToAuthorize) {\n if (accountsToAuthorize == null || accountsToAuthorize.isEmpty()) {\n LOGGER.info(\"No additional security policies attached for the queue \" + queueName);\n return;\n }\n LOGGER.info(\"Authorizing \" + accountsToAuthorize + \" to the queue \" + queueName);\n Map<String, String> attributes = new HashMap<>();\n attributes.put(\"Policy\", getPolicy(accountsToAuthorize));\n SetQueueAttributesResult result = client.setQueueAttributes(queueURL, attributes);\n LOGGER.info(\"policy attachment result: \" + result);\n LOGGER.info(\n \"policy attachment result: status=\"\n + result.getSdkHttpMetadata().getHttpStatusCode());\n }\n\n private String getPolicy(List<String> accountIds) {\n Policy policy = new Policy(\"AuthorizedWorkerAccessPolicy\");\n Statement stmt = new Statement(Effect.Allow);\n Action action = SQSActions.SendMessage;\n stmt.getActions().add(action);\n stmt.setResources(new LinkedList<>());\n for (String accountId : accountIds) {\n Principal principal = new Principal(accountId);\n stmt.getPrincipals().add(principal);\n }\n stmt.getResources().add(new Resource(getQueueARN()));\n policy.getStatements().add(stmt);\n return policy.toJson();\n }\n\n private List<String> listQueues(String queueName) {\n ListQueuesRequest listQueuesRequest =\n new ListQueuesRequest().withQueueNamePrefix(queueName);\n ListQueuesResult resultList = client.listQueues(listQueuesRequest);\n return resultList.getQueueUrls().stream()\n .filter(queueUrl -> queueUrl.contains(queueName))\n .collect(Collectors.toList());\n }\n\n private void publishMessages(List<Message> messages) {\n LOGGER.debug(\"Sending {} messages to the SQS queue: {}\", messages.size(), queueName);\n SendMessageBatchRequest batch = new SendMessageBatchRequest(queueURL);\n messages.forEach(\n msg -> {\n SendMessageBatchRequestEntry sendr =\n new SendMessageBatchRequestEntry(msg.getId(), msg.getPayload());\n batch.getEntries().add(sendr);\n });\n LOGGER.debug(\"sending {} messages in batch\", batch.getEntries().size());\n SendMessageBatchResult result = client.sendMessageBatch(batch);\n LOGGER.debug(\"send result: {} for SQS queue: {}\", result.getFailed().toString(), queueName);\n }\n\n List<Message> receiveMessages() {\n try {\n ReceiveMessageRequest receiveMessageRequest =\n new ReceiveMessageRequest()\n .withQueueUrl(queueURL)\n .withVisibilityTimeout(visibilityTimeoutInSeconds)\n .withMaxNumberOfMessages(batchSize);\n\n ReceiveMessageResult result = client.receiveMessage(receiveMessageRequest);\n\n List<Message> messages =\n result.getMessages().stream()\n .map(\n msg ->\n new Message(\n msg.getMessageId(),\n msg.getBody(),\n msg.getReceiptHandle()))\n .collect(Collectors.toList());\n Monitors.recordEventQueueMessagesProcessed(QUEUE_TYPE, this.queueName, messages.size());\n return messages;\n } catch (Exception e) {\n LOGGER.error(\"Exception while getting messages from SQS\", e);\n Monitors.recordObservableQMessageReceivedErrors(QUEUE_TYPE);\n }\n return new ArrayList<>();\n }\n\n OnSubscribe<Message> getOnSubscribe() {\n return subscriber -> {\n Observable<Long> interval = Observable.interval(pollTimeInMS, TimeUnit.MILLISECONDS);\n interval.flatMap(\n (Long x) -> {\n if (!isRunning()) {\n LOGGER.debug(\n \"Component stopped, skip listening for messages from SQS\");\n return Observable.from(Collections.emptyList());\n }\n List<Message> messages = receiveMessages();\n return Observable.from(messages);\n })\n .subscribe(subscriber::onNext, subscriber::onError);\n };\n }\n\n private List<String> delete(List<Message> messages) {\n if (messages == null || messages.isEmpty()) {\n return null;\n }\n\n DeleteMessageBatchRequest batch = new DeleteMessageBatchRequest().withQueueUrl(queueURL);\n List<DeleteMessageBatchRequestEntry> entries = batch.getEntries();\n\n messages.forEach(\n m ->\n entries.add(\n new DeleteMessageBatchRequestEntry()\n .withId(m.getId())\n .withReceiptHandle(m.getReceipt())));\n\n DeleteMessageBatchResult result = client.deleteMessageBatch(batch);\n List<String> failures =\n result.getFailed().stream()\n .map(BatchResultErrorEntry::getId)\n .collect(Collectors.toList());\n LOGGER.debug(\"Failed to delete messages from queue: {}: {}\", queueName, failures);\n return failures;\n }\n}"
}
] | import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.springframework.lang.NonNull;
import com.netflix.conductor.core.events.EventQueueProvider;
import com.netflix.conductor.core.events.queue.ObservableQueue;
import com.netflix.conductor.sqs.eventqueue.SQSObservableQueue;
import com.amazonaws.services.sqs.AmazonSQS;
import rx.Scheduler; | 3,571 | /*
* Copyright 2022 Conductor Authors.
* <p>
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.netflix.conductor.sqs.config;
public class SQSEventQueueProvider implements EventQueueProvider {
private final Map<String, ObservableQueue> queues = new ConcurrentHashMap<>();
private final AmazonSQS client;
private final int batchSize;
private final long pollTimeInMS;
private final int visibilityTimeoutInSeconds;
private final Scheduler scheduler;
public SQSEventQueueProvider(
AmazonSQS client, SQSEventQueueProperties properties, Scheduler scheduler) {
this.client = client;
this.batchSize = properties.getBatchSize();
this.pollTimeInMS = properties.getPollTimeDuration().toMillis();
this.visibilityTimeoutInSeconds = (int) properties.getVisibilityTimeout().getSeconds();
this.scheduler = scheduler;
}
@Override
public String getQueueType() {
return "sqs";
}
@Override
@NonNull
public ObservableQueue getQueue(String queueURI) {
return queues.computeIfAbsent(
queueURI,
q -> | /*
* Copyright 2022 Conductor Authors.
* <p>
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.netflix.conductor.sqs.config;
public class SQSEventQueueProvider implements EventQueueProvider {
private final Map<String, ObservableQueue> queues = new ConcurrentHashMap<>();
private final AmazonSQS client;
private final int batchSize;
private final long pollTimeInMS;
private final int visibilityTimeoutInSeconds;
private final Scheduler scheduler;
public SQSEventQueueProvider(
AmazonSQS client, SQSEventQueueProperties properties, Scheduler scheduler) {
this.client = client;
this.batchSize = properties.getBatchSize();
this.pollTimeInMS = properties.getPollTimeDuration().toMillis();
this.visibilityTimeoutInSeconds = (int) properties.getVisibilityTimeout().getSeconds();
this.scheduler = scheduler;
}
@Override
public String getQueueType() {
return "sqs";
}
@Override
@NonNull
public ObservableQueue getQueue(String queueURI) {
return queues.computeIfAbsent(
queueURI,
q -> | new SQSObservableQueue.Builder() | 2 | 2023-12-08 06:06:09+00:00 | 4k |
10cks/fofaEX | src/main/java/plugins/FofaHack.java | [
{
"identifier": "SelectedCellBorderHighlighter",
"path": "src/main/java/tableInit/SelectedCellBorderHighlighter.java",
"snippet": "public class SelectedCellBorderHighlighter extends DefaultTableCellRenderer {\n private static final Border SELECTED_BORDER = BorderFactory.createLineBorder(new Color(201, 79, 79), 3);\n private static final Border UNSELECTED_BORDER = BorderFactory.createEmptyBorder(1, 1, 1, 1);\n\n @Override\n public Component getTableCellRendererComponent(JTable table, Object value,\n boolean isSelected, boolean hasFocus,\n int row, int column) {\n super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);\n if (table.getSelectedRow() == row && table.getSelectedColumn() == column) {\n setBorder(SELECTED_BORDER);\n } else {\n setBorder(UNSELECTED_BORDER);\n }\n return this;\n }\n}"
},
{
"identifier": "adjustColumnWidths",
"path": "src/main/java/tableInit/GetjTableHeader.java",
"snippet": "public static void adjustColumnWidths(JTable table) {\n TableColumnModel columnModel = table.getColumnModel();\n for (int column = 0; column < table.getColumnCount(); column++) {\n int width = 15; // Min width\n for (int row = 0; row < table.getRowCount(); row++) {\n TableCellRenderer renderer = table.getCellRenderer(row, column);\n Component comp = table.prepareRenderer(renderer, row, column);\n width = Math.max(comp.getPreferredSize().width + 1, width);\n }\n if (width > 300)\n width = 300;\n columnModel.getColumn(column).setPreferredWidth(width);\n }\n}"
},
{
"identifier": "getjTableHeader",
"path": "src/main/java/tableInit/GetjTableHeader.java",
"snippet": "public static JTableHeader getjTableHeader(JTable table) {\n JTableHeader header = table.getTableHeader();\n // 自定义列标题的渲染器\n header.setDefaultRenderer(new DefaultTableCellRenderer() {\n @Override\n public Component getTableCellRendererComponent(\n JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {\n\n // 设置渲染器返回的组件类型为JLabel\n JLabel headerLabel = (JLabel) super.getTableCellRendererComponent(\n table, value, isSelected, hasFocus, row, column);\n\n // 检查排序键是否与当前列匹配\n if(table.getRowSorter() != null) {\n java.util.List<? extends RowSorter.SortKey> sortKeys = table.getRowSorter().getSortKeys();\n\n if (sortKeys.size() > 0 && sortKeys.get(0).getColumn() == table.convertColumnIndexToView(column)) {\n headerLabel.setFont(headerLabel.getFont().deriveFont(Font.BOLD));\n headerLabel.setForeground(Color.CYAN);\n } else {\n headerLabel.setFont(headerLabel.getFont().deriveFont(Font.PLAIN));\n headerLabel.setForeground(Color.WHITE);\n }\n }\n\n // 设置背景色为灰色\n headerLabel.setBackground(Color.GRAY);\n // 设置文字居中\n headerLabel.setHorizontalAlignment(JLabel.CENTER);\n // 设置标题加粗和大小\n headerLabel.setFont(new Font(headerLabel.getFont().getFamily(), Font.BOLD, 15));\n // 设置边框,其中颜色设置为白色\n headerLabel.setBorder(BorderFactory.createMatteBorder(0, 0, 0, 1, Color.WHITE));\n // 设置数据文字大小\n table.setFont(new Font(\"Serif\", Font.PLAIN, 15)); // 设置数据单元格的字体和大小\n\n return headerLabel;\n }\n });\n return header;\n}"
}
] | import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Map;
import com.google.gson.*;
import java.util.Vector;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import tableInit.SelectedCellBorderHighlighter;
import static tableInit.GetjTableHeader.adjustColumnWidths;
import static tableInit.GetjTableHeader.getjTableHeader; | 2,814 | File dataDirectory = new File("./plugins/fofahack/data");
// 检查该路径表示的目录是否存在
if (!dataDirectory.exists()) {
// 不存在,则尝试创建该目录
boolean wasSuccessful = dataDirectory.mkdirs(); // 使用 mkdirs 而不是 mkdir 以创建任何必需的父目录
if (wasSuccessful) {
System.out.println("[+] FofaHack: The 'data' directory was created successfully.");
} else {
System.out.println("Failed to create the 'data' directory.");
}
}
// 构建完整的命令
String command = String.format("%s -k %s -on %s -e %s -l %s -o json", path, searchStr, outputname, endcount, level);
ProcessBuilder builder = new ProcessBuilder(command.split("\\s+"));
builder.redirectErrorStream(true); // 合并标准错误和标准输出
process = builder.start();
writer = new PrintWriter(new OutputStreamWriter(process.getOutputStream(), StandardCharsets.UTF_8), true);
// 处理输出流
Thread outputThread = new Thread(() -> {
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8))) {
String line;
while ((line = reader.readLine()) != null) {
final String lineCopy = line;
SwingUtilities.invokeLater(() -> {
resultArea.append(lineCopy + "\n");
});
}
} catch (IOException e) {
SwingUtilities.invokeLater(() -> {
resultArea.append("Error reading output: " + e.getMessage() + "\n");
});
} finally {
try {
process.waitFor();
} catch (InterruptedException ex) {
SwingUtilities.invokeLater(() -> {
resultArea.append("Process was interrupted: " + ex.getMessage() + "\n");
});
}
SwingUtilities.invokeLater(() -> {
resultArea.append("\n程序运行结束\n");
try {
if (checkMakeFile()) {
System.out.println("[*] FofaHack running success.");
// 导出表格
JButton exportButton = new JButton("Export to Excel");
exportButton.setFocusPainted(false); // 添加这一行来取消焦点边框的绘制
exportButton.setFocusable(false); // 禁止了按钮获取焦点,因此按钮不会在被点击后显示为"激活"或"选中"的状态
if (!exportButtonAdded) {
exportPanel.add(exportButton);
exportButtonAdded = true;
}
exportButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// 在这里检查 table 是否被初始化
if (table == null) {
JOptionPane.showMessageDialog(null, "表格没有被初始化");
return;
}
// 检查 table 是否有模型和数据
if (table.getModel() == null || table.getModel().getRowCount() <= 0) {
JOptionPane.showMessageDialog(null, "当前无数据");
return;
}
exportTableToExcel(table);
}
});
}else{
JOptionPane.showMessageDialog(null, "读取数据失败", "Error", JOptionPane.ERROR_MESSAGE);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
;
});
}
});
outputThread.start();
} catch (Exception ex) {
resultArea.setText("Error executing command: " + ex.getMessage());
// 在这里弹出“执行失败”的警告窗口
JOptionPane.showMessageDialog(null, "Execution failed", "Error", JOptionPane.ERROR_MESSAGE);
}
}
public static boolean checkMakeFile() throws IOException {
// 从配置文件中读取设置
Properties properties = new Properties();
properties.load(new FileInputStream("./plugins/fofahack/FofaHackSetting.txt"));
String finalname = properties.getProperty("finalname").trim();
finalname = finalname.replace("\"", "");
// 在这里检查 final 文件是否存在
System.out.println(finalname);
File file = new File(finalname);
if (file.exists()) {
loadFileIntoTable(file);
return true;
}
return false;
}
public static void loadFileIntoTable(File file) {
// 重新设置表格头,以便新的渲染器生效
JTableHeader header = getjTableHeader(table);
table.setTableHeader(header);
| package plugins;
public class FofaHack {
public static boolean exportButtonAdded;
private Process process;
public static JPanel panel = new JPanel(); // 主面板
public static JPanel exportPanel = new JPanel(); // 主面板
public static JTable table = new JTable(); // 表格
public static JLabel rowCountLabel = new JLabel();
private PrintWriter writer;
private static JFrame frame; // 使frame成为类的成员变量,以便可以在任意地方访问
public void fofaHack() {
// 创建基础的窗口框架
frame = new JFrame("Fofa Hack");
frame.setSize(800, 600);
frame.setLocationRelativeTo(null); // 居中
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); // 插件关闭主程序不关闭
frame.setLayout(new BorderLayout());
// 输入面板
JPanel panel = new JPanel();
JTextField commandField = new JTextField(50);
JTextField endcountField = new JTextField(10);
JButton executeButton = new JButton("搜索");
JButton chooseFileButton = new JButton("选择程序");
chooseFileButton.setFocusPainted(false);
chooseFileButton.setFocusable(false);
executeButton.setFocusPainted(false); // 添加这一行来取消焦点边框的绘制
executeButton.setFocusable(false); // 禁止了按钮获取焦点,因此按钮不会在被点击后显示为"激活"或"选中"的状态
JTextArea resultArea = new JTextArea(10, 50);
// 设置断行不断字
resultArea.setWrapStyleWord(false);
panel.add(new JLabel("查询语法:"));
panel.add(commandField);
panel.add(new JLabel("查询数量:"));
panel.add(endcountField);
panel.add(executeButton);
//panel.add(chooseFileButton);
// 结果滚动面板
JScrollPane scrollPane = new JScrollPane(resultArea);
resultArea.setEditable(false);
// 添加面板和滚动面板到窗口框架
frame.add(panel, BorderLayout.NORTH);
frame.add(scrollPane, BorderLayout.CENTER);
// 执行按钮点击事件
executeButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// 清空文本区域
resultArea.setText("");
String command = commandField.getText().trim();
String endcount = endcountField.getText().trim();
executeCommand(command, endcount, resultArea);
}
});
// 选择文件按钮事件
chooseFileButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setCurrentDirectory(new File(".\\plugins")); // 设置默认目录
int result = fileChooser.showOpenDialog(frame);
if (result == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
commandField.setText("\"" + selectedFile.getAbsolutePath() + "\""); // 将选定的文件路径放入命令字段
}
}
});
// 显示窗口
frame.setVisible(true);
}
private void executeCommand(String searchStr, String endcount, JTextArea resultArea) {
try {
// 从配置文件中读取设置
Properties properties = new Properties();
properties.load(new FileInputStream("./plugins/fofahack/FofaHackSetting.txt"));
String path = properties.getProperty("Path").replace("\"", ""); // 移除引号
String level = properties.getProperty("level").trim();
String outputname = properties.getProperty("outputname").trim();
// 构建 plugins/data 的文件路径对象
File dataDirectory = new File("./plugins/fofahack/data");
// 检查该路径表示的目录是否存在
if (!dataDirectory.exists()) {
// 不存在,则尝试创建该目录
boolean wasSuccessful = dataDirectory.mkdirs(); // 使用 mkdirs 而不是 mkdir 以创建任何必需的父目录
if (wasSuccessful) {
System.out.println("[+] FofaHack: The 'data' directory was created successfully.");
} else {
System.out.println("Failed to create the 'data' directory.");
}
}
// 构建完整的命令
String command = String.format("%s -k %s -on %s -e %s -l %s -o json", path, searchStr, outputname, endcount, level);
ProcessBuilder builder = new ProcessBuilder(command.split("\\s+"));
builder.redirectErrorStream(true); // 合并标准错误和标准输出
process = builder.start();
writer = new PrintWriter(new OutputStreamWriter(process.getOutputStream(), StandardCharsets.UTF_8), true);
// 处理输出流
Thread outputThread = new Thread(() -> {
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8))) {
String line;
while ((line = reader.readLine()) != null) {
final String lineCopy = line;
SwingUtilities.invokeLater(() -> {
resultArea.append(lineCopy + "\n");
});
}
} catch (IOException e) {
SwingUtilities.invokeLater(() -> {
resultArea.append("Error reading output: " + e.getMessage() + "\n");
});
} finally {
try {
process.waitFor();
} catch (InterruptedException ex) {
SwingUtilities.invokeLater(() -> {
resultArea.append("Process was interrupted: " + ex.getMessage() + "\n");
});
}
SwingUtilities.invokeLater(() -> {
resultArea.append("\n程序运行结束\n");
try {
if (checkMakeFile()) {
System.out.println("[*] FofaHack running success.");
// 导出表格
JButton exportButton = new JButton("Export to Excel");
exportButton.setFocusPainted(false); // 添加这一行来取消焦点边框的绘制
exportButton.setFocusable(false); // 禁止了按钮获取焦点,因此按钮不会在被点击后显示为"激活"或"选中"的状态
if (!exportButtonAdded) {
exportPanel.add(exportButton);
exportButtonAdded = true;
}
exportButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// 在这里检查 table 是否被初始化
if (table == null) {
JOptionPane.showMessageDialog(null, "表格没有被初始化");
return;
}
// 检查 table 是否有模型和数据
if (table.getModel() == null || table.getModel().getRowCount() <= 0) {
JOptionPane.showMessageDialog(null, "当前无数据");
return;
}
exportTableToExcel(table);
}
});
}else{
JOptionPane.showMessageDialog(null, "读取数据失败", "Error", JOptionPane.ERROR_MESSAGE);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
;
});
}
});
outputThread.start();
} catch (Exception ex) {
resultArea.setText("Error executing command: " + ex.getMessage());
// 在这里弹出“执行失败”的警告窗口
JOptionPane.showMessageDialog(null, "Execution failed", "Error", JOptionPane.ERROR_MESSAGE);
}
}
public static boolean checkMakeFile() throws IOException {
// 从配置文件中读取设置
Properties properties = new Properties();
properties.load(new FileInputStream("./plugins/fofahack/FofaHackSetting.txt"));
String finalname = properties.getProperty("finalname").trim();
finalname = finalname.replace("\"", "");
// 在这里检查 final 文件是否存在
System.out.println(finalname);
File file = new File(finalname);
if (file.exists()) {
loadFileIntoTable(file);
return true;
}
return false;
}
public static void loadFileIntoTable(File file) {
// 重新设置表格头,以便新的渲染器生效
JTableHeader header = getjTableHeader(table);
table.setTableHeader(header);
| adjustColumnWidths(table); // 自动调整列宽 | 1 | 2023-12-07 13:46:27+00:00 | 4k |
specmock/specmock | specmock/src/test/java/io/specmock/core/SpringWebIncorrectTest.java | [
{
"identifier": "Example1Request",
"path": "specmock/src/test/java/io/specmock/core/example/Example1Request.java",
"snippet": "public class Example1Request {\n private String stringValue;\n private Integer integerValue;\n private Long longValue;\n private BigDecimal bigDecimalValue;\n\n /**\n * Empty constructor for ExampleRequest.\n */\n public Example1Request() {\n }\n\n /**\n * Constructs an ExampleRequest with specified values.\n *\n * @param stringValue The string value.\n * @param integerValue The integer value.\n * @param longValue The long value.\n * @param bigDecimalValue The BigDecimal value.\n */\n public Example1Request(\n String stringValue,\n Integer integerValue,\n Long longValue,\n BigDecimal bigDecimalValue\n ) {\n this.stringValue = stringValue;\n this.integerValue = integerValue;\n this.longValue = longValue;\n this.bigDecimalValue = bigDecimalValue;\n }\n\n /**\n * Retrieves the string value.\n *\n * @return The string value.\n */\n public String getStringValue() {\n return stringValue;\n }\n\n /**\n * Retrieves the integer value.\n *\n * @return The integer value.\n */\n public Integer getIntegerValue() {\n return integerValue;\n }\n\n /**\n * Retrieves the long value.\n *\n * @return The long value.\n */\n public Long getLongValue() {\n return longValue;\n }\n\n /**\n * Retrieves the BigDecimal value.\n *\n * @return The BigDecimal value.\n */\n public BigDecimal getBigDecimalValue() {\n return bigDecimalValue;\n }\n}"
},
{
"identifier": "Example1Response",
"path": "specmock/src/test/java/io/specmock/core/example/Example1Response.java",
"snippet": "public class Example1Response {\n private String stringValue;\n\n /**\n * Empty constructor for ExampleResponse.\n */\n public Example1Response() {\n }\n\n /**\n * Constructs an ExampleResponse with the specified string value.\n *\n * @param stringValue The string value.\n */\n public Example1Response(String stringValue) {\n this.stringValue = stringValue;\n }\n\n /**\n * Retrieves the string value.\n *\n * @return The string value.\n */\n public String getStringValue() {\n return stringValue;\n }\n\n /**\n * Sets the string value.\n *\n * @param stringValue The string value to set.\n */\n public void setStringValue(String stringValue) {\n this.stringValue = stringValue;\n }\n}"
},
{
"identifier": "Example5Request",
"path": "specmock/src/test/java/io/specmock/core/example/Example5Request.java",
"snippet": "public class Example5Request {\n private String stringValue;\n private Integer integerValue;\n private Long longValue;\n private BigDecimal bigDecimalValue;\n\n /**\n * Empty constructor for ExampleRequest.\n */\n public Example5Request() {\n }\n\n /**\n * Constructs an ExampleRequest with specified values.\n *\n * @param stringValue The string value.\n * @param integerValue The integer value.\n * @param longValue The long value.\n * @param bigDecimalValue The BigDecimal value.\n */\n public Example5Request(\n String stringValue,\n Integer integerValue,\n Long longValue,\n BigDecimal bigDecimalValue\n ) {\n this.stringValue = stringValue;\n this.integerValue = integerValue;\n this.longValue = longValue;\n this.bigDecimalValue = bigDecimalValue;\n }\n\n /**\n * Retrieves the string value.\n *\n * @return The string value.\n */\n public String getStringValue() {\n return stringValue;\n }\n\n /**\n * Retrieves the integer value.\n *\n * @return The integer value.\n */\n public Integer getIntegerValue() {\n return integerValue;\n }\n\n /**\n * Retrieves the long value.\n *\n * @return The long value.\n */\n public Long getLongValue() {\n return longValue;\n }\n\n /**\n * Retrieves the BigDecimal value.\n *\n * @return The BigDecimal value.\n */\n public BigDecimal getBigDecimalValue() {\n return bigDecimalValue;\n }\n}"
},
{
"identifier": "Example5Response",
"path": "specmock/src/test/java/io/specmock/core/example/Example5Response.java",
"snippet": "public class Example5Response {\n private String stringValue;\n\n /**\n * Empty constructor for ExampleResponse.\n */\n public Example5Response() {\n }\n\n /**\n * Constructs an ExampleResponse with the specified string value.\n *\n * @param stringValue The string value.\n */\n public Example5Response(String stringValue) {\n this.stringValue = stringValue;\n }\n\n /**\n * Retrieves the string value.\n *\n * @return The string value.\n */\n public String getStringValue() {\n return stringValue;\n }\n\n /**\n * Sets the string value.\n *\n * @param stringValue The string value to set.\n */\n public void setStringValue(String stringValue) {\n this.stringValue = stringValue;\n }\n}"
},
{
"identifier": "Example6Request",
"path": "specmock/src/test/java/io/specmock/core/example/Example6Request.java",
"snippet": "public class Example6Request {\n private String stringValue;\n private Integer integerValue;\n private Long longValue;\n private BigDecimal bigDecimalValue;\n\n /**\n * Empty constructor for ExampleRequest.\n */\n public Example6Request() {\n }\n\n /**\n * Constructs an ExampleRequest with specified values.\n *\n * @param stringValue The string value.\n * @param integerValue The integer value.\n * @param longValue The long value.\n * @param bigDecimalValue The BigDecimal value.\n */\n public Example6Request(\n String stringValue,\n Integer integerValue,\n Long longValue,\n BigDecimal bigDecimalValue\n ) {\n this.stringValue = stringValue;\n this.integerValue = integerValue;\n this.longValue = longValue;\n this.bigDecimalValue = bigDecimalValue;\n }\n\n /**\n * Retrieves the string value.\n *\n * @return The string value.\n */\n public String getStringValue() {\n return stringValue;\n }\n\n /**\n * Retrieves the integer value.\n *\n * @return The integer value.\n */\n public Integer getIntegerValue() {\n return integerValue;\n }\n\n /**\n * Retrieves the long value.\n *\n * @return The long value.\n */\n public Long getLongValue() {\n return longValue;\n }\n\n /**\n * Retrieves the BigDecimal value.\n *\n * @return The BigDecimal value.\n */\n public BigDecimal getBigDecimalValue() {\n return bigDecimalValue;\n }\n}"
},
{
"identifier": "Example6Response",
"path": "specmock/src/test/java/io/specmock/core/example/Example6Response.java",
"snippet": "public class Example6Response {\n private String stringValue;\n\n /**\n * Empty constructor for ExampleResponse.\n */\n public Example6Response() {\n }\n\n /**\n * Constructs an ExampleResponse with the specified string value.\n *\n * @param stringValue The string value.\n */\n public Example6Response(String stringValue) {\n this.stringValue = stringValue;\n }\n\n /**\n * Retrieves the string value.\n *\n * @return The string value.\n */\n public String getStringValue() {\n return stringValue;\n }\n\n /**\n * Sets the string value.\n *\n * @param stringValue The string value to set.\n */\n public void setStringValue(String stringValue) {\n this.stringValue = stringValue;\n }\n}"
},
{
"identifier": "ExampleApi",
"path": "specmock/src/test/java/io/specmock/core/example/ExampleApi.java",
"snippet": "public interface ExampleApi {\n /**\n * POST request to /example1.\n *\n * @param request The Example1Request object.\n * @return The Example1Response object.\n */\n @RequestMapping(method = RequestMethod.POST, value = \"/example1\",\n consumes = MediaType.APPLICATION_JSON_VALUE)\n Example1Response example1_POST_requestBody(@RequestBody Example1Request request);\n\n /**\n * GET request to /example2.\n *\n * @return The Example2Response object.\n */\n @RequestMapping(method = RequestMethod.GET, value = \"/example2\",\n consumes = MediaType.APPLICATION_JSON_VALUE)\n Example2Response example2_GET_path();\n\n /**\n * GET request to /example3.\n *\n * @param request The Example3Request object.\n * @return The Example3Response object.\n */\n @RequestMapping(method = RequestMethod.PUT, value = \"/example3\",\n consumes = MediaType.APPLICATION_JSON_VALUE)\n Example3Response example3_PUT_requestBody(@RequestBody Example3Request request);\n\n /**\n * POST request to /example4_1 or /example4_2.\n *\n * @param request The Example4Request object.\n * @return The Example4Response object.\n */\n @RequestMapping(method = RequestMethod.POST, value = { \"/example4_1\", \"/example4_2\" },\n consumes = MediaType.APPLICATION_JSON_VALUE)\n Example4Response example4_POST_multiplePathParam(@RequestBody Example4Request request);\n\n /**\n * POST request to /example5.\n *\n * @param request The Example5Request object.\n * @param queryParam1 The first query parameter.\n * @param queryParam2 The second query parameter (annotated).\n * @return The Example5Response object.\n */\n @RequestMapping(method = RequestMethod.POST, path = \"/example5\",\n consumes = MediaType.APPLICATION_JSON_VALUE)\n Example5Response example5_POST_multipleQueryParam(@RequestBody Example5Request request,\n @RequestParam String queryParam1,\n @RequestParam(\"queryParam2_annotate\") String queryParam2);\n\n /**\n * POST request to /example6/{pathParam1}/{pathParam2_annotate}.\n *\n * @param request The Example6Request object.\n * @param pathParam1 The first path parameter.\n * @param pathParam2 The second path parameter (annotated).\n * @return The Example6Response object.\n */\n @RequestMapping(method = RequestMethod.POST, path = \"/example6/{pathParam1}/{pathParam2_annotate}\",\n consumes = MediaType.APPLICATION_JSON_VALUE)\n Example6Response example6_POST_multiplePathParam(@RequestBody Example6Request request,\n @PathVariable String pathParam1,\n @PathVariable(\"pathParam2_annotate\") String pathParam2);\n\n /**\n * PATCH request to /example7.\n *\n * @return The Example7Response object.\n */\n @RequestMapping(method = RequestMethod.PATCH, value = \"/example7\",\n consumes = MediaType.APPLICATION_JSON_VALUE)\n Example7Response example7_Patch_path(@RequestBody Example7Request request);\n\n /**\n * DELETE request to /example8.\n *\n * @return The Example8Response object.\n */\n @RequestMapping(method = RequestMethod.DELETE, value = \"/example8\",\n consumes = MediaType.APPLICATION_JSON_VALUE)\n Example8Response example8_Delete_path();\n}"
}
] | import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.HttpServerErrorException;
import org.springframework.web.client.RestTemplate;
import io.specmock.core.example.Example1Request;
import io.specmock.core.example.Example1Response;
import io.specmock.core.example.Example5Request;
import io.specmock.core.example.Example5Response;
import io.specmock.core.example.Example6Request;
import io.specmock.core.example.Example6Response;
import io.specmock.core.example.ExampleApi; | 3,013 | /*
* Copyright 2023 SpecMock
* (c) 2023 SpecMock Contributors
* SPDX-License-Identifier: Apache-2.0
*
* You may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.specmock.core;
class SpringWebIncorrectTest {
private static final String RESPONSE_VALUE = "SUCCESS";
private HttpSpecServer specServer; | /*
* Copyright 2023 SpecMock
* (c) 2023 SpecMock Contributors
* SPDX-License-Identifier: Apache-2.0
*
* You may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.specmock.core;
class SpringWebIncorrectTest {
private static final String RESPONSE_VALUE = "SUCCESS";
private HttpSpecServer specServer; | private Example1Request example1Request; | 0 | 2023-12-13 10:43:07+00:00 | 4k |
kdhrubo/db2rest | src/main/java/com/homihq/db2rest/rest/read/helper/SelectBuilder.java | [
{
"identifier": "Db2RestConfigProperties",
"path": "src/main/java/com/homihq/db2rest/config/Db2RestConfigProperties.java",
"snippet": "@Getter\n@Setter\n@Configuration\n@ConfigurationProperties(prefix = \"db2rest\")\n@Validated\n@Slf4j\npublic class Db2RestConfigProperties {\n\n private boolean allowSafeDelete;\n\n private List<String> schemas; //TODO validate\n\n private MultiTenancy multiTenancy;\n\n public String [] getSchemas() {\n String[] schemaList = new String[schemas.size()];\n schemas.toArray(schemaList);\n\n return schemaList;\n }\n\n public void verifySchema(String schemaName) {\n\n if(!multiTenancy.isEnabled() && !schemas.contains(schemaName)) {\n log.error(\"Invalid schema found - {}\", schemaName);\n throw new InvalidSchemaException(schemaName);\n }\n }\n\n\n\n}"
},
{
"identifier": "MyBatisTable",
"path": "src/main/java/com/homihq/db2rest/mybatis/MyBatisTable.java",
"snippet": "@Getter\n@Setter\npublic class MyBatisTable extends SqlTable{\n\n String alias;\n String tableName;\n String schemaName;\n\n List<SqlColumn<?>> sqlColumnList;\n\n Table table;\n\n boolean root;\n\n public MyBatisTable(String schemaName, String tableName, Table table) {\n super(tableName);\n this.tableName = tableName;\n this.schemaName = schemaName;\n this.table = table;\n sqlColumnList = new ArrayList<>();\n }\n\n public void addAllColumns() {\n for(Column column : table.getColumns()) addColumn(column);\n }\n\n public void addColumn(Column column) {\n sqlColumnList.add(column(column.getName()));\n }\n\n public void addColumn(String columnName, String alias) {\n sqlColumnList.add(column(columnName).as(alias));\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n\n if (o == null || getClass() != o.getClass()) return false;\n\n MyBatisTable table = (MyBatisTable) o;\n\n return new EqualsBuilder().append(tableName, table.tableName).isEquals();\n }\n\n @Override\n public int hashCode() {\n return new HashCodeBuilder(17, 37).append(tableName).toHashCode();\n }\n}"
},
{
"identifier": "SchemaManager",
"path": "src/main/java/com/homihq/db2rest/schema/SchemaManager.java",
"snippet": "@Slf4j\n@RequiredArgsConstructor\n@Component\npublic final class SchemaManager {\n\n private final DataSource dataSource;\n private final Map<String, Table> tableMap = new ConcurrentHashMap<>();\n private final List<Table> tableList = new ArrayList<>();\n\n @PostConstruct\n public void reload() {\n createSchemaCache();\n }\n\n public void createSchemaCache() {\n\n // Create the options\n final LimitOptionsBuilder limitOptionsBuilder = LimitOptionsBuilder.builder();\n\n final LoadOptionsBuilder loadOptionsBuilder = LoadOptionsBuilder.builder()\n\n // Set what details are required in the schema - this affects the\n // time taken to crawl the schema\n .withSchemaInfoLevel(SchemaInfoLevelBuilder.standard());\n\n final SchemaCrawlerOptions options = SchemaCrawlerOptionsBuilder.newSchemaCrawlerOptions()\n .withLimitOptions(limitOptionsBuilder.toOptions()).withLoadOptions(loadOptionsBuilder.toOptions());\n\n // Get the schema definition\n\n final Catalog catalog = SchemaCrawlerUtility.getCatalog(DatabaseConnectionSources.fromDataSource(dataSource), options);\n\n for (final Schema schema : catalog.getSchemas()) {\n\n for (final Table table : catalog.getTables(schema)) {\n\n String schemaName = getSchemaName(table);\n\n String fullName = schemaName + \".\" + table.getName();\n log.info(\"Full name - {}\", fullName);\n tableMap.put(fullName, table);\n tableList.add(table);\n\n }\n }\n\n log.info(\"tableMap - {}\", tableMap);\n\n }\n\n private String getSchemaName(Table table) {\n //TODO - move DB specific handling to Dialect class\n String schemaName = table.getSchema().getCatalogName();\n\n if(StringUtils.isBlank(schemaName)) {\n //POSTGRESQL\n\n schemaName = table.getSchema().getName();\n }\n return schemaName;\n }\n\n public Optional<Table> getTable(String schemaName, String tableName) {\n log.info(\"Get table - {}.{}\", schemaName, tableName);\n Table table = tableMap.get(schemaName + \".\" + tableName);\n log.info(\"Get table - {}\", table);\n return Optional.of(table);\n }\n\n public Column getColumn(String schemaName, String tableName, String columnName) {\n\n Table table = getTable(schemaName, tableName).orElseThrow(() -> new InvalidTableException(tableName));\n\n return table.getColumns().stream().filter(c -> StringUtils.equalsIgnoreCase(columnName, c.getName()))\n .findFirst().orElseThrow(() -> new InvalidColumnException(tableName, columnName));\n }\n\n public List<ForeignKey> getForeignKeysBetween(String schemaName, String rootTable, String childTable) {\n\n //1. first locate table in the cache\n Table table = getTable(schemaName, rootTable).orElseThrow(() -> new InvalidTableException(rootTable));\n\n //2. if foreign keys = null, look for join table option\n return table.getImportedForeignKeys().stream()\n .filter(fk -> StringUtils.equalsIgnoreCase(fk.getSchema().getCatalogName(), schemaName)\n && StringUtils.equalsIgnoreCase(fk.getReferencedTable().getName(), childTable)).toList();\n }\n\n public List<MyBatisTable> findTables(String tableName) {\n return tableList.stream()\n .filter(t -> StringUtils.equalsIgnoreCase(t.getName(), tableName))\n .toList()\n .stream()\n .map(t ->\n new MyBatisTable(\n getSchemaName(t), tableName, t))\n .toList();\n\n }\n\n public MyBatisTable findTable(String schemaName, String tableName, int counter) {\n\n Table table = getTable(schemaName, tableName).orElseThrow(() -> new InvalidTableException(tableName));\n\n MyBatisTable myBatisTable = new MyBatisTable(schemaName, tableName, table);\n myBatisTable.setAlias(getAlias(counter, \"\"));\n\n return myBatisTable;\n }\n}"
}
] | import com.homihq.db2rest.config.Db2RestConfigProperties;
import com.homihq.db2rest.mybatis.MyBatisTable;
import com.homihq.db2rest.schema.SchemaManager;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List; | 1,643 | package com.homihq.db2rest.rest.read.helper;
@Component
@Slf4j
@RequiredArgsConstructor
public class SelectBuilder{
| package com.homihq.db2rest.rest.read.helper;
@Component
@Slf4j
@RequiredArgsConstructor
public class SelectBuilder{
| private final SchemaManager schemaManager; | 2 | 2023-12-14 19:26:05+00:00 | 4k |
kaifangqian/open-sign | src/main/java/com/resrun/service/pdf/CalculatePositionService.java | [
{
"identifier": "RealPositionProperty",
"path": "src/main/java/com/resrun/service/pojo/RealPositionProperty.java",
"snippet": "@AllArgsConstructor\n@NoArgsConstructor\n@Data\npublic class RealPositionProperty implements Serializable {\n\n\n private static final long serialVersionUID = 8586984409612483553L;\n\n /** 签章左下角x坐标 */\n private float startx;\n\n /** 签章左下角y坐标*/\n private float starty;\n\n /** 签章右上角x坐标*/\n private float endx;\n\n /** 签章右上角x坐标*/\n private float endy;\n\n private int pageNum;\n\n // 填写值,填写专用\n private String value ;\n //对齐方式\n private String align ;\n //字体\n private String fontFamily ;\n //文字大小\n private Integer fontSize ;\n}"
},
{
"identifier": "SelectKeywords",
"path": "src/main/java/com/resrun/service/pojo/SelectKeywords.java",
"snippet": "public class SelectKeywords extends PDFTextStripper {\n\n private static ThreadLocal<KeyWorkPair> keyWorkPair = new ThreadLocal<KeyWorkPair>();\n\n private Log logger = LogFactory.getLog(SelectKeywords.class);\n\n public SelectKeywords() throws IOException {\n super.setSortByPosition(true);\n }\n\n// public static void main(String[] args) throws Exception {\n// //selectKeyword\n// File file = new File(\"e:/test/948ad938bab14f4e8a2d843f6dd81d57.pdf\");\n// float [] resus = new SelectKeywords().selectKeyword(IOUtils.toByteArray(file), \"948ad938bab14f4e8a2d843f6dd81d57\");//66 571\n// System.out.println(resus[0]+\"--\"+resus[1]+\"---\"+resus[2]);\n// }\n /**\n * 查出PDF里所有的关键字\n * @param pdfFile\n * @param KEY_WORD\n * @return\n */\n public List<float[]> selectAllKeyword(byte [] pdfFile, String KEY_WORD) {\n keyWorkPair.set(new KeyWorkPair(KEY_WORD.split(\",\")));\n ByteArrayInputStream in = null;\n PDDocument document = null;\n try {\n in = new ByteArrayInputStream(pdfFile);\n document = PDDocument.load(in);//加载pdf文件\n this.getText(document);\n List<float[]> allResu = getAllResult();\n return allResu;\n } catch (Exception e) {\n e.printStackTrace();\n }finally{\n try {\n if(in!=null) in.close();\n if(document!=null) document.close();\n } catch (IOException e) {\n }\n }\n return null;\n }\n private List<float[]> getAllResult(){\n KeyWorkPair pair = keyWorkPair.get();\n if(pair!=null && pair.getResu()!=null){\n keyWorkPair.set(null);\n return pair.getAllResu();\n }else{\n keyWorkPair.set(null);\n return null;\n }\n }\n /**\n * 查出PDF里最后一个关键字\n * @param pdfFile\n * @param KEY_WORD\n * @return\n */\n public float [] selectKeyword(byte [] pdfFile,String KEY_WORD) {\n keyWorkPair.set(new KeyWorkPair(KEY_WORD.split(\",\")));\n ByteArrayInputStream in = null;\n PDDocument document = null;\n try {\n in = new ByteArrayInputStream(pdfFile);\n document = PDDocument.load(in);//加载pdf文件\n this.getText(document);\n float[] resu = getResult();\n return resu;\n } catch (Exception e) {\n e.printStackTrace();\n }finally{\n try {\n if(in!=null) in.close();\n if(document!=null) document.close();\n } catch (IOException e) {\n }\n }\n return null;\n }\n\n private float[] getResult(){\n KeyWorkPair pair = keyWorkPair.get();\n if(pair!=null && pair.getResu()!=null){\n keyWorkPair.set(null);\n return pair.getResu();\n }else{\n keyWorkPair.set(null);\n return null;\n }\n }\n\n @Override\n protected void writeString(String string, List<TextPosition> textPositions) throws IOException {\n for (TextPosition text : textPositions) {\n String tChar = text.toString();\n char c = tChar.charAt(0);\n String REGEX = \"[,.\\\\[\\\\](:;!?)/]\";\n lineMatch = matchCharLine(text);\n if ((!tChar.matches(REGEX)) && (!Character.isWhitespace(c))) {\n if ((!is1stChar) && (lineMatch == true)) {\n appendChar(tChar);\n } else if (is1stChar == true) {\n setWordCoord(text, tChar);\n }\n } else {\n endWord();\n }\n }\n endWord();\n }\n protected void appendChar(String tChar) {\n tWord.append(tChar);\n is1stChar = false;\n }\n\n /**\n *\n * %拼接字符串%。\n */\n protected void setWordCoord(TextPosition text, String tChar) {\n itext = text;\n tWord.append(\"(\").append(pageNo).append(\")[\").append(roundVal(Float.valueOf(text.getXDirAdj()))).append(\" : \")\n .append(roundVal(Float.valueOf(text.getYDirAdj()))).append(\"] \").append(tChar);\n is1stChar = false;\n }\n\n protected boolean matchCharLine(TextPosition text) {\n\n Double yVal = roundVal(Float.valueOf(text.getYDirAdj()));\n if (yVal.doubleValue() == lastYVal) {\n return true;\n }\n lastYVal = yVal.doubleValue();\n endWord();\n return false;\n }\n\n protected Double roundVal(Float yVal) {\n DecimalFormat rounded = new DecimalFormat(\"0.0'0'\");\n Double yValDub = new Double(rounded.format(yVal));\n return yValDub;\n }\n\n protected void endWord() {\n // String newWord = tWord.toString().replaceAll(\"[^\\\\x00-\\\\x7F]\",\n // \"\");//为了检索速度 使用正则去掉中文\n String newWord = tWord.toString();// 去掉正则 可以检索中文\n KeyWorkPair pair = keyWorkPair.get();\n\n try {\n String[] seekA = pair.getSeekA();\n float[] resu = new float[3];\n String sWord = newWord.substring(newWord.lastIndexOf(' ') + 1);\n if (!\"\".equals(sWord)) {\n if (sWord.contains(seekA[0])) {\n resu[2] = getCurrentPageNo();// (595,842)\n resu[0] = (float) (roundVal(Float.valueOf(itext.getXDirAdj())) + 0.0F);\n resu[1] = 842.0F - (float) (roundVal(Float.valueOf(itext.getYDirAdj())) + 0.0F);\n logger.info(\"PDF关键字信息:[页数:\" + resu[2] + \"][X:\" + resu[0] + \"][Y:\" + resu[1] + \"]\");\n pair.setResu(resu);\n pair.addResuList(resu);//把每一次找出的关键字放在一个集合里\n keyWorkPair.set(pair);\n }\n }\n } catch (Exception e) {\n e.printStackTrace();\n keyWorkPair.set(null);\n throw new RuntimeException();\n }\n tWord.delete(0, tWord.length());\n is1stChar = true;\n }\n\n private StringBuilder tWord = new StringBuilder();\n private boolean is1stChar = true;\n private boolean lineMatch;\n private int pageNo = 0;\n private double lastYVal;\n\n private TextPosition itext;\n\n /**\n * 关键字和返回的位置信息类\n */\n class KeyWorkPair {\n\n public KeyWorkPair(String[] seekA) {\n super();\n this.seekA = seekA;\n }\n public KeyWorkPair(String[] seekA, float[] resu) {\n super();\n this.seekA = seekA;\n this.resu = resu;\n }\n public KeyWorkPair() {\n super();\n }\n public String[] getSeekA() {\n return seekA;\n }\n public void setSeekA(String[] seekA) {\n this.seekA = seekA;\n }\n public float[] getResu() {\n return resu;\n }\n public void setResu(float[] resu) {\n this.resu = resu;\n }\n\n public void addResuList(float[] resu) {\n resuAll.add(resu);\n }\n public List<float[]> getAllResu() {\n return resuAll;\n }\n\n private String[] seekA;\n private float[] resu;\n //所有的位置\n private List<float[]> resuAll = new ArrayList<>();\n }\n}"
},
{
"identifier": "SourcePositionProperty",
"path": "src/main/java/com/resrun/service/pojo/SourcePositionProperty.java",
"snippet": "@Data\n@AllArgsConstructor\n@NoArgsConstructor\npublic class SourcePositionProperty implements Serializable {\n\n private static final long serialVersionUID = 725976764583634367L;\n\n @ApiModelProperty(\"控件X坐标(左上角)\")\n private Float offsetX ;\n @ApiModelProperty(\"控件Y坐标(左上角)\")\n private Float offsetY ;\n @ApiModelProperty(\"控件宽度\")\n private Float width ;\n @ApiModelProperty(\"控件高度\")\n private Float height ;\n @ApiModelProperty(\"当前文件页面宽度\")\n private Float pageWidth ;\n @ApiModelProperty(\"当前文件页面高度\")\n private Float pageHeight ;\n @ApiModelProperty(\"控件所属页码\")\n private Integer page ;\n\n @ApiModelProperty(\"当前文件页面宽度\")\n private Float realWidth ;\n @ApiModelProperty(\"当前文件页面高度\")\n private Float realHeight ;\n\n\n}"
}
] | import com.itextpdf.text.Document;
import com.itextpdf.text.pdf.PdfReader;
import com.resrun.service.pojo.RealPositionProperty;
import com.resrun.service.pojo.SelectKeywords;
import com.resrun.service.pojo.SourcePositionProperty;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List; | 2,657 | package com.resrun.service.pdf;
/**
* @Description: 计算签署位置业务
* @Package: com.resrun.service.pdf
* @ClassName: CalculatePositionService
* @copyright 北京资源律动科技有限公司
*/
@Service
public class CalculatePositionService {
/**
* @Description #批量计算真实签署位置
* @Param [sourcePositionProperties]
* @return java.util.List<com.resrun.modules.sign.service.tool.pojo.RealPositionProperty>
**/ | package com.resrun.service.pdf;
/**
* @Description: 计算签署位置业务
* @Package: com.resrun.service.pdf
* @ClassName: CalculatePositionService
* @copyright 北京资源律动科技有限公司
*/
@Service
public class CalculatePositionService {
/**
* @Description #批量计算真实签署位置
* @Param [sourcePositionProperties]
* @return java.util.List<com.resrun.modules.sign.service.tool.pojo.RealPositionProperty>
**/ | public List<RealPositionProperty> calculatePositions(List<SourcePositionProperty> sourcePositionProperties, byte[] pdfFileByte){ | 0 | 2023-12-14 06:53:32+00:00 | 4k |
Mahmud0808/ColorBlendr | app/src/main/java/com/drdisagree/colorblendr/utils/WallpaperUtil.java | [
{
"identifier": "MONET_SEED_COLOR",
"path": "app/src/main/java/com/drdisagree/colorblendr/common/Const.java",
"snippet": "public static final String MONET_SEED_COLOR = \"monetSeedColor\";"
},
{
"identifier": "WALLPAPER_COLOR_LIST",
"path": "app/src/main/java/com/drdisagree/colorblendr/common/Const.java",
"snippet": "public static final String WALLPAPER_COLOR_LIST = \"wallpaperColorList\";"
},
{
"identifier": "Const",
"path": "app/src/main/java/com/drdisagree/colorblendr/common/Const.java",
"snippet": "public class Const {\n\n // Preferences file\n public static final String SharedPrefs = BuildConfig.APPLICATION_ID + \"_preferences\";\n\n // System packages\n public static final String FRAMEWORK_PACKAGE = \"android\";\n public static final String SYSTEMUI_PACKAGE = \"com.android.systemui\";\n\n // General preferences\n public static final String FIRST_RUN = \"firstRun\";\n public static final String THEMING_ENABLED = \"themingEnabled\";\n public static final String MONET_STYLE = \"customMonetStyle\";\n public static final String MONET_ACCENT_SATURATION = \"monetAccentSaturationValue\";\n public static final String MONET_BACKGROUND_SATURATION = \"monetBackgroundSaturationValue\";\n public static final String MONET_BACKGROUND_LIGHTNESS = \"monetBackgroundLightnessValue\";\n public static final String MONET_ACCURATE_SHADES = \"monetAccurateShades\";\n public static final String MONET_PITCH_BLACK_THEME = \"monetPitchBlackTheme\";\n public static final String MONET_SEED_COLOR = \"monetSeedColor\";\n public static final String MONET_SEED_COLOR_ENABLED = \"monetSeedColorEnabled\";\n public static final String MANUAL_OVERRIDE_COLORS = \"manualOverrideColors\";\n public static final String MONET_LAST_UPDATED = \"monetLastUpdated\";\n public static final String FABRICATED_OVERLAY_SOURCE_PACKAGE = FRAMEWORK_PACKAGE;\n public static final String FABRICATED_OVERLAY_NAME_SYSTEM = BuildConfig.APPLICATION_ID + \"_dynamic_theme\";\n public static final String FABRICATED_OVERLAY_NAME_APPS = BuildConfig.APPLICATION_ID + \".%s_dynamic_theme\";\n public static final String WALLPAPER_COLOR_LIST = \"wallpaperColorList\";\n public static final String FABRICATED_OVERLAY_FOR_APPS_STATE = \"fabricatedOverlayForAppsState\";\n public static final String SHOW_PER_APP_THEME_WARN = \"showPerAppThemeWarn\";\n public static final String TINT_TEXT_COLOR = \"tintTextColor\";\n\n // Service preferences\n public static final Gson GSON = new Gson();\n public static final String PREF_WORKING_METHOD = \"workingMethod\";\n\n public static Set<String> EXCLUDED_PREFS_FROM_BACKUP = new HashSet<>(\n Arrays.asList(\n PREF_WORKING_METHOD,\n MONET_LAST_UPDATED\n )\n );\n\n public static void saveSelectedFabricatedApps(HashMap<String, Boolean> selectedApps) {\n RPrefs.putString(FABRICATED_OVERLAY_FOR_APPS_STATE, Const.GSON.toJson(selectedApps));\n }\n\n public static HashMap<String, Boolean> getSelectedFabricatedApps() {\n String selectedApps = RPrefs.getString(FABRICATED_OVERLAY_FOR_APPS_STATE, null);\n if (selectedApps == null || selectedApps.isEmpty()) {\n return new HashMap<>();\n }\n\n return Const.GSON.fromJson(selectedApps, new TypeToken<HashMap<String, Boolean>>() {\n }.getType());\n }\n}"
},
{
"identifier": "RPrefs",
"path": "app/src/main/java/com/drdisagree/colorblendr/config/RPrefs.java",
"snippet": "@SuppressWarnings(\"unused\")\npublic class RPrefs {\n\n private static final String TAG = RPrefs.class.getSimpleName();\n\n public static SharedPreferences prefs = ColorBlendr.getAppContext().createDeviceProtectedStorageContext().getSharedPreferences(Const.SharedPrefs, MODE_PRIVATE);\n static SharedPreferences.Editor editor = prefs.edit();\n\n public static void putBoolean(String key, boolean val) {\n editor.putBoolean(key, val).apply();\n }\n\n public static void putInt(String key, int val) {\n editor.putInt(key, val).apply();\n }\n\n public static void putLong(String key, long val) {\n editor.putLong(key, val).apply();\n }\n\n public static void putFloat(String key, float val) {\n editor.putFloat(key, val).apply();\n }\n\n public static void putString(String key, String val) {\n editor.putString(key, val).apply();\n }\n\n public static boolean getBoolean(String key) {\n return prefs.getBoolean(key, false);\n }\n\n public static boolean getBoolean(String key, Boolean defValue) {\n return prefs.getBoolean(key, defValue);\n }\n\n public static int getInt(String key) {\n return prefs.getInt(key, 0);\n }\n\n public static int getInt(String key, int defValue) {\n return prefs.getInt(key, defValue);\n }\n\n public static long getLong(String key) {\n return prefs.getLong(key, 0);\n }\n\n public static long getLong(String key, long defValue) {\n return prefs.getLong(key, defValue);\n }\n\n public static float getFloat(String key) {\n return prefs.getFloat(key, 0);\n }\n\n public static float getFloat(String key, float defValue) {\n return prefs.getFloat(key, defValue);\n }\n\n public static String getString(String key) {\n return prefs.getString(key, null);\n }\n\n public static String getString(String key, String defValue) {\n return prefs.getString(key, defValue);\n }\n\n public static void clearPref(String key) {\n editor.remove(key).apply();\n }\n\n public static void clearPrefs(String... keys) {\n for (String key : keys) {\n editor.remove(key).apply();\n }\n }\n\n public static void clearAllPrefs() {\n editor.clear().apply();\n }\n\n public static void backupPrefs(final @NonNull OutputStream outputStream) {\n try (outputStream; ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream)) {\n objectOutputStream.writeObject(prefs.getAll());\n } catch (IOException e) {\n Log.e(TAG, \"Error serializing preferences\", e);\n }\n\n try (outputStream; ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream)) {\n Map<String, ?> allPrefs = prefs.getAll();\n\n for (String excludedPref : EXCLUDED_PREFS_FROM_BACKUP) {\n allPrefs.remove(excludedPref);\n }\n\n objectOutputStream.writeObject(allPrefs);\n } catch (IOException e) {\n Log.e(TAG, \"Error serializing preferences\", e);\n }\n }\n\n @SuppressWarnings(\"unchecked\")\n public static void restorePrefs(final @NonNull InputStream inputStream) {\n Map<String, Object> map;\n try (inputStream; ObjectInputStream objectInputStream = new ObjectInputStream(inputStream)) {\n map = (Map<String, Object>) objectInputStream.readObject();\n } catch (ClassNotFoundException | IOException e) {\n Log.e(TAG, \"Error deserializing preferences\", e);\n return;\n }\n\n // Retrieve excluded prefs from current prefs\n Map<String, Object> excludedPrefs = new HashMap<>();\n for (String excludedPref : EXCLUDED_PREFS_FROM_BACKUP) {\n Object prefValue = prefs.getAll().get(excludedPref);\n if (prefValue != null) {\n excludedPrefs.put(excludedPref, prefValue);\n }\n }\n\n editor.clear();\n\n // Restore excluded prefs\n for (Map.Entry<String, Object> entry : excludedPrefs.entrySet()) {\n putObject(entry.getKey(), entry.getValue());\n }\n\n // Restore non-excluded prefs\n for (Map.Entry<String, Object> entry : map.entrySet()) {\n if (EXCLUDED_PREFS_FROM_BACKUP.contains(entry.getKey())) {\n continue;\n }\n\n putObject(entry.getKey(), entry.getValue());\n }\n\n editor.apply();\n }\n\n private static void putObject(String key, Object value) {\n if (value instanceof Boolean) {\n editor.putBoolean(key, (Boolean) value);\n } else if (value instanceof String) {\n editor.putString(key, (String) value);\n } else if (value instanceof Integer) {\n editor.putInt(key, (Integer) value);\n } else if (value instanceof Float) {\n editor.putFloat(key, (Float) value);\n } else if (value instanceof Long) {\n editor.putLong(key, (Long) value);\n } else {\n throw new IllegalArgumentException(\"Type \" + value.getClass().getName() + \" is unknown\");\n }\n }\n}"
}
] | import static com.drdisagree.colorblendr.common.Const.MONET_SEED_COLOR;
import static com.drdisagree.colorblendr.common.Const.WALLPAPER_COLOR_LIST;
import android.app.WallpaperManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Handler;
import android.os.Looper;
import android.os.ParcelFileDescriptor;
import android.util.Log;
import android.util.Size;
import androidx.annotation.ColorInt;
import androidx.annotation.NonNull;
import androidx.palette.graphics.Palette;
import com.drdisagree.colorblendr.common.Const;
import com.drdisagree.colorblendr.config.RPrefs;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.stream.Collectors;
import java.util.stream.Stream; | 2,396 | package com.drdisagree.colorblendr.utils;
public class WallpaperUtil {
private static final String TAG = WallpaperUtil.class.getSimpleName();
private static final int SMALL_SIDE = 128;
private static final int MAX_BITMAP_SIZE = 112;
private static final int MAX_WALLPAPER_EXTRACTION_AREA = MAX_BITMAP_SIZE * MAX_BITMAP_SIZE;
private static final double MINIMUM_DARKNESS = 0.1;
private static final double MAXIMUM_DARKNESS = 0.8;
private static final float HUE_THRESHOLD = 25f;
public static void getAndSaveWallpaperColors(Context context) {
if (RPrefs.getInt(MONET_SEED_COLOR, Integer.MIN_VALUE) == Integer.MIN_VALUE &&
AppUtil.permissionsGranted(context)
) {
ArrayList<Integer> wallpaperColors = WallpaperUtil.getWallpaperColors(context); | package com.drdisagree.colorblendr.utils;
public class WallpaperUtil {
private static final String TAG = WallpaperUtil.class.getSimpleName();
private static final int SMALL_SIDE = 128;
private static final int MAX_BITMAP_SIZE = 112;
private static final int MAX_WALLPAPER_EXTRACTION_AREA = MAX_BITMAP_SIZE * MAX_BITMAP_SIZE;
private static final double MINIMUM_DARKNESS = 0.1;
private static final double MAXIMUM_DARKNESS = 0.8;
private static final float HUE_THRESHOLD = 25f;
public static void getAndSaveWallpaperColors(Context context) {
if (RPrefs.getInt(MONET_SEED_COLOR, Integer.MIN_VALUE) == Integer.MIN_VALUE &&
AppUtil.permissionsGranted(context)
) {
ArrayList<Integer> wallpaperColors = WallpaperUtil.getWallpaperColors(context); | RPrefs.putString(WALLPAPER_COLOR_LIST, Const.GSON.toJson(wallpaperColors)); | 2 | 2023-12-06 13:20:16+00:00 | 4k |
bzvs1992/spring-boot-holiday-starter | src/main/java/cn/bzvs/holiday/service/HolidayFixService.java | [
{
"identifier": "HolidayProperties",
"path": "src/main/java/cn/bzvs/holiday/autoconfigure/properties/HolidayProperties.java",
"snippet": "@Data\n@ConfigurationProperties(prefix = \"holiday\")\npublic class HolidayProperties {\n\n /**\n * 类型:在线模式:network, 本地模式:local\n */\n private String type = \"network\";\n\n /**\n * 配置 在线获取 模式下,数据获取的年份\n */\n private Set<Integer> years;\n /**\n * 配置 本地获取 模式下,数据路径\n */\n private String path = \"/config/holiday.json\";\n}"
},
{
"identifier": "CalendarVO",
"path": "src/main/java/cn/bzvs/holiday/entity/vo/CalendarVO.java",
"snippet": "@Data\npublic class CalendarVO {\n\n /**\n * 主键\n * 日期yyyy-MM-dd\n * isNullAble:0\n */\n private String date;\n /**\n * 0普通工作日1周末2需要补班的工作日3法定节假日\n * isNullAble:1,defaultVal:0\n */\n private Integer status;\n}"
},
{
"identifier": "HolidayFix",
"path": "src/main/java/cn/bzvs/holiday/util/HolidayFix.java",
"snippet": "@Slf4j\npublic class HolidayFix {\n\n private HolidayFix() {\n }\n\n /**\n * 重置数据\n *\n * @param file JSON文件\n * @return boolean\n */\n public static boolean reset(@NonNull File file) {\n String json = FileUtil.readString(file, StandardCharsets.UTF_8);\n return reset(json);\n }\n\n /**\n * 重置数据\n *\n * @param json JSON数据\n * @return boolean\n */\n public static boolean reset(String json) {\n try {\n List<CalendarVO> calendarVOList = JSON.parseArray(json, CalendarVO.class);\n return reset(calendarVOList);\n } catch (Exception e) {\n log.warn(\"节假日修复失败, 请检查 JSON 数据,异常信息:{}\", e.getMessage());\n return false;\n }\n }\n\n /**\n * 重置数据\n *\n * @param calendarVOList 对象列表\n * @return boolean\n */\n public static boolean reset(List<CalendarVO> calendarVOList) {\n try {\n ConstantData.init(calendarVOList);\n } catch (Exception e) {\n log.warn(\"节假日修复失败, 请检查 JSON 数据,异常信息:{}\", e.getMessage());\n return false;\n }\n return true;\n }\n\n /**\n * 修复数据\n *\n * @param file JSON文件\n * @return boolean\n */\n public static boolean fix(File file) {\n return fix(file, false);\n }\n\n /**\n * 修复数据\n *\n * @param json JSON数据\n * @return boolean\n */\n public static boolean fix(String json) {\n return fix(json, false);\n }\n\n /**\n * 修复数据\n *\n * @param calendarVOList 对象列表\n * @return boolean\n */\n public static boolean fix(List<CalendarVO> calendarVOList) {\n return fix(calendarVOList, false);\n }\n\n /**\n * 修复数据\n *\n * @param file JSON文件\n * @param updateFile boolean\n * @return boolean\n */\n public static boolean fix(File file, boolean updateFile) {\n if (\"json\".equalsIgnoreCase(FileUtil.getPrefix(file))) {\n String json = FileUtil.readString(file, StandardCharsets.UTF_8);\n return fix(json, updateFile);\n }\n log.warn(\"文件:{} 不是 JSON 文件,无法修复\", file.getName());\n return false;\n }\n\n /**\n * 修复数据\n *\n * @param json JSON数据\n * @param updateFile boolean\n * @return boolean\n */\n public static boolean fix(String json, boolean updateFile) {\n try {\n List<CalendarVO> calendarVOList = JSON.parseArray(json, CalendarVO.class);\n return fix(calendarVOList, updateFile);\n } catch (Exception e) {\n log.warn(\"节假日修复失败, 请检查 JSON 数据,异常信息:{}\", e.getMessage());\n return false;\n }\n }\n\n /**\n * 修复数据\n *\n * @param calendarVOList 对象列表\n * @param updateFile boolean\n * @return boolean\n */\n public static boolean fix(List<CalendarVO> calendarVOList, boolean updateFile) {\n try {\n ConstantData.setDayInfoAll(calendarVOList);\n } catch (Exception e) {\n log.warn(\"节假日修复失败, 请检查 JSON 数据,异常信息:{}\", e.getMessage());\n return false;\n }\n if (updateFile) {\n return updateFile();\n }\n return false;\n }\n\n /**\n * 更新 JSON 文件\n *\n * @return boolean\n */\n public static boolean updateFile() {\n HolidayProperties holidayProperties = (HolidayProperties) ApplicationContextUtil.getBean(HolidayProperties.class);\n if (\"local\".equals(holidayProperties.getType()) && StringUtils.hasText(holidayProperties.getPath())) {\n if (FileUtil.exist(holidayProperties.getPath())) {\n FileUtil.writeString(JSON.toJSONString(ConstantData.getAllDateMap()), holidayProperties.getPath(), StandardCharsets.UTF_8);\n return true;\n } else {\n log.warn(\"文件更新失败,Jar内部JSON文件数据不可更改,请配置外部JSON文件\");\n }\n } else {\n log.warn(\"文件更新失败,请检查配置文件,type 或 path 配置错误, type: {} path: {}\", holidayProperties.getType(), holidayProperties.getPath());\n }\n return false;\n }\n}"
},
{
"identifier": "HolidayUtil",
"path": "src/main/java/cn/bzvs/holiday/util/HolidayUtil.java",
"snippet": "@Slf4j\npublic class HolidayUtil {\n\n private HolidayUtil() {\n }\n\n /**\n * 获取多年的日历数据\n *\n * @param years\n * @return List<CalendarVO>\n */\n public static List<CalendarVO> getYears(@NonNull Set<Integer> years) {\n List<CalendarVO> calendarVOList = new ArrayList<>();\n Set<Integer> sortSet = new TreeSet<>(Comparator.naturalOrder());\n sortSet.addAll(years);\n for (Integer year : sortSet) {\n calendarVOList.addAll(getYear(year));\n }\n return calendarVOList;\n }\n\n /**\n * 获取某年的日历数据\n *\n * @param year\n * @return List<CalendarVO>\n */\n public static List<CalendarVO> getYear(int year) {\n List<CalendarVO> calendarVOList = new ArrayList<>();\n for (int month = 1; month <= 12; month++) {\n calendarVOList.addAll(getMonth(year, month));\n }\n return calendarVOList;\n }\n\n /**\n * 获取某年某月的日历数据\n *\n * @param year\n * @param month\n * @return List<CalendarVO>\n */\n public static List<CalendarVO> getMonth(int year, int month) {\n List<CalendarVO> calendarVOList = new ArrayList<>();\n String result = getMonthStr(year, month);\n JSONObject json = JSON.parseObject(result);\n JSONArray data = json.getJSONArray(\"data\");\n JSONObject dataObj = JSON.parseObject(data.get(0).toString());\n List<AlmanacDTO> almanacDTOList = JSONArray.parseArray(dataObj.getString(\"almanac\"), AlmanacDTO.class);\n for (AlmanacDTO vo : almanacDTOList) {\n String status = vo.getStatus();\n if (vo.getMonth().equals(String.valueOf(month)) && StringUtils.hasText(status)) {\n DateTime dateTime = DateUtil.parse(String.format(\"%s-%s-%s\", year, month, Integer.parseInt(vo.getDay())));\n CalendarVO date = new CalendarVO();\n date.setDate(DateUtil.formatDate(dateTime));\n if (status.equals(\"1\")) {\n date.setStatus(3);\n } else if (status.equals(\"2\")) {\n date.setStatus(2);\n }\n calendarVOList.add(date);\n }\n }\n return calendarVOList;\n }\n\n /**\n * 获取某年某月的日历数据\n *\n * @param year\n * @param month\n * @return List<CalendarVO>\n */\n public static String getMonthStr(int year, int month) {\n String result = \"fail\";\n String query;\n query = year + \"年\" + month + \"月\";\n long timeMillis = System.currentTimeMillis();\n try {\n String apiUrl = \"https://sp1.baidu.com/8aQDcjqpAAV3otqbppnN2DJv/api.php?tn=wisetpl&format=json&query=\" + query + \"&co=&resource_id=39043&t=\" + timeMillis + \"&cb=op_aladdin_callback\" + timeMillis;\n String content = HttpUtil.get(apiUrl);\n result = reParseJson(content);\n } catch (Exception e) {\n log.error(\"在线获取 {} 数据异常\", query, e);\n }\n return result;\n }\n\n /**\n * 解析json\n */\n public static String reParseJson(String old) {\n int start = old.indexOf(\"{\");\n int end = old.lastIndexOf(\"}\");\n return old.substring(start, end + 1);\n }\n\n public static int getDayOfWeek(DateTime dateTime) {\n Calendar calendar = dateTime.toCalendar();\n int day = calendar.get(Calendar.DAY_OF_WEEK);\n switch (day) {\n case Calendar.SUNDAY -> {\n return 7;\n }\n case Calendar.MONDAY -> {\n return 1;\n }\n case Calendar.TUESDAY -> {\n return 2;\n }\n case Calendar.WEDNESDAY -> {\n return 3;\n }\n case Calendar.THURSDAY -> {\n return 4;\n }\n case Calendar.FRIDAY -> {\n return 5;\n }\n case Calendar.SATURDAY -> {\n return 6;\n }\n default -> throw new IllegalStateException(\"Unexpected value: \" + day);\n }\n }\n\n public static void setHolidayData(HolidayProperties properties, ResourceLoader resourceLoader) throws Exception {\n List<CalendarVO> calendarVOList;\n String result;\n // 本地模式\n if (properties.getType().equals(\"local\")) {\n // 使用外部 JSON 文件数据\n if (FileUtil.exist(properties.getPath())) {\n result = FileUtil.readString(properties.getPath(), StandardCharsets.UTF_8);\n }\n // 使用内部 JSON 文件数据\n else {\n Resource resource = resourceLoader.getResource(properties.getPath());\n InputStream inputStream = resource.getInputStream();\n result = new BufferedReader(new InputStreamReader(inputStream)).lines().collect(Collectors.joining(System.lineSeparator()));\n }\n Assert.state(StringUtils.hasText(result),\n \"If the data is empty, please configure the data\");\n calendarVOList = JSON.parseArray(result, CalendarVO.class);\n }\n // 在线模式\n else {\n Set<Integer> years = new HashSet<>();\n if (properties.getYears() != null && !properties.getYears().isEmpty()) {\n years = properties.getYears();\n }\n int year = LocalDate.now().getYear();\n years.add(year);\n calendarVOList = HolidayUtil.getYears(years);\n }\n\n if (calendarVOList != null && !calendarVOList.isEmpty()) {\n ConstantData.init(calendarVOList);\n } else {\n log.warn(\"节假日数据初始化失败\");\n }\n }\n}"
}
] | import cn.bzvs.holiday.autoconfigure.properties.HolidayProperties;
import cn.bzvs.holiday.entity.vo.CalendarVO;
import cn.bzvs.holiday.util.HolidayFix;
import cn.bzvs.holiday.util.HolidayUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ResourceLoader;
import java.io.File;
import java.util.List; | 3,130 | package cn.bzvs.holiday.service;
/**
* 节假日相关的日历修复服务
*
* @author bzvs
* @date 2024/12/06
* @since 1.0.0
*/
@Slf4j
public class HolidayFixService {
private final HolidayProperties properties;
private final ResourceLoader resourceLoader;
/**
* 构建函数
*
* @param properties 配置
* @param resourceLoader 资源加载Loader
*/
public HolidayFixService(HolidayProperties properties, ResourceLoader resourceLoader) {
this.properties = properties;
this.resourceLoader = resourceLoader;
reset();
}
/**
* 数据重置并刷新
*/
public void reset() {
try { | package cn.bzvs.holiday.service;
/**
* 节假日相关的日历修复服务
*
* @author bzvs
* @date 2024/12/06
* @since 1.0.0
*/
@Slf4j
public class HolidayFixService {
private final HolidayProperties properties;
private final ResourceLoader resourceLoader;
/**
* 构建函数
*
* @param properties 配置
* @param resourceLoader 资源加载Loader
*/
public HolidayFixService(HolidayProperties properties, ResourceLoader resourceLoader) {
this.properties = properties;
this.resourceLoader = resourceLoader;
reset();
}
/**
* 数据重置并刷新
*/
public void reset() {
try { | HolidayUtil.setHolidayData(properties, resourceLoader); | 3 | 2023-12-05 10:59:02+00:00 | 4k |
HelpChat/DeluxeMenus | src/main/java/com/extendedclip/deluxemenus/persistentmeta/PersistentMetaHandler.java | [
{
"identifier": "DeluxeMenus",
"path": "src/main/java/com/extendedclip/deluxemenus/DeluxeMenus.java",
"snippet": "public class DeluxeMenus extends JavaPlugin {\r\n\r\n public final static Map<String, Material> MATERIALS\r\n = Arrays.stream(Material.values()).collect(Collectors.toUnmodifiableMap(Enum::name, Function.identity()));\r\n private static DeluxeMenus instance;\r\n private static DebugLevel debugLevel = DebugLevel.LOWEST;\r\n private DeluxeMenusConfig menuConfig;\r\n private Map<String, ItemHook> itemHooks;\r\n private VaultHook vaultHook;\r\n private boolean checkUpdates;\r\n private ItemStack head;\r\n private PersistentMetaHandler persistentMetaHandler;\r\n private MenuItemMarker menuItemMarker;\r\n private DupeFixer dupeFixer;\r\n private BukkitAudiences adventure;\r\n\r\n @Override\r\n public void onLoad() {\r\n instance = this;\r\n\r\n this.persistentMetaHandler = new PersistentMetaHandler();\r\n \r\n if (NbtProvider.isAvailable()) {\r\n DeluxeMenus.debug(\r\n DebugLevel.HIGHEST,\r\n Level.INFO,\r\n \"NMS hook has been setup successfully!\"\r\n );\r\n return;\r\n }\r\n\r\n debug(\r\n DebugLevel.HIGHEST,\r\n Level.WARNING,\r\n \"Could not setup a NMS hook for your server version!\"\r\n );\r\n }\r\n\r\n @SuppressWarnings(\"deprecation\")\r\n @Override\r\n public void onEnable() {\r\n if (!hookPlaceholderAPI()) {\r\n debug(\r\n DebugLevel.HIGHEST,\r\n Level.SEVERE,\r\n \"Could not hook into PlaceholderAPI!\",\r\n \"DeluxeMenus will now disable!\"\r\n );\r\n Bukkit.getPluginManager().disablePlugin(this);\r\n return;\r\n } else {\r\n debug(\r\n DebugLevel.HIGHEST,\r\n Level.INFO,\r\n \"Successfully hooked into PlaceholderAPI!\"\r\n );\r\n }\r\n\r\n menuItemMarker = new MenuItemMarker(this);\r\n dupeFixer = new DupeFixer(this, menuItemMarker);\r\n\r\n this.adventure = BukkitAudiences.create(this);\r\n\r\n setupItemHooks();\r\n\r\n if (Bukkit.getPluginManager().isPluginEnabled(\"Vault\")) {\r\n vaultHook = new VaultHook();\r\n\r\n if (vaultHook.hooked()) {\r\n debug(\r\n DebugLevel.HIGHEST,\r\n Level.INFO,\r\n \"Successfully hooked into Vault!\"\r\n );\r\n }\r\n }\r\n\r\n if (!VersionHelper.IS_ITEM_LEGACY) {\r\n head = new ItemStack(Material.PLAYER_HEAD, 1);\r\n } else {\r\n head = new ItemStack(Material.valueOf(\"SKULL_ITEM\"), 1, (short) 3);\r\n }\r\n\r\n menuConfig = new DeluxeMenusConfig(this);\r\n if (menuConfig.loadDefConfig()) {\r\n debugLevel(menuConfig.debugLevel());\r\n checkUpdates = getConfig().getBoolean(\"check_updates\");\r\n debug(\r\n DebugLevel.HIGHEST,\r\n Level.INFO,\r\n menuConfig.loadGUIMenus() + \" GUI menus loaded!\"\r\n );\r\n } else {\r\n debug(\r\n DebugLevel.HIGHEST,\r\n Level.WARNING,\r\n \"Failed to load from config.yml. Use /dm reload after fixing your errors.\"\r\n );\r\n }\r\n\r\n new PlayerListener(this);\r\n new DeluxeMenusCommands(this);\r\n Bukkit.getMessenger().registerOutgoingPluginChannel(this, \"BungeeCord\");\r\n\r\n if (checkUpdates) {\r\n UpdateChecker updateChecker = new UpdateChecker(this);\r\n\r\n if (updateChecker.updateAvailable()) {\r\n debug(\r\n DebugLevel.HIGHEST,\r\n Level.INFO,\r\n \"An update for DeluxeMenus (DeluxeMenus v\" + updateChecker.getLatestVersion() + \")\",\r\n \"is available at https://www.spigotmc.org/resources/deluxemenus.11734/\"\r\n );\r\n } else {\r\n debug(\r\n DebugLevel.HIGHEST,\r\n Level.INFO,\r\n \"You are running the latest version of DeluxeMenus!\"\r\n );\r\n }\r\n }\r\n\r\n startMetrics();\r\n\r\n new Expansion(this).register();\r\n }\r\n\r\n @Override\r\n public void onDisable() {\r\n Bukkit.getMessenger().unregisterOutgoingPluginChannel(this, \"BungeeCord\");\r\n\r\n Bukkit.getScheduler().cancelTasks(this);\r\n\r\n if (this.adventure != null) {\r\n this.adventure.close();\r\n this.adventure = null;\r\n }\r\n\r\n Menu.unloadForShutdown();\r\n\r\n itemHooks.clear();\r\n\r\n instance = null;\r\n }\r\n\r\n private void setupItemHooks() {\r\n itemHooks = new HashMap<>();\r\n\r\n if (PlaceholderAPIPlugin.getServerVersion().isSpigot()) {\r\n itemHooks.put(HeadType.NAMED.getHookName(), new NamedHeadHook(this));\r\n itemHooks.put(HeadType.BASE64.getHookName(), new BaseHeadHook());\r\n itemHooks.put(HeadType.TEXTURE.getHookName(), new TextureHeadHook());\r\n }\r\n\r\n if (Bukkit.getPluginManager().isPluginEnabled(\"HeadDatabase\")) {\r\n try {\r\n Class.forName(\"me.arcaniax.hdb.api.HeadDatabaseAPI\");\r\n itemHooks.put(HeadType.HDB.getHookName(), new HeadDatabaseHook());\r\n } catch (ClassNotFoundException ignored) {}\r\n }\r\n\r\n if (Bukkit.getPluginManager().isPluginEnabled(\"ItemsAdder\")) {\r\n itemHooks.put(\"itemsadder\", new ItemsAdderHook());\r\n }\r\n\r\n if (Bukkit.getPluginManager().isPluginEnabled(\"Oraxen\")) {\r\n itemHooks.put(\"oraxen\", new OraxenHook());\r\n }\r\n\r\n if (Bukkit.getPluginManager().isPluginEnabled(\"MMOItems\")) {\r\n itemHooks.put(\"mmoitems\", new MMOItemsHook());\r\n }\r\n }\r\n\r\n public Optional<ItemHook> getItemHook(String id) {\r\n return Optional.ofNullable(itemHooks.get(id));\r\n }\r\n\r\n public Map<String, ItemHook> getItemHooks() {\r\n return itemHooks;\r\n }\r\n\r\n public ItemStack getHead() {\r\n return head != null ? head : new ItemStack(Material.DIRT, 1);\r\n }\r\n\r\n public static DeluxeMenus getInstance() {\r\n return instance;\r\n }\r\n\r\n public static DebugLevel debugLevel() {\r\n return debugLevel;\r\n }\r\n\r\n public static void debugLevel(final DebugLevel level) {\r\n debugLevel = level;\r\n }\r\n\r\n public static DebugLevel printStacktraceLevel() {\r\n return DebugLevel.MEDIUM;\r\n }\r\n\r\n public static boolean shouldPrintStackTrace() {\r\n return debugLevel().getPriority() <= printStacktraceLevel().getPriority();\r\n }\r\n\r\n public static void printStacktrace(final String message, final Throwable throwable) {\r\n if (!shouldPrintStackTrace()) return;\r\n\r\n getInstance().getLogger().log(Level.SEVERE, message, throwable);\r\n }\r\n\r\n private void startMetrics() {\r\n Metrics metrics = new Metrics(this, 445);\r\n metrics.addCustomChart(new Metrics.SingleLineChart(\"menus\", Menu::getLoadedMenuSize));\r\n }\r\n\r\n public void connect(Player p, String server) {\r\n ByteArrayDataOutput out = ByteStreams.newDataOutput();\r\n\r\n try {\r\n out.writeUTF(\"Connect\");\r\n out.writeUTF(server);\r\n } catch (Exception e) {\r\n debug(\r\n DebugLevel.HIGHEST,\r\n Level.SEVERE,\r\n \"There was a problem attempting to send \" + p.getName() + \" to server \" + server + \"!\"\r\n );\r\n\r\n printStacktrace(\r\n \"There was a problem attempting to send \" + p.getName() + \" to server \" + server + \"!\",\r\n e\r\n );\r\n }\r\n\r\n p.sendPluginMessage(this, \"BungeeCord\", out.toByteArray());\r\n }\r\n\r\n public void sms(CommandSender s, Component msg) {\r\n adventure().sender(s).sendMessage(msg);\r\n }\r\n\r\n public void sms(CommandSender s, Messages msg) {\r\n adventure().sender(s).sendMessage(msg.message());\r\n }\r\n\r\n public static void debug(@NotNull final DebugLevel debugLevel, @NotNull final Level level, @NotNull final String... messages) {\r\n if (debugLevel().getPriority() > debugLevel.getPriority()) return;\r\n\r\n getInstance().getLogger().log(\r\n level,\r\n String.join(System.lineSeparator(), messages)\r\n );\r\n }\r\n\r\n private boolean hookPlaceholderAPI() {\r\n return Bukkit.getPluginManager().getPlugin(\"PlaceholderAPI\") != null;\r\n }\r\n\r\n public MenuItemMarker getMenuItemMarker() {\r\n return menuItemMarker;\r\n }\r\n\r\n public DeluxeMenusConfig getConfiguration() {\r\n return menuConfig;\r\n }\r\n\r\n public VaultHook getVault() {\r\n return vaultHook;\r\n }\r\n\r\n public PersistentMetaHandler getPersistentMetaHandler() {\r\n return persistentMetaHandler;\r\n }\r\n\r\n public BukkitAudiences adventure() {\r\n if (this.adventure == null) {\r\n throw new IllegalStateException(\"Tried to access Adventure when the plugin was disabled!\");\r\n }\r\n return this.adventure;\r\n }\r\n\r\n public void clearCaches() {\r\n itemHooks.values().stream()\r\n .filter(Objects::nonNull)\r\n .filter(hook -> hook instanceof SimpleCache)\r\n .map(hook -> (SimpleCache) hook)\r\n .forEach(SimpleCache::clearCache);\r\n }\r\n}\r"
},
{
"identifier": "DebugLevel",
"path": "src/main/java/com/extendedclip/deluxemenus/utils/DebugLevel.java",
"snippet": "public enum DebugLevel {\r\n LOWEST(0, \"LOWEST\"),\r\n LOW(1, \"LOW\"),\r\n MEDIUM(2, \"MEDIUM\"),\r\n HIGH(3, \"HIGH\"),\r\n HIGHEST(4, \"HIGHEST\");\r\n\r\n private final String[] names;\r\n private final int priority;\r\n\r\n private DebugLevel(final int priority, @NotNull final String... names) {\r\n this.priority = priority;\r\n this.names = names;\r\n }\r\n\r\n public int getPriority() {\r\n return priority;\r\n }\r\n\r\n private static final Map<String, DebugLevel> LEVELS = Arrays.stream(values())\r\n .flatMap(level -> Arrays.stream(level.names).map(name -> Map.entry(name.toLowerCase(Locale.ROOT), level)))\r\n .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));\r\n\r\n public static @Nullable DebugLevel getByName(@NotNull final String name) {\r\n return LEVELS.get(name.toLowerCase(Locale.ROOT));\r\n }\r\n}\r"
}
] | import com.extendedclip.deluxemenus.DeluxeMenus;
import java.util.Arrays;
import java.util.Locale;
import java.util.Map;
import java.util.function.Function;
import java.util.logging.Level;
import java.util.stream.Collectors;
import com.extendedclip.deluxemenus.utils.DebugLevel;
import org.bukkit.NamespacedKey;
import org.bukkit.entity.Player;
import org.bukkit.persistence.PersistentDataType;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
| 3,042 | package com.extendedclip.deluxemenus.persistentmeta;
public class PersistentMetaHandler {
/**
* Get a {@link PersistentDataType} from its name.
*
* @param name The name of the type.
* @return The type, or null if type does not exist or is not supported.
*/
public @Nullable PersistentDataType<?, ?> getSupportedType(@NotNull final String name) {
switch (name.toUpperCase(Locale.ROOT)) {
case "DOUBLE":
return PersistentDataType.DOUBLE;
case "INTEGER":
case "LONG":
return PersistentDataType.LONG;
case "STRING":
case "BOOLEAN":
return PersistentDataType.STRING;
}
return null;
}
/**
* Get a {@link NamespacedKey} from a string. If the key contains a namespace, it will use that, otherwise it will
* use the plugin's namespace.
*
* @param key The string to get the {@link NamespacedKey} from.
* @return The {@link NamespacedKey}.
*/
private @NotNull NamespacedKey getKey(@NotNull final String key) {
final NamespacedKey namespacedKey;
if (key.contains(":")) {
final String[] split = key.split(":", 2);
namespacedKey = new NamespacedKey(split[0], split[1]);
} else {
namespacedKey = new NamespacedKey(DeluxeMenus.getInstance(), key);
}
return namespacedKey;
}
/**
* Get a meta value from a player's {@link org.bukkit.persistence.PersistentDataContainer}.
*
* @param player The player to get the meta value from.
* @param key The key of the meta value.
* @param typeName The name of the type of the meta value.
* @param defaultValue The default value if no meta value will be found.
* @return The meta value or the default value if no meta value was found.
*/
public @Nullable String getMeta(
@NotNull final Player player,
@NotNull final String key,
@NotNull final String typeName,
@Nullable final String defaultValue
) {
final NamespacedKey namespacedKey;
try {
namespacedKey = getKey(key);
} catch (final IllegalArgumentException e) {
DeluxeMenus.debug(
| package com.extendedclip.deluxemenus.persistentmeta;
public class PersistentMetaHandler {
/**
* Get a {@link PersistentDataType} from its name.
*
* @param name The name of the type.
* @return The type, or null if type does not exist or is not supported.
*/
public @Nullable PersistentDataType<?, ?> getSupportedType(@NotNull final String name) {
switch (name.toUpperCase(Locale.ROOT)) {
case "DOUBLE":
return PersistentDataType.DOUBLE;
case "INTEGER":
case "LONG":
return PersistentDataType.LONG;
case "STRING":
case "BOOLEAN":
return PersistentDataType.STRING;
}
return null;
}
/**
* Get a {@link NamespacedKey} from a string. If the key contains a namespace, it will use that, otherwise it will
* use the plugin's namespace.
*
* @param key The string to get the {@link NamespacedKey} from.
* @return The {@link NamespacedKey}.
*/
private @NotNull NamespacedKey getKey(@NotNull final String key) {
final NamespacedKey namespacedKey;
if (key.contains(":")) {
final String[] split = key.split(":", 2);
namespacedKey = new NamespacedKey(split[0], split[1]);
} else {
namespacedKey = new NamespacedKey(DeluxeMenus.getInstance(), key);
}
return namespacedKey;
}
/**
* Get a meta value from a player's {@link org.bukkit.persistence.PersistentDataContainer}.
*
* @param player The player to get the meta value from.
* @param key The key of the meta value.
* @param typeName The name of the type of the meta value.
* @param defaultValue The default value if no meta value will be found.
* @return The meta value or the default value if no meta value was found.
*/
public @Nullable String getMeta(
@NotNull final Player player,
@NotNull final String key,
@NotNull final String typeName,
@Nullable final String defaultValue
) {
final NamespacedKey namespacedKey;
try {
namespacedKey = getKey(key);
} catch (final IllegalArgumentException e) {
DeluxeMenus.debug(
| DebugLevel.HIGHEST,
| 1 | 2023-12-14 23:41:07+00:00 | 4k |
lxs2601055687/contextAdminRuoYi | ruoyi-common/src/main/java/com/ruoyi/common/utils/sql/SqlUtil.java | [
{
"identifier": "UtilException",
"path": "ruoyi-common/src/main/java/com/ruoyi/common/exception/UtilException.java",
"snippet": "public class UtilException extends RuntimeException {\n private static final long serialVersionUID = 8247610319171014183L;\n\n public UtilException(Throwable e) {\n super(e.getMessage(), e);\n }\n\n public UtilException(String message) {\n super(message);\n }\n\n public UtilException(String message, Throwable throwable) {\n super(message, throwable);\n }\n}"
},
{
"identifier": "StringUtils",
"path": "ruoyi-common/src/main/java/com/ruoyi/common/utils/StringUtils.java",
"snippet": "@NoArgsConstructor(access = AccessLevel.PRIVATE)\npublic class StringUtils extends org.apache.commons.lang3.StringUtils {\n\n public static final String SEPARATOR = \",\";\n\n /**\n * 获取参数不为空值\n *\n * @param str defaultValue 要判断的value\n * @return value 返回值\n */\n public static String blankToDefault(String str, String defaultValue) {\n return StrUtil.blankToDefault(str, defaultValue);\n }\n\n /**\n * * 判断一个字符串是否为空串\n *\n * @param str String\n * @return true:为空 false:非空\n */\n public static boolean isEmpty(String str) {\n return StrUtil.isEmpty(str);\n }\n\n /**\n * * 判断一个字符串是否为非空串\n *\n * @param str String\n * @return true:非空串 false:空串\n */\n public static boolean isNotEmpty(String str) {\n return !isEmpty(str);\n }\n\n /**\n * 去空格\n */\n public static String trim(String str) {\n return StrUtil.trim(str);\n }\n\n /**\n * 截取字符串\n *\n * @param str 字符串\n * @param start 开始\n * @return 结果\n */\n public static String substring(final String str, int start) {\n return substring(str, start, str.length());\n }\n\n /**\n * 截取字符串\n *\n * @param str 字符串\n * @param start 开始\n * @param end 结束\n * @return 结果\n */\n public static String substring(final String str, int start, int end) {\n return StrUtil.sub(str, start, end);\n }\n\n /**\n * 格式化文本, {} 表示占位符<br>\n * 此方法只是简单将占位符 {} 按照顺序替换为参数<br>\n * 如果想输出 {} 使用 \\\\转义 { 即可,如果想输出 {} 之前的 \\ 使用双转义符 \\\\\\\\ 即可<br>\n * 例:<br>\n * 通常使用:format(\"this is {} for {}\", \"a\", \"b\") -> this is a for b<br>\n * 转义{}: format(\"this is \\\\{} for {}\", \"a\", \"b\") -> this is {} for a<br>\n * 转义\\: format(\"this is \\\\\\\\{} for {}\", \"a\", \"b\") -> this is \\a for b<br>\n *\n * @param template 文本模板,被替换的部分用 {} 表示\n * @param params 参数值\n * @return 格式化后的文本\n */\n public static String format(String template, Object... params) {\n return StrUtil.format(template, params);\n }\n\n /**\n * 是否为http(s)://开头\n *\n * @param link 链接\n * @return 结果\n */\n public static boolean ishttp(String link) {\n return Validator.isUrl(link);\n }\n\n /**\n * 字符串转set\n *\n * @param str 字符串\n * @param sep 分隔符\n * @return set集合\n */\n public static Set<String> str2Set(String str, String sep) {\n return new HashSet<>(str2List(str, sep, true, false));\n }\n\n /**\n * 字符串转list\n *\n * @param str 字符串\n * @param sep 分隔符\n * @param filterBlank 过滤纯空白\n * @param trim 去掉首尾空白\n * @return list集合\n */\n public static List<String> str2List(String str, String sep, boolean filterBlank, boolean trim) {\n List<String> list = new ArrayList<>();\n if (isEmpty(str)) {\n return list;\n }\n\n // 过滤空白字符串\n if (filterBlank && isBlank(str)) {\n return list;\n }\n String[] split = str.split(sep);\n for (String string : split) {\n if (filterBlank && isBlank(string)) {\n continue;\n }\n if (trim) {\n string = trim(string);\n }\n list.add(string);\n }\n\n return list;\n }\n\n /**\n * 查找指定字符串是否包含指定字符串列表中的任意一个字符串同时串忽略大小写\n *\n * @param cs 指定字符串\n * @param searchCharSequences 需要检查的字符串数组\n * @return 是否包含任意一个字符串\n */\n public static boolean containsAnyIgnoreCase(CharSequence cs, CharSequence... searchCharSequences) {\n return StrUtil.containsAnyIgnoreCase(cs, searchCharSequences);\n }\n\n /**\n * 驼峰转下划线命名\n */\n public static String toUnderScoreCase(String str) {\n return StrUtil.toUnderlineCase(str);\n }\n\n /**\n * 是否包含字符串\n *\n * @param str 验证字符串\n * @param strs 字符串组\n * @return 包含返回true\n */\n public static boolean inStringIgnoreCase(String str, String... strs) {\n return StrUtil.equalsAnyIgnoreCase(str, strs);\n }\n\n /**\n * 将下划线大写方式命名的字符串转换为驼峰式。如果转换前的下划线大写方式命名的字符串为空,则返回空字符串。 例如:HELLO_WORLD->HelloWorld\n *\n * @param name 转换前的下划线大写方式命名的字符串\n * @return 转换后的驼峰式命名的字符串\n */\n public static String convertToCamelCase(String name) {\n return StrUtil.upperFirst(StrUtil.toCamelCase(name));\n }\n\n /**\n * 驼峰式命名法 例如:user_name->userName\n */\n public static String toCamelCase(String s) {\n return StrUtil.toCamelCase(s);\n }\n\n /**\n * 查找指定字符串是否匹配指定字符串列表中的任意一个字符串\n *\n * @param str 指定字符串\n * @param strs 需要检查的字符串数组\n * @return 是否匹配\n */\n public static boolean matches(String str, List<String> strs) {\n if (isEmpty(str) || CollUtil.isEmpty(strs)) {\n return false;\n }\n for (String pattern : strs) {\n if (isMatch(pattern, str)) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * 判断url是否与规则配置:\n * ? 表示单个字符;\n * * 表示一层路径内的任意字符串,不可跨层级;\n * ** 表示任意层路径;\n *\n * @param pattern 匹配规则\n * @param url 需要匹配的url\n */\n public static boolean isMatch(String pattern, String url) {\n AntPathMatcher matcher = new AntPathMatcher();\n return matcher.match(pattern, url);\n }\n\n /**\n * 数字左边补齐0,使之达到指定长度。注意,如果数字转换为字符串后,长度大于size,则只保留 最后size个字符。\n *\n * @param num 数字对象\n * @param size 字符串指定长度\n * @return 返回数字的字符串格式,该字符串为指定长度。\n */\n public static String padl(final Number num, final int size) {\n return padl(num.toString(), size, '0');\n }\n\n /**\n * 字符串左补齐。如果原始字符串s长度大于size,则只保留最后size个字符。\n *\n * @param s 原始字符串\n * @param size 字符串指定长度\n * @param c 用于补齐的字符\n * @return 返回指定长度的字符串,由原字符串左补齐或截取得到。\n */\n public static String padl(final String s, final int size, final char c) {\n final StringBuilder sb = new StringBuilder(size);\n if (s != null) {\n final int len = s.length();\n if (s.length() <= size) {\n for (int i = size - len; i > 0; i--) {\n sb.append(c);\n }\n sb.append(s);\n } else {\n return s.substring(len - size, len);\n }\n } else {\n for (int i = size; i > 0; i--) {\n sb.append(c);\n }\n }\n return sb.toString();\n }\n\n /**\n * 切分字符串(分隔符默认逗号)\n *\n * @param str 被切分的字符串\n * @return 分割后的数据列表\n */\n public static List<String> splitList(String str) {\n return splitTo(str, Convert::toStr);\n }\n\n /**\n * 切分字符串\n *\n * @param str 被切分的字符串\n * @param separator 分隔符\n * @return 分割后的数据列表\n */\n public static List<String> splitList(String str, String separator) {\n return splitTo(str, separator, Convert::toStr);\n }\n\n /**\n * 切分字符串自定义转换(分隔符默认逗号)\n *\n * @param str 被切分的字符串\n * @param mapper 自定义转换\n * @return 分割后的数据列表\n */\n public static <T> List<T> splitTo(String str, Function<? super Object, T> mapper) {\n return splitTo(str, SEPARATOR, mapper);\n }\n\n /**\n * 切分字符串自定义转换\n *\n * @param str 被切分的字符串\n * @param separator 分隔符\n * @param mapper 自定义转换\n * @return 分割后的数据列表\n */\n public static <T> List<T> splitTo(String str, String separator, Function<? super Object, T> mapper) {\n if (isBlank(str)) {\n return new ArrayList<>(0);\n }\n return StrUtil.split(str, separator)\n .stream()\n .filter(Objects::nonNull)\n .map(mapper)\n .collect(Collectors.toList());\n }\n\n}"
}
] | import com.ruoyi.common.exception.UtilException;
import com.ruoyi.common.utils.StringUtils;
import lombok.AccessLevel;
import lombok.NoArgsConstructor; | 3,125 | package com.ruoyi.common.utils.sql;
/**
* sql操作工具类
*
* @author ruoyi
*/
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class SqlUtil {
/**
* 定义常用的 sql关键字
*/
public static final String SQL_REGEX = "select |insert |delete |update |drop |count |exec |chr |mid |master |truncate |char |and |declare ";
/**
* 仅支持字母、数字、下划线、空格、逗号、小数点(支持多个字段排序)
*/
public static final String SQL_PATTERN = "[a-zA-Z0-9_\\ \\,\\.]+";
/**
* 检查字符,防止注入绕过
*/
public static String escapeOrderBySql(String value) {
if (StringUtils.isNotEmpty(value) && !isValidOrderBySql(value)) { | package com.ruoyi.common.utils.sql;
/**
* sql操作工具类
*
* @author ruoyi
*/
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class SqlUtil {
/**
* 定义常用的 sql关键字
*/
public static final String SQL_REGEX = "select |insert |delete |update |drop |count |exec |chr |mid |master |truncate |char |and |declare ";
/**
* 仅支持字母、数字、下划线、空格、逗号、小数点(支持多个字段排序)
*/
public static final String SQL_PATTERN = "[a-zA-Z0-9_\\ \\,\\.]+";
/**
* 检查字符,防止注入绕过
*/
public static String escapeOrderBySql(String value) {
if (StringUtils.isNotEmpty(value) && !isValidOrderBySql(value)) { | throw new UtilException("参数不符合规范,不能进行查询"); | 0 | 2023-12-07 12:06:21+00:00 | 4k |
DHBin/isme-java-serve | src/main/java/cn/dhbin/isme/pms/controller/RoleController.java | [
{
"identifier": "RoleType",
"path": "src/main/java/cn/dhbin/isme/common/auth/RoleType.java",
"snippet": "public class RoleType {\n\n\n public static final String SUPER_ADMIN = \"SUPER_ADMIN\";\n\n public static final String SYS_ADMIN = \"SYS_ADMIN\";\n\n public static final String ROLE_PMS = \"ROLE_PMS\";\n}"
},
{
"identifier": "SaTokenConfigure",
"path": "src/main/java/cn/dhbin/isme/common/auth/SaTokenConfigure.java",
"snippet": "@Configuration\npublic class SaTokenConfigure implements WebMvcConfigurer {\n\n public static final String JWT_USER_ID_KEY = \"userId\";\n\n public static final String JWT_USERNAME_KEY = \"username\";\n\n public static final String JWT_ROLE_LIST_KEY = \"roleCodes\";\n\n public static final String JWT_CURRENT_ROLE_KEY = \"currentRoleCode\";\n\n @Bean\n public StpLogic getStpLogicJwt() {\n return new StpLogicJwtForStateless();\n }\n\n @Override\n public void addInterceptors(InterceptorRegistry registry) {\n registry.addInterceptor(new SaInterceptor(handle -> StpUtil.checkLogin()))\n .addPathPatterns(\"/**\")\n .excludePathPatterns(\"/auth/login\")\n .excludePathPatterns(\"/auth/captcha\")\n .excludePathPatterns(\"/doc.html\")\n .excludePathPatterns(\"/webjars/**\")\n .excludePathPatterns(\"/favicon.ico\")\n .excludePathPatterns(\"/v3/api-docs/**\")\n ;\n }\n\n}"
},
{
"identifier": "Page",
"path": "src/main/java/cn/dhbin/isme/common/response/Page.java",
"snippet": "@Data\npublic class Page<T> {\n\n private List<T> pageData;\n\n private Long total;\n\n\n /**\n * mpPage转成Page\n *\n * @param mpPage mp的分页结果\n * @param <T> 类型\n * @return page\n */\n public static <T> Page<T> convert(IPage<T> mpPage) {\n Page<T> page = new Page<>();\n page.setPageData(mpPage.getRecords());\n page.setTotal(mpPage.getTotal());\n return page;\n }\n}"
},
{
"identifier": "R",
"path": "src/main/java/cn/dhbin/isme/common/response/R.java",
"snippet": "@Data\n@Accessors(chain = true)\npublic class R<T> {\n\n /**\n * 数据\n */\n private T data;\n\n /**\n * 响应码\n */\n private int code;\n\n /**\n * 描述\n */\n private String message;\n\n /**\n * 无数据的成功响应\n *\n * @param <T> 类型\n * @return 响应体\n */\n public static <T> R<T> ok() {\n return ok(null);\n }\n\n /**\n * 成功的响应码,附带数据\n *\n * @param data 数据\n * @param <T> 数据类型\n * @return 响应体\n */\n public static <T> R<T> ok(T data) {\n R<T> r = new R<>();\n r.setData(data);\n r.setCode(BizResponseCode.OK.getCode());\n r.setMessage(BizResponseCode.OK.getMsg());\n return r;\n }\n\n /**\n * 构建业务异常的响应\n *\n * @param exception 业务异常\n * @param <T> 类型\n * @return 响应体\n */\n public static <T> R<T> build(BizException exception) {\n R<T> r = new R<>();\n r.setCode(exception.getCode().getCode());\n r.setData(null);\n r.setMessage(exception.getMessage());\n return r;\n }\n\n}"
},
{
"identifier": "PermissionDto",
"path": "src/main/java/cn/dhbin/isme/pms/domain/dto/PermissionDto.java",
"snippet": "@Data\npublic class PermissionDto {\n\n private Long id;\n\n private String name;\n\n private String code;\n\n private String type;\n\n private Long parentId;\n\n private String path;\n\n private String redirect;\n\n private String icon;\n\n private String component;\n\n private String layout;\n\n private Boolean keepalive;\n\n private String method;\n\n private String description;\n\n private Boolean show;\n\n private Boolean enable;\n\n private Integer order;\n\n}"
},
{
"identifier": "RoleDto",
"path": "src/main/java/cn/dhbin/isme/pms/domain/dto/RoleDto.java",
"snippet": "@Data\npublic class RoleDto {\n\n private Long id;\n\n private String code;\n\n private String name;\n\n private Boolean enable;\n\n}"
},
{
"identifier": "RolePageDto",
"path": "src/main/java/cn/dhbin/isme/pms/domain/dto/RolePageDto.java",
"snippet": "@Data\npublic class RolePageDto {\n\n private Long id;\n\n private String code;\n\n private String name;\n\n private Boolean enable;\n\n private List<Long> permissionIds;\n\n}"
},
{
"identifier": "Role",
"path": "src/main/java/cn/dhbin/isme/pms/domain/entity/Role.java",
"snippet": "@Data\n@TableName(\"role\")\npublic class Role implements Convert {\n\n @TableId(type = IdType.AUTO)\n private Long id;\n\n private String code;\n\n private String name;\n\n private Boolean enable;\n\n}"
},
{
"identifier": "AddRolePermissionsRequest",
"path": "src/main/java/cn/dhbin/isme/pms/domain/request/AddRolePermissionsRequest.java",
"snippet": "@Data\npublic class AddRolePermissionsRequest {\n\n private Long id;\n\n private List<Long> permissionIds;\n}"
},
{
"identifier": "AddRoleUsersRequest",
"path": "src/main/java/cn/dhbin/isme/pms/domain/request/AddRoleUsersRequest.java",
"snippet": "@Data\npublic class AddRoleUsersRequest {\n\n private List<Long> userIds;\n\n}"
},
{
"identifier": "CreateRoleRequest",
"path": "src/main/java/cn/dhbin/isme/pms/domain/request/CreateRoleRequest.java",
"snippet": "@Data\npublic class CreateRoleRequest implements Convert {\n\n @NotBlank(message = \"角色编码不能为空\")\n private String code;\n\n @NotBlank(message = \"角色名不能为空\")\n private String name;\n\n private List<Long> permissionIds;\n\n private Boolean enable;\n\n}"
},
{
"identifier": "RemoveRoleUsersRequest",
"path": "src/main/java/cn/dhbin/isme/pms/domain/request/RemoveRoleUsersRequest.java",
"snippet": "@Data\npublic class RemoveRoleUsersRequest {\n\n private List<Long> userIds;\n\n}"
},
{
"identifier": "RolePageRequest",
"path": "src/main/java/cn/dhbin/isme/pms/domain/request/RolePageRequest.java",
"snippet": "@Data\n@EqualsAndHashCode(callSuper = true)\npublic class RolePageRequest extends PageRequest {\n\n private String name;\n\n private Boolean enable;\n\n}"
},
{
"identifier": "UpdateRoleRequest",
"path": "src/main/java/cn/dhbin/isme/pms/domain/request/UpdateRoleRequest.java",
"snippet": "@Data\npublic class UpdateRoleRequest {\n\n private String name;\n\n private Boolean enable;\n\n private List<Long> permissionIds;\n\n\n}"
},
{
"identifier": "RoleService",
"path": "src/main/java/cn/dhbin/isme/pms/service/RoleService.java",
"snippet": "public interface RoleService extends IService<Role> {\n\n /**\n * 根据用户id查询角色\n *\n * @param userId 用户id\n * @return 用户角色列表\n */\n List<Role> findRolesByUserId(Long userId);\n\n /**\n * 根据角色编码获取权限树\n *\n * @param roleCode 角色编码\n * @return 权限树\n */\n List<Tree<Long>> findRolePermissionsTree(String roleCode);\n\n /**\n * 根据角色编码获取角色\n *\n * @param roleCode 角色编码\n * @return 角色\n */\n Role findByCode(String roleCode);\n\n\n /**\n * 创建角色\n *\n * @param request req\n */\n void createRole(CreateRoleRequest request);\n\n /**\n * 分页查询\n *\n * @param request 请求\n * @return dto\n */\n Page<RolePageDto> queryPage(RolePageRequest request);\n\n /**\n * 查询角色权限\n *\n * @param id 角色id\n * @return 角色权限\n */\n List<PermissionDto> findRolePermissions(Long id);\n\n /**\n * 更新角色,当角色标识是管理员时,不给修改\n *\n * @param id 角色id\n * @param request req\n */\n void updateRole(Long id, UpdateRoleRequest request);\n\n /**\n * 删除角色,不能删除管理员\n *\n * @param id 角色id\n */\n void removeRole(Long id);\n\n /**\n * 给角色添加权限\n *\n * @param request req\n */\n void addRolePermissions(AddRolePermissionsRequest request);\n\n /**\n * 给角色分配用户\n *\n * @param roleId 角色id\n * @param request req\n */\n void addRoleUsers(Long roleId, AddRoleUsersRequest request);\n\n /**\n * 给角色移除用户\n *\n * @param roleId 角色id\n * @param request req\n */\n void removeRoleUsers(Long roleId, RemoveRoleUsersRequest request);\n}"
}
] | import cn.dev33.satoken.stp.StpUtil;
import cn.dhbin.isme.common.auth.RoleType;
import cn.dhbin.isme.common.auth.Roles;
import cn.dhbin.isme.common.auth.SaTokenConfigure;
import cn.dhbin.isme.common.response.Page;
import cn.dhbin.isme.common.response.R;
import cn.dhbin.isme.pms.domain.dto.PermissionDto;
import cn.dhbin.isme.pms.domain.dto.RoleDto;
import cn.dhbin.isme.pms.domain.dto.RolePageDto;
import cn.dhbin.isme.pms.domain.entity.Role;
import cn.dhbin.isme.pms.domain.request.AddRolePermissionsRequest;
import cn.dhbin.isme.pms.domain.request.AddRoleUsersRequest;
import cn.dhbin.isme.pms.domain.request.CreateRoleRequest;
import cn.dhbin.isme.pms.domain.request.RemoveRoleUsersRequest;
import cn.dhbin.isme.pms.domain.request.RolePageRequest;
import cn.dhbin.isme.pms.domain.request.UpdateRoleRequest;
import cn.dhbin.isme.pms.service.RoleService;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.util.ObjectUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PatchMapping;
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; | 2,964 | package cn.dhbin.isme.pms.controller;
/**
* 角色Controller
*/
@RestController
@RequestMapping("/role")
@RequiredArgsConstructor
@Tag(name = "角色")
public class RoleController {
private final RoleService roleService;
/**
* 新建角色
*
* @return R
*/
@PostMapping
@Roles(RoleType.SUPER_ADMIN)
@Operation(summary = "新增角色")
public R<Void> create(@RequestBody @Validated CreateRoleRequest request) {
roleService.createRole(request);
return R.ok();
}
/**
* 获取所有角色
*
* @return R
*/
@GetMapping
@Operation(summary = "获取所有角色")
public R<List<RoleDto>> findAll(
@RequestParam(value = "enable", required = false) Boolean enable
) {
List<RoleDto> roleDtoList = roleService.lambdaQuery().eq(ObjectUtil.isNotNull(enable), Role::getEnable, enable)
.list()
.stream()
.map(role -> role.convert(RoleDto.class))
.toList();
return R.ok(roleDtoList);
}
/**
* 分页
*
* @return R
*/
@GetMapping("/page")
@Operation(summary = "分页") | package cn.dhbin.isme.pms.controller;
/**
* 角色Controller
*/
@RestController
@RequestMapping("/role")
@RequiredArgsConstructor
@Tag(name = "角色")
public class RoleController {
private final RoleService roleService;
/**
* 新建角色
*
* @return R
*/
@PostMapping
@Roles(RoleType.SUPER_ADMIN)
@Operation(summary = "新增角色")
public R<Void> create(@RequestBody @Validated CreateRoleRequest request) {
roleService.createRole(request);
return R.ok();
}
/**
* 获取所有角色
*
* @return R
*/
@GetMapping
@Operation(summary = "获取所有角色")
public R<List<RoleDto>> findAll(
@RequestParam(value = "enable", required = false) Boolean enable
) {
List<RoleDto> roleDtoList = roleService.lambdaQuery().eq(ObjectUtil.isNotNull(enable), Role::getEnable, enable)
.list()
.stream()
.map(role -> role.convert(RoleDto.class))
.toList();
return R.ok(roleDtoList);
}
/**
* 分页
*
* @return R
*/
@GetMapping("/page")
@Operation(summary = "分页") | public R<Page<RolePageDto>> findPagination(RolePageRequest request) { | 2 | 2023-12-13 17:21:04+00:00 | 4k |
Earthcomputer/ModCompatChecker | root/src/main/java/net/earthcomputer/modcompatchecker/indexer/IndexerClassVisitor.java | [
{
"identifier": "AccessFlags",
"path": "root/src/main/java/net/earthcomputer/modcompatchecker/util/AccessFlags.java",
"snippet": "public final class AccessFlags {\n private final int flags;\n\n public AccessFlags(int flags) {\n this.flags = flags;\n }\n\n public AccessLevel accessLevel() {\n return AccessLevel.fromAsm(flags);\n }\n\n public boolean isStatic() {\n return (flags & Opcodes.ACC_STATIC) != 0;\n }\n\n public boolean isFinal() {\n return (flags & Opcodes.ACC_FINAL) != 0;\n }\n\n public boolean isAbstract() {\n return (flags & Opcodes.ACC_ABSTRACT) != 0;\n }\n\n public boolean isNative() {\n return (flags & Opcodes.ACC_NATIVE) != 0;\n }\n\n public boolean isVarArgs() {\n return (flags & Opcodes.ACC_VARARGS) != 0;\n }\n\n public boolean isInterface() {\n return (flags & Opcodes.ACC_INTERFACE) != 0;\n }\n\n public boolean isEnum() {\n return (flags & Opcodes.ACC_ENUM) != 0;\n }\n\n public int toAsm() {\n return flags;\n }\n\n public static AccessFlags fromReflectionModifiers(int modifiers) {\n return new AccessFlags(modifiers & (\n Opcodes.ACC_PUBLIC\n | Opcodes.ACC_PROTECTED\n | Opcodes.ACC_PRIVATE\n | Opcodes.ACC_STATIC\n | Opcodes.ACC_FINAL\n | Opcodes.ACC_ABSTRACT\n | Opcodes.ACC_NATIVE\n | Opcodes.ACC_INTERFACE\n ));\n }\n\n @Nullable\n public static AccessFlags parse(String str) {\n String[] parts = str.split(\"-\");\n AccessLevel accessLevel;\n try {\n accessLevel = AccessLevel.valueOf(parts[0].toUpperCase(Locale.ROOT));\n } catch (IllegalArgumentException e) {\n return null;\n }\n int flags = accessLevel.toAsm();\n for (int i = 1; i < parts.length; i++) {\n switch (parts[i]) {\n case \"static\" -> flags |= Opcodes.ACC_STATIC;\n case \"final\" -> flags |= Opcodes.ACC_FINAL;\n case \"abstract\" -> flags |= Opcodes.ACC_ABSTRACT;\n case \"native\" -> flags |= Opcodes.ACC_NATIVE;\n case \"varargs\" -> flags |= Opcodes.ACC_VARARGS;\n case \"interface\" -> flags |= Opcodes.ACC_INTERFACE;\n case \"enum\" -> flags |= Opcodes.ACC_ENUM;\n default -> {\n return null;\n }\n }\n }\n return new AccessFlags(flags);\n }\n\n @Override\n public String toString() {\n StringBuilder sb = new StringBuilder(accessLevel().getLowerName());\n if (isStatic()) {\n sb.append(\"-static\");\n }\n if (isFinal()) {\n sb.append(\"-final\");\n }\n if (isAbstract()) {\n sb.append(\"-abstract\");\n }\n if (isNative()) {\n sb.append(\"-native\");\n }\n if (isVarArgs()) {\n sb.append(\"-varargs\");\n }\n if (isInterface()) {\n sb.append(\"-interface\");\n }\n if (isEnum()) {\n sb.append(\"-enum\");\n }\n return sb.toString();\n }\n\n @Override\n public int hashCode() {\n return flags;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) {\n return true;\n }\n if (o == null || getClass() != o.getClass()) {\n return false;\n }\n AccessFlags that = (AccessFlags) o;\n return flags == that.flags;\n }\n}"
},
{
"identifier": "AsmUtil",
"path": "root/src/main/java/net/earthcomputer/modcompatchecker/util/AsmUtil.java",
"snippet": "public final class AsmUtil {\n public static final int API = getAsmApi();\n\n public static final String OBJECT = \"java/lang/Object\";\n public static final String ENUM = \"java/lang/Enum\";\n public static final String CONSTRUCTOR_NAME = \"<init>\";\n public static final String CLASS_INITIALIZER_NAME = \"<clinit>\";\n\n private AsmUtil() {\n }\n\n private static int getAsmApi() {\n try {\n int apiVersion = Opcodes.ASM4;\n for (Field field : Opcodes.class.getFields()) {\n if (field.getName().matches(\"ASM\\\\d+\")) {\n apiVersion = Math.max(apiVersion, field.getInt(null));\n }\n }\n return apiVersion;\n } catch (Exception e) {\n throw new RuntimeException(\"Failed to determine ASM API\", e);\n }\n }\n\n public static boolean isClassAccessible(String fromClass, String targetClass, int accessFlags) {\n return isClassAccessible(fromClass, targetClass, AccessLevel.fromAsm(accessFlags));\n }\n\n public static boolean isClassAccessible(String fromClass, String targetClass, AccessLevel accessLevel) {\n // JVMS 21 §5.4.4\n return accessLevel == AccessLevel.PUBLIC || areSamePackage(fromClass, targetClass);\n }\n\n public static boolean isMemberAccessible(Index index, String fromClass, String containingClassName, AccessLevel accessLevel) {\n IResolvedClass resolvedClass = index.findClass(containingClassName);\n return resolvedClass != null && isMemberAccessible(index, fromClass, containingClassName, resolvedClass, accessLevel);\n }\n\n public static boolean isMemberAccessible(Index index, String fromClass, String containingClassName, IResolvedClass containingClass, AccessLevel accessLevel) {\n // JVMS 21 §5.4.4\n\n switch (accessLevel) {\n case PUBLIC -> {\n return true;\n }\n case PROTECTED -> {\n if (isSubclass(index, fromClass, containingClassName) || areSamePackage(fromClass, containingClassName)) {\n return true;\n }\n }\n case PACKAGE -> {\n if (areSamePackage(fromClass, containingClassName)) {\n return true;\n }\n }\n }\n\n String nestHost = Objects.requireNonNullElse(containingClass.getNestHost(), containingClassName);\n if (nestHost.equals(fromClass)) {\n return true;\n }\n IResolvedClass resolvedNestHost = index.findClass(nestHost);\n return resolvedNestHost != null && resolvedNestHost.getNestMembers().contains(fromClass);\n }\n\n private static boolean isSubclass(Index index, String className, String superclass) {\n IResolvedClass clazz;\n while ((clazz = index.findClass(className)) != null) {\n if (superclass.equals(className)) {\n return true;\n }\n className = clazz.getSuperclass();\n }\n\n return false;\n }\n\n public static boolean areSamePackage(String a, String b) {\n int slashA = a.lastIndexOf('/');\n int slashB = b.lastIndexOf('/');\n return slashA == slashB && (slashA == -1 || a.startsWith(b.substring(0, slashB)));\n }\n\n @Nullable\n public static String getReferredClass(String typeDescriptor) {\n return getReferredClass(Type.getType(typeDescriptor));\n }\n\n @Nullable\n public static String getReferredClass(Type type) {\n if (type.getSort() == Type.ARRAY) {\n type = type.getElementType();\n }\n return type.getSort() == Type.OBJECT ? type.getInternalName() : null;\n }\n\n @Nullable\n public static Type toClassConstant(Object constant) {\n if (constant instanceof Type type) {\n return type.getSort() == Type.METHOD ? null : type;\n } else if (constant instanceof ConstantDynamic condy) {\n if (\"java/lang/invoke/ConstantBootstraps\".equals(condy.getBootstrapMethod().getOwner())\n && \"primitiveClass\".equals(condy.getBootstrapMethod().getName())\n && \"(Ljava/lang/invoke/MethodHandles$Lookup;Ljava/lang/String;Ljava/lang/Class;)Ljava/lang/Class;\".equals(condy.getBootstrapMethod().getDesc())\n ) {\n return Type.getType(condy.getName());\n }\n return null;\n } else {\n return null;\n }\n }\n}"
}
] | import net.earthcomputer.modcompatchecker.util.AccessFlags;
import net.earthcomputer.modcompatchecker.util.AsmUtil;
import org.jetbrains.annotations.Nullable;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.FieldVisitor;
import org.objectweb.asm.MethodVisitor;
import java.util.ArrayList;
import java.util.Arrays; | 2,187 | package net.earthcomputer.modcompatchecker.indexer;
public final class IndexerClassVisitor extends ClassVisitor {
private final Index index;
private String className;
@Nullable
private ClassIndex classIndex;
public IndexerClassVisitor(Index index) {
super(AsmUtil.API);
this.index = index;
}
@Override
public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) {
className = name; | package net.earthcomputer.modcompatchecker.indexer;
public final class IndexerClassVisitor extends ClassVisitor {
private final Index index;
private String className;
@Nullable
private ClassIndex classIndex;
public IndexerClassVisitor(Index index) {
super(AsmUtil.API);
this.index = index;
}
@Override
public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) {
className = name; | classIndex = index.addClass(name, new AccessFlags(access), superName, new ArrayList<>(Arrays.asList(interfaces))); | 0 | 2023-12-11 00:48:12+00:00 | 4k |
HzlGauss/bulls | src/main/java/com/bulls/qa/configuration/RequestConfigs.java | [
{
"identifier": "YamlPropertySourceFactory",
"path": "src/main/java/com/bulls/qa/common/YamlPropertySourceFactory.java",
"snippet": "public class YamlPropertySourceFactory implements PropertySourceFactory {\n private static final Logger logger = LoggerFactory.getLogger(YamlPropertySourceFactory.class);\n //Properties properties;\n int i = 0;\n int requestsNo;\n int pioneersNo;\n int globalVariableNo;\n Properties properties;\n\n @Override\n public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {\n Properties propertiesFromYaml = loadYamlIntoProperties(resource);\n append(propertiesFromYaml);\n String sourceName = name != null ? name : resource.getResource().getFilename();\n //logger.info(\"load source:{}\", sourceName);\n //logger.info(\"i={}\", i);\n\n i++;\n return new PropertiesPropertySource(sourceName, properties);\n\n /* List<PropertySource<?>> sources = new YamlPropertySourceLoader().load(resource.getResource().getFilename(), resource.getResource());\n return sources.get(0);*/\n }\n\n private void append(Properties newProperties) {\n if (i == 0) {\n properties = newProperties;\n Set<String> global = new HashSet<>();\n Set<String> pioneer = new HashSet<>();\n Set<String> request = new HashSet<>();\n for (String key : newProperties.stringPropertyNames()) {\n\n String[] ss = key.split(\"\\\\.\");\n if (ss.length != 3) {\n continue;\n }\n if (key.startsWith(\"api.globalVariable\")) {\n\n global.add(ss[1]);\n } else if (key.startsWith(\"api.pioneers\")) {\n\n pioneer.add(ss[1]);\n } else if (key.startsWith(\"api.requests\")) {\n\n request.add(ss[1]);\n }\n }\n globalVariableNo = global.size() - 1;\n pioneersNo = pioneer.size() - 1;\n requestsNo = request.size() - 1;\n } else {\n Map<String, String> map = new HashMap<>();\n\n Object[] keys = newProperties.stringPropertyNames().toArray();\n Arrays.sort(newProperties.stringPropertyNames().toArray());\n\n for (Object keyo : keys) {\n\n String key = (String) keyo;\n String value = newProperties.getProperty(key);\n String[] ss = key.split(\"\\\\.\");\n String newKey = null;\n if (map.containsKey(ss[1])) {\n newKey = ss[0] + \".\" + map.get(ss[1]) + \".\" + ss[2];\n } else {\n if (key.startsWith(\"api.globalVariable\")) {\n globalVariableNo++;\n map.put(ss[1], globalVariableNo + \"\");\n newKey = ss[0] + \".globalVariable[\" + globalVariableNo + \"].\" + ss[2];\n } else if (key.startsWith(\"api.pioneers\")) {\n pioneersNo++;\n map.put(ss[1], pioneersNo + \"\");\n newKey = ss[0] + \"pioneers.[\" + pioneersNo + \"].\" + ss[2];\n } else if (key.startsWith(\"api.requests\")) {\n requestsNo++;\n map.put(ss[1], requestsNo + \"\");\n newKey = ss[0] + \".requests[\" + requestsNo + \"].\" + ss[2];\n }\n }\n if (StringUtils.isNotEmpty(newKey)) {\n //logger.info(key);\n //logger.info(newKey);\n String[] ss1 = key.split(\"[\\\\[,\\\\]]\");\n newKey = ss1[0] + \"[\" + map.get(ss[1]) + \"]\" + ss1[2];\n /*logger.info(newKey);\n logger.info(\"i={}\", i);\n logger.info(\"{}:{}\", key, newProperties.getProperty(key));\n logger.info(\"{}:{}\", newKey, newProperties.getProperty(key));*/\n properties.setProperty(newKey, newProperties.getProperty(key));\n //newProperties.setProperty(newKey, newProperties.getProperty(key));\n //newProperties.remove(key);\n }\n }\n\n }\n }\n\n private Properties loadYamlIntoProperties(EncodedResource resource) throws FileNotFoundException {\n try {\n YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();\n factory.setResources(resource.getResource());\n factory.afterPropertiesSet();\n return factory.getObject();\n } catch (IllegalStateException e) {\n // for ignoreResourceNotFound\n Throwable cause = e.getCause();\n if (cause instanceof FileNotFoundException)\n throw (FileNotFoundException) e.getCause();\n throw e;\n }\n }\n}"
},
{
"identifier": "PioneerService",
"path": "src/main/java/com/bulls/qa/service/PioneerService.java",
"snippet": "@Service\npublic class PioneerService {\n @Autowired\n private RequestConfigs requestConfigs;\n @Value(\"${miria.cookie:abc}\")\n String buildinCookie;\n\n @Autowired\n private Environment env;\n\n private static Environment staticEnv;\n\n public static String getProperty(String key) {\n return staticEnv.getProperty(key);\n }\n\n public static void handle(PioneerConfig pioneerConfig, RequestConfigs requestConfigs) {\n Request request = Request.getInstance(pioneerConfig);\n Response response = request.doRequest();\n String cookiesName = null;\n Map<String, String> cookies = new HashMap<>();\n for (Map<String, String> extractor : pioneerConfig.getExtractors()) {\n String name = extractor.get(\"name\");\n String value = extractor.get(\"value\");\n if (name.equals(\"appendCookie\")) {\n String[] ss = value.split(\"=\");\n if (ss.length == 2) {\n if (StringUtils.isNotEmpty(ss[1])) {\n //通过配置变量引用添加\n if (ss[1].startsWith(\"$\")) {\n String k = ss[1].replace(\"$\", \"\");\n if (cookies != null) {\n Object v = requestConfigs.getGlobalVariable(k);\n cookies.put(ss[0], v.toString());\n requestConfigs.setGlobalVariable(cookiesName, cookies);\n }\n //直接添加\n } else {\n cookies.put(ss[0], ss[1]);\n requestConfigs.setGlobalVariable(cookiesName, cookies);\n }\n }\n }\n } else if (value.equals(\"cookies\")) {\n cookies.putAll(response.getCookies());\n if (requestConfigs.getGlobalVariable(name) != null) {\n ((Map) requestConfigs.getGlobalVariable(name)).putAll(cookies);\n } else {\n requestConfigs.setGlobalVariable(name, cookies);\n }\n cookiesName = name;\n } else if (StringUtils.isNotEmpty(value) && value.startsWith(\"$.\")) {\n value = value.replace(\"$.\", \"\");\n Object o = response.jsonPath().get(value);\n\n if (o != null) {\n //System.out.println(o);\n requestConfigs.setGlobalVariable(name, o);\n }\n }\n }\n }\n\n @PostConstruct\n private void prepareAction() {\n //initRequest();\n PioneerService.staticEnv = this.env;\n if (Request.getRequestConfigs() == null) {\n //return;\n Request.setRequestConfigs(requestConfigs);\n }\n List<PioneerConfig> pioneers = requestConfigs.getPioneers();\n if (pioneers == null) {\n return;\n }\n Collections.sort(pioneers, new Comparator<PioneerConfig>() {\n @Override\n public int compare(PioneerConfig o1, PioneerConfig o2) {\n return o1.getPriority() - o2.getPriority();\n }\n });\n for (PioneerConfig pioneerConfig : pioneers) {\n handle(pioneerConfig, this.requestConfigs);\n }\n }\n\n //多场景支持\n private void initRequest() {\n if (StringUtils.isNotEmpty(buildinCookie)) {\n System.out.println(buildinCookie);\n RestAssured.filters(new AuthFilter() {\n @Override\n public Response filter(FilterableRequestSpecification requestSpec, FilterableResponseSpecification responseSpec, FilterContext ctx) {\n if (buildinCookie.contains(\"=\") || buildinCookie.contains(\":\")) {\n String[] ss = buildinCookie.split(\"=|:\");\n requestSpec.cookies(ss[0], ss[1]);\n }\n return ctx.next(requestSpec, responseSpec);\n }\n });\n }\n\n }\n}"
}
] | import com.bulls.qa.common.YamlPropertySourceFactory;
import com.bulls.qa.service.PioneerService;
import lombok.AccessLevel;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties; | 2,377 | package com.bulls.qa.configuration;
@Data
@Configuration
@Component
@PropertySource(factory = YamlPropertySourceFactory.class, value = {"testerhome.yml"})
//@PropertySource(factory = YamlPropertySourceFactory.class, value = {"interface_*.yml"})
//@PropertySource(factory = YamlPropertySourceFactory.class, value = {"request-copy.yml"},name = "b" ,ignoreResourceNotFound = true)
@ConfigurationProperties(prefix = "api", ignoreInvalidFields = true, ignoreUnknownFields = true)
//@ConfigurationProperties(ignoreUnknownFields = false)
public class RequestConfigs {
@Setter
@Getter
private List<PioneerConfig> pioneers;
//@Setter
//@Getter
private List<RequestConfig> requests;
@Setter(AccessLevel.PRIVATE)
@Getter(AccessLevel.PRIVATE)
private Map<String, Object> globalVariableMap = new HashMap<>();
private List<Map<String, String>> globalVariables;
@Setter(AccessLevel.PRIVATE)
@Getter(AccessLevel.PRIVATE)
private static Map<String, RequestConfig> requestMap = new HashMap<>();
@Autowired
Environment environment;
private Properties properties;
public Map<String, String> reLogin(String cookiesName) {
for (PioneerConfig pioneerConfig : pioneers) {
for (Map<String, String> map : pioneerConfig.getExtractors()) {
System.out.println(map.keySet());
if (map.get("name").equals(cookiesName)) { | package com.bulls.qa.configuration;
@Data
@Configuration
@Component
@PropertySource(factory = YamlPropertySourceFactory.class, value = {"testerhome.yml"})
//@PropertySource(factory = YamlPropertySourceFactory.class, value = {"interface_*.yml"})
//@PropertySource(factory = YamlPropertySourceFactory.class, value = {"request-copy.yml"},name = "b" ,ignoreResourceNotFound = true)
@ConfigurationProperties(prefix = "api", ignoreInvalidFields = true, ignoreUnknownFields = true)
//@ConfigurationProperties(ignoreUnknownFields = false)
public class RequestConfigs {
@Setter
@Getter
private List<PioneerConfig> pioneers;
//@Setter
//@Getter
private List<RequestConfig> requests;
@Setter(AccessLevel.PRIVATE)
@Getter(AccessLevel.PRIVATE)
private Map<String, Object> globalVariableMap = new HashMap<>();
private List<Map<String, String>> globalVariables;
@Setter(AccessLevel.PRIVATE)
@Getter(AccessLevel.PRIVATE)
private static Map<String, RequestConfig> requestMap = new HashMap<>();
@Autowired
Environment environment;
private Properties properties;
public Map<String, String> reLogin(String cookiesName) {
for (PioneerConfig pioneerConfig : pioneers) {
for (Map<String, String> map : pioneerConfig.getExtractors()) {
System.out.println(map.keySet());
if (map.get("name").equals(cookiesName)) { | PioneerService.handle(pioneerConfig, this); | 1 | 2023-12-14 06:54:24+00:00 | 4k |
wkgcass/jdkman | src/main/java/io/vproxy/jdkman/action/RefreshAction.java | [
{
"identifier": "JDKInfo",
"path": "src/main/java/io/vproxy/jdkman/entity/JDKInfo.java",
"snippet": "public class JDKInfo implements JSONObject, Comparable<JDKInfo> {\n private String id;\n private int majorVersion;\n private int minorVersion;\n private int patchVersion;\n private String buildVersion; // nullable\n private String fullVersion;\n private String implementor; // nullable\n private String home;\n\n public static final Rule<JDKInfo> rule = new ObjectRule<>(JDKInfo::new)\n .put(\"id\", JDKInfo::setId, StringRule.get())\n .put(\"majorVersion\", JDKInfo::setMajorVersion, IntRule.get())\n .put(\"minorVersion\", JDKInfo::setMinorVersion, IntRule.get())\n .put(\"patchVersion\", JDKInfo::setPatchVersion, IntRule.get())\n .put(\"buildVersion\", JDKInfo::setBuildVersion, NullableStringRule.get())\n .put(\"fullVersion\", JDKInfo::setFullVersion, StringRule.get())\n .put(\"implementor\", JDKInfo::setImplementor, NullableStringRule.get())\n .put(\"home\", JDKInfo::setHome, StringRule.get());\n\n @Override\n public JSON.Object toJson() {\n return new ObjectBuilder()\n .put(\"id\", id)\n .put(\"majorVersion\", majorVersion)\n .put(\"minorVersion\", minorVersion)\n .put(\"patchVersion\", patchVersion)\n .put(\"buildVersion\", buildVersion)\n .put(\"fullVersion\", fullVersion)\n .put(\"implementor\", implementor)\n .put(\"home\", home)\n .build();\n }\n\n public JDKInfo() {\n }\n\n public JDKInfo(JDKInfoMatcher m) {\n this.majorVersion = m.majorVersion;\n this.minorVersion = m.minorVersion == null ? 0 : m.minorVersion;\n this.patchVersion = m.patchVersion == null ? 0 : m.patchVersion;\n this.buildVersion = m.buildVersion;\n this.fullVersion = m.fullVersion;\n this.implementor = m.implementor;\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 int getMajorVersion() {\n return majorVersion;\n }\n\n public void setMajorVersion(int majorVersion) {\n this.majorVersion = majorVersion;\n }\n\n public int getMinorVersion() {\n return minorVersion;\n }\n\n public void setMinorVersion(int minorVersion) {\n this.minorVersion = minorVersion;\n }\n\n public int getPatchVersion() {\n return patchVersion;\n }\n\n public void setPatchVersion(int patchVersion) {\n this.patchVersion = patchVersion;\n }\n\n public String getBuildVersion() {\n return buildVersion;\n }\n\n public void setBuildVersion(String buildVersion) {\n this.buildVersion = buildVersion;\n }\n\n public String getFullVersion() {\n return fullVersion;\n }\n\n public void setFullVersion(String fullVersion) {\n this.fullVersion = fullVersion;\n }\n\n public String getImplementor() {\n return implementor;\n }\n\n public void setImplementor(String implementor) {\n this.implementor = implementor;\n }\n\n public String getHome() {\n return home;\n }\n\n public void setHome(String home) {\n this.home = home;\n }\n\n @Override\n public int compareTo(JDKInfo that) {\n if (majorVersion > that.majorVersion)\n return 1;\n if (majorVersion < that.majorVersion)\n return -1;\n if (minorVersion > that.minorVersion)\n return 1;\n if (minorVersion < that.minorVersion)\n return -1;\n if (patchVersion > that.patchVersion)\n return 1;\n if (patchVersion < that.patchVersion)\n return -1;\n if (buildVersion != null && that.buildVersion == null)\n return 1;\n if (buildVersion == null && that.buildVersion != null)\n return -1;\n if (implementor != null && that.implementor == null)\n return 1;\n if (implementor == null && that.implementor != null)\n return -1;\n return 0;\n }\n\n @SuppressWarnings(\"StringTemplateMigration\")\n @Override\n public String toString() {\n return \"JDKInfo{\" +\n \"id=\" + (id == null ? \"null\" : (\"'\" + id + \"'\")) +\n \", majorVersion=\" + majorVersion +\n \", minorVersion=\" + minorVersion +\n \", patchVersion=\" + patchVersion +\n \", buildVersion=\" + (buildVersion == null ? \"null\" : (\"'\" + buildVersion + \"'\")) +\n \", fullVersion=\" + (fullVersion == null ? \"null\" : (\"'\" + fullVersion + \"'\")) +\n \", implementor=\" + (implementor == null ? \"null\" : (\"'\" + implementor + \"'\")) +\n \", home=\" + (home == null ? \"null\" : (\"'\" + home + \"'\")) +\n '}';\n }\n}"
},
{
"identifier": "JDKManConfig",
"path": "src/main/java/io/vproxy/jdkman/entity/JDKManConfig.java",
"snippet": "public class JDKManConfig implements JSONObject {\n private String defaultJDK;\n private List<JDKInfo> jdks;\n\n public static final Rule<JDKManConfig> rule = new ObjectRule<>(() -> new JDKManConfig(null))\n .put(\"defaultJDK\", JDKManConfig::setDefaultJDK, NullableStringRule.get())\n .put(\"jdks\", JDKManConfig::setJdks, new ArrayRule<>(ArrayList::new, List::add, JDKInfo.rule));\n\n @Override\n public JSON.Object toJson() {\n return new ObjectBuilder()\n .put(\"defaultJDK\", defaultJDK)\n .putArray(\"jdks\", a -> jdks.forEach(e -> a.addInst(e.toJson())))\n .build();\n }\n\n public JDKManConfig() {\n jdks = new ArrayList<>();\n }\n\n private JDKManConfig(@SuppressWarnings(\"unused\") Void unused) {\n }\n\n public String getDefaultJDK() {\n return defaultJDK;\n }\n\n public void setDefaultJDK(String defaultJDK) {\n this.defaultJDK = defaultJDK;\n }\n\n public List<JDKInfo> getJdks() {\n return jdks;\n }\n\n public void setJdks(List<JDKInfo> jdks) {\n this.jdks = jdks;\n }\n}"
}
] | import io.vproxy.base.util.LogType;
import io.vproxy.base.util.Logger;
import io.vproxy.jdkman.entity.JDKInfo;
import io.vproxy.jdkman.entity.JDKManConfig;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays; | 1,768 | package io.vproxy.jdkman.action;
public class RefreshAction implements Action {
@Override
public String validate(String[] options) {
if (options.length == 0) {
return null;
}
return STR."unknown options for `refresh`: \{Arrays.toString(options)}";
}
@Override
public boolean execute(JDKManConfig config, String[] options) {
var homes = new ArrayList<String>(); | package io.vproxy.jdkman.action;
public class RefreshAction implements Action {
@Override
public String validate(String[] options) {
if (options.length == 0) {
return null;
}
return STR."unknown options for `refresh`: \{Arrays.toString(options)}";
}
@Override
public boolean execute(JDKManConfig config, String[] options) {
var homes = new ArrayList<String>(); | JDKInfo oldDefault = null; | 0 | 2023-12-07 04:55:35+00:00 | 4k |
DantSu/studio | core/src/main/java/studio/core/v1/utils/PackAssetsCompression.java | [
{
"identifier": "StageNode",
"path": "core/src/main/java/studio/core/v1/model/StageNode.java",
"snippet": "public class StageNode extends Node {\n\n private String uuid;\n private ImageAsset image;\n private AudioAsset audio;\n private Transition okTransition;\n private Transition homeTransition;\n private ControlSettings controlSettings;\n\n public StageNode(String uuid, ImageAsset image, AudioAsset audio, Transition okTransition, Transition homeTransition, ControlSettings controlSettings, EnrichedNodeMetadata enriched) {\n super(enriched);\n this.uuid = uuid;\n this.image = image;\n this.audio = audio;\n this.okTransition = okTransition;\n this.homeTransition = homeTransition;\n this.controlSettings = controlSettings;\n }\n\n public String getUuid() {\n return uuid;\n }\n\n public void setUuid(String uuid) {\n this.uuid = uuid;\n }\n\n public ImageAsset getImage() {\n return image;\n }\n\n public void setImage(ImageAsset image) {\n this.image = image;\n }\n\n public AudioAsset getAudio() {\n return audio;\n }\n\n public void setAudio(AudioAsset audio) {\n this.audio = audio;\n }\n\n public Transition getOkTransition() {\n return okTransition;\n }\n\n public void setOkTransition(Transition okTransition) {\n this.okTransition = okTransition;\n }\n\n public Transition getHomeTransition() {\n return homeTransition;\n }\n\n public void setHomeTransition(Transition homeTransition) {\n this.homeTransition = homeTransition;\n }\n\n public ControlSettings getControlSettings() {\n return controlSettings;\n }\n\n public void setControlSettings(ControlSettings controlSettings) {\n this.controlSettings = controlSettings;\n }\n}"
},
{
"identifier": "StoryPack",
"path": "core/src/main/java/studio/core/v1/model/StoryPack.java",
"snippet": "public class StoryPack {\n\n private String uuid;\n private boolean factoryDisabled;\n private short version;\n private List<StageNode> stageNodes;\n private EnrichedPackMetadata enriched;\n private boolean nightModeAvailable = false;\n\n public String getUuid() {\n return uuid;\n }\n\n public void setUuid(String uuid) {\n this.uuid = uuid;\n }\n\n public boolean isFactoryDisabled() {\n return factoryDisabled;\n }\n\n public void setFactoryDisabled(boolean factoryDisabled) {\n this.factoryDisabled = factoryDisabled;\n }\n\n public short getVersion() {\n return version;\n }\n\n public void setVersion(short version) {\n this.version = version;\n }\n\n public List<StageNode> getStageNodes() {\n return stageNodes;\n }\n\n public void setStageNodes(List<StageNode> stageNodes) {\n this.stageNodes = stageNodes;\n }\n\n public EnrichedPackMetadata getEnriched() {\n return enriched;\n }\n\n public void setEnriched(EnrichedPackMetadata enriched) {\n this.enriched = enriched;\n }\n\n public boolean isNightModeAvailable() {\n return nightModeAvailable;\n }\n\n public void setNightModeAvailable(boolean nightModeAvailable) {\n this.nightModeAvailable = nightModeAvailable;\n }\n}"
},
{
"identifier": "AudioAsset",
"path": "core/src/main/java/studio/core/v1/model/asset/AudioAsset.java",
"snippet": "public class AudioAsset {\n\n private AudioType type;\n private byte[] rawData;\n\n public AudioAsset(AudioType type, byte[] rawData) {\n super();\n this.type = type;\n this.rawData = rawData;\n }\n\n public AudioType getType() {\n return type;\n }\n\n public void setType(AudioType type) {\n this.type = type;\n }\n\n public byte[] getRawData() {\n return rawData;\n }\n\n public void setRawData(byte[] rawData) {\n this.rawData = rawData;\n }\n\n}"
},
{
"identifier": "AudioType",
"path": "core/src/main/java/studio/core/v1/model/asset/AudioType.java",
"snippet": "public enum AudioType {\n\n WAV(\"audio/x-wav\", \".wav\"), MPEG(\"audio/mpeg\", \".mp3\"), MP3(\"audio/mp3\", \".mp3\"), OGG(\"audio/ogg\", \".ogg\", \".oga\");\n\n private final String mime;\n private final List<String> extensions;\n\n private AudioType(String mime, String... extensions) {\n this.mime = mime;\n this.extensions = Arrays.asList(extensions);\n }\n\n public static AudioType fromExtension(String extension) {\n for (AudioType e : values()) {\n if (e.extensions.contains(extension)) {\n return e;\n }\n }\n return null;\n }\n\n public static AudioType fromMime(String mime) {\n for (AudioType e : values()) {\n if (e.mime.equals(mime)) {\n return e;\n }\n }\n return null;\n }\n\n public String getMime() {\n return mime;\n }\n\n public List<String> getExtensions() {\n return extensions;\n }\n\n public String getFirstExtension() {\n return extensions.get(0);\n }\n}"
},
{
"identifier": "ImageAsset",
"path": "core/src/main/java/studio/core/v1/model/asset/ImageAsset.java",
"snippet": "public class ImageAsset {\n\n private ImageType type;\n private byte[] rawData;\n\n public ImageAsset(ImageType type, byte[] rawData) {\n super();\n this.type = type;\n this.rawData = rawData;\n }\n\n public ImageType getType() {\n return type;\n }\n\n public void setType(ImageType imageType) {\n this.type = imageType;\n }\n\n public byte[] getRawData() {\n return rawData;\n }\n\n public void setRawData(byte[] rawData) {\n this.rawData = rawData;\n }\n\n}"
},
{
"identifier": "ImageType",
"path": "core/src/main/java/studio/core/v1/model/asset/ImageType.java",
"snippet": "public enum ImageType {\n\n BMP(\"image/bmp\", \".bmp\"), PNG(\"image/png\", \".png\"), JPEG(\"image/jpeg\", \".jpg\", \".jpeg\");\n\n private final String mime;\n private final List<String> extensions;\n\n private ImageType(String mime, String... extensions) {\n this.mime = mime;\n this.extensions = Arrays.asList(extensions);\n }\n\n public static ImageType fromExtension(String extension) {\n for (ImageType e : values()) {\n if (e.extensions.contains(extension)) {\n return e;\n }\n }\n return null;\n }\n\n public static ImageType fromMime(String mime) {\n for (ImageType e : values()) {\n if (e.mime.equals(mime)) {\n return e;\n }\n }\n return null;\n }\n\n public String getMime() {\n return mime;\n }\n\n public List<String> getExtensions() {\n return extensions;\n }\n\n public String getFirstExtension() {\n return extensions.get(0);\n }\n\n}"
},
{
"identifier": "StoppingConsumer",
"path": "core/src/main/java/studio/core/v1/utils/stream/StoppingConsumer.java",
"snippet": "public interface StoppingConsumer<T> {\n\n void accept(T t) throws StoryTellerException;\n\n static <T> Consumer<T> stopped(StoppingConsumer<T > consumer) {\n return t -> {\n try {\n consumer.accept(t);\n } catch (StoryTellerException e) {\n // Stop current parallel stream (if any)\n if(!ForkJoinPool.commonPool().isQuiescent()) {\n ForkJoinPool.commonPool().awaitQuiescence(10, TimeUnit.SECONDS);\n }\n // re-throw exception\n throw e;\n }\n };\n }\n}"
},
{
"identifier": "ThrowingFunction",
"path": "core/src/main/java/studio/core/v1/utils/stream/ThrowingFunction.java",
"snippet": "@FunctionalInterface\npublic interface ThrowingFunction<T, R, E extends Exception> {\n\n R apply(T t) throws E;\n\n static <T, R, E extends Exception> Function<T, R> unchecked(ThrowingFunction<T, R, E> f) {\n return t -> {\n try {\n return f.apply(t);\n } catch (Exception e) {\n // custom RuntimeException\n throw new StoryTellerException(e);\n }\n };\n }\n}"
}
] | import java.io.ByteArrayInputStream;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import studio.core.v1.model.StageNode;
import studio.core.v1.model.StoryPack;
import studio.core.v1.model.asset.AudioAsset;
import studio.core.v1.model.asset.AudioType;
import studio.core.v1.model.asset.ImageAsset;
import studio.core.v1.model.asset.ImageType;
import studio.core.v1.utils.stream.StoppingConsumer;
import studio.core.v1.utils.stream.ThrowingFunction; | 2,307 | /*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package studio.core.v1.utils;
public class PackAssetsCompression {
private static final Logger LOGGER = LogManager.getLogger(PackAssetsCompression.class);
private PackAssetsCompression() {
throw new IllegalStateException("Utility class");
}
public static boolean hasCompressedAssets(StoryPack pack) { | /*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package studio.core.v1.utils;
public class PackAssetsCompression {
private static final Logger LOGGER = LogManager.getLogger(PackAssetsCompression.class);
private PackAssetsCompression() {
throw new IllegalStateException("Utility class");
}
public static boolean hasCompressedAssets(StoryPack pack) { | for (StageNode node : pack.getStageNodes()) { | 0 | 2023-12-14 15:08:35+00:00 | 4k |
cworld1/notie | app/src/main/java/com/cworld/notie/MainActivity.java | [
{
"identifier": "NoteItemAdapter",
"path": "app/src/main/java/com/cworld/notie/adapter/NoteItemAdapter.java",
"snippet": "public class NoteItemAdapter extends RecyclerView.Adapter<NoteItemAdapter.NoteViewHolder> {\r\n private final List<NoteModel> noteList;\r\n private OnItemClickListener listener;\r\n private boolean isSelectionMode = false;\r\n private final List<Integer> selectedItems = new ArrayList<>();\r\n\r\n public NoteItemAdapter(List<NoteModel> noteList) {\r\n this.noteList = noteList;\r\n }\r\n\r\n public void setOnItemClickListener(OnItemClickListener listener) {\r\n this.listener = listener;\r\n }\r\n\r\n @NonNull\r\n @Override\r\n public NoteViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {\r\n View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_note, parent, false);\r\n return new NoteViewHolder(itemView);\r\n }\r\n\r\n @Override\r\n public void onBindViewHolder(NoteViewHolder holder, int position) {\r\n NoteModel currentNote = noteList.get(position);\r\n // format data to show\r\n String formattedTime = FormatHelper.time(currentNote.getEditTime());\r\n String formattedTitle = FormatHelper.text(currentNote.getTitle());\r\n String formattedContent = FormatHelper.text(currentNote.getContent());\r\n holder.titleTextView.setText(formattedTitle);\r\n holder.contentTextView.setText(formattedContent);\r\n holder.editTimeTextView.setText(formattedTime);\r\n\r\n // for selection mode\r\n if (isSelectionMode) {\r\n holder.checkbox.setVisibility(View.VISIBLE);\r\n holder.checkbox.setOnCheckedChangeListener(\r\n (buttonView, isChecked) -> toggleSelection(holder.getAdapterPosition()));\r\n holder.itemView.setOnClickListener(v -> holder.checkbox.toggle());\r\n return;\r\n }\r\n\r\n // for normal mode\r\n holder.checkbox.setVisibility(View.GONE);\r\n holder.itemView.setOnClickListener(v -> {\r\n if (listener != null) {\r\n listener.onItemClick(currentNote);\r\n }\r\n });\r\n }\r\n\r\n @Override\r\n public int getItemCount() {\r\n return noteList.size();\r\n }\r\n\r\n public static class NoteViewHolder extends RecyclerView.ViewHolder {\r\n public TextView titleTextView;\r\n public TextView contentTextView;\r\n public TextView editTimeTextView;\r\n public CheckBox checkbox;\r\n\r\n public NoteViewHolder(View itemView) {\r\n super(itemView);\r\n titleTextView = itemView.findViewById(R.id.titleTextView);\r\n contentTextView = itemView.findViewById(R.id.contentTextView);\r\n editTimeTextView = itemView.findViewById(R.id.editTimeTextView);\r\n checkbox = itemView.findViewById(R.id.checkbox_note);\r\n }\r\n }\r\n\r\n public interface OnItemClickListener {\r\n void onItemClick(NoteModel note);\r\n }\r\n\r\n @SuppressLint(\"NotifyDataSetChanged\")\r\n public void setSelectionMode(boolean selectionMode) {\r\n isSelectionMode = selectionMode;\r\n notifyDataSetChanged();\r\n }\r\n\r\n public void clearSelection() {\r\n selectedItems.clear();\r\n }\r\n\r\n public void toggleSelection(int position) {\r\n if (selectedItems.contains(position)) {\r\n selectedItems.remove(Integer.valueOf(position));\r\n } else {\r\n selectedItems.add(position);\r\n }\r\n }\r\n\r\n public List<NoteModel> getSelectedItems() {\r\n List<NoteModel> selectedNotes = new ArrayList<>();\r\n for (int position : selectedItems) {\r\n selectedNotes.add(noteList.get(position));\r\n }\r\n return selectedNotes;\r\n }\r\n}\r"
},
{
"identifier": "NoteModel",
"path": "app/src/main/java/com/cworld/notie/adapter/NoteModel.java",
"snippet": "public class NoteModel {\r\n private final String title;\r\n private final String content;\r\n private final Date editTime;\r\n\r\n public NoteModel(String title, String content, Date editTime) {\r\n this.title = title;\r\n this.content = content;\r\n this.editTime = editTime;\r\n }\r\n\r\n public String getTitle() {\r\n return title;\r\n }\r\n\r\n public String getContent() {\r\n return content;\r\n }\r\n\r\n public Date getEditTime() {\r\n return editTime;\r\n }\r\n}\r"
},
{
"identifier": "Hitokoto",
"path": "app/src/main/java/com/cworld/notie/util/Hitokoto.java",
"snippet": "public class Hitokoto {\r\n static int maxLength = 16;\r\n static String apiUrl = \"https://v1.hitokoto.cn?max_length=\" + maxLength;\r\n\r\n public static String fetchPoem() {\r\n StringBuilder result = new StringBuilder();\r\n\r\n try {\r\n URL url = new URL(apiUrl + \"&c=i\");\r\n HttpURLConnection connection = (HttpURLConnection) url.openConnection();\r\n connection.setRequestMethod(\"GET\");\r\n\r\n int responseCode = connection.getResponseCode();\r\n if (responseCode == HttpURLConnection.HTTP_OK) {\r\n BufferedReader reader = new BufferedReader(\r\n new InputStreamReader(connection.getInputStream()));\r\n\r\n String line;\r\n while ((line = reader.readLine()) != null) {\r\n result.append(line);\r\n }\r\n\r\n reader.close();\r\n }\r\n } catch (IOException e) {\r\n e.printStackTrace();\r\n }\r\n\r\n return parseHitokotoJson(result.toString());\r\n }\r\n\r\n private static String parseHitokotoJson(String resultJson) {\r\n try {\r\n JSONObject jsonObject = new JSONObject(resultJson);\r\n return jsonObject.getString(\"hitokoto\");\r\n } catch (JSONException e) {\r\n e.printStackTrace();\r\n return null;\r\n }\r\n }\r\n}\r"
},
{
"identifier": "NoteHelper",
"path": "app/src/main/java/com/cworld/notie/util/NoteHelper.java",
"snippet": "public class NoteHelper {\r\n private static String path;\r\n @SuppressLint(\"StaticFieldLeak\")\r\n private static Context context;\r\n\r\n public NoteHelper(Context context, String path) {\r\n NoteHelper.context = context;\r\n NoteHelper.path = path;\r\n }\r\n\r\n public List<NoteModel> getAllNotes() {\r\n List<NoteModel> notes = new ArrayList<>();\r\n\r\n try {\r\n File directory = new File(context.getExternalFilesDir(null), path);\r\n File[] files = directory.listFiles();\r\n if (files != null) {\r\n for (File file : files) {\r\n String noteName = file.getName().replace(\".txt\", \"\");\r\n String noteContent = getNoteContent(file);\r\n Date lastEditedTime = new Date(file.lastModified());\r\n NoteModel note = new NoteModel(noteName, noteContent, lastEditedTime);\r\n notes.add(note);\r\n }\r\n }\r\n } catch (Exception ex) {\r\n Log.d(\"fileAccess\", \"读取笔记文件失败\");\r\n ex.printStackTrace();\r\n }\r\n\r\n return notes;\r\n }\r\n\r\n public static void setNote(NoteModel note) {\r\n try {\r\n File directory = new File(context.getExternalFilesDir(null), path);\r\n if (!directory.exists()) {\r\n directory.mkdirs();\r\n }\r\n\r\n File file = new File(directory, note.getTitle() + \".txt\");\r\n FileOutputStream fos = new FileOutputStream(file);\r\n fos.write(note.getContent().getBytes());\r\n fos.close();\r\n } catch (IOException ex) {\r\n Log.d(\"fileAccess\", \"写文件失败\");\r\n ex.printStackTrace();\r\n }\r\n }\r\n\r\n\r\n public static void setNote(NoteModel note, String originTitle) {\r\n deleteSpecifyNote(originTitle);\r\n setNote(note);\r\n }\r\n\r\n public static void deleteNote(NoteModel note) {\r\n deleteSpecifyNote(note.getTitle());\r\n }\r\n\r\n public static void deleteNote(String title) {\r\n deleteSpecifyNote(title);\r\n }\r\n\r\n private static void deleteSpecifyNote(String title) {\r\n try {\r\n File directory = new File(context.getExternalFilesDir(null), path);\r\n File file = new File(directory, title + \".txt\");\r\n if (file.exists()) {\r\n file.delete();\r\n }\r\n } catch (Exception ex) {\r\n ex.printStackTrace();\r\n }\r\n }\r\n\r\n private String getNoteContent(File file) {\r\n try {\r\n FileInputStream fis = new FileInputStream(file);\r\n Scanner scanner = new Scanner(fis);\r\n StringBuilder content = new StringBuilder();\r\n while (scanner.hasNextLine()) {\r\n String line = scanner.nextLine();\r\n Log.d(\"fileAccess\", line);\r\n content.append(line).append(\"\\n\");\r\n }\r\n scanner.close();\r\n fis.close();\r\n return content.toString();\r\n } catch (IOException ex) {\r\n Log.d(\"fileAccess\", \"读文件失败\");\r\n ex.printStackTrace();\r\n }\r\n return null;\r\n }\r\n}"
}
] | import com.cworld.notie.adapter.NoteItemAdapter;
import com.cworld.notie.adapter.NoteModel;
import com.cworld.notie.util.Hitokoto;
import com.cworld.notie.util.NoteHelper;
import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.ActionMode;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import com.google.android.material.appbar.MaterialToolbar;
import com.google.android.material.navigation.NavigationView;
import com.google.android.material.snackbar.Snackbar;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
import java.util.concurrent.Executors; | 2,093 | package com.cworld.notie;
public class MainActivity extends AppCompatActivity {
ActionMode actionMode; | package com.cworld.notie;
public class MainActivity extends AppCompatActivity {
ActionMode actionMode; | NoteItemAdapter noteAdapter; | 0 | 2023-12-09 16:22:05+00:00 | 4k |
wuhit/slash | src/main/java/com/wuhit/core/SshClient.java | [
{
"identifier": "Logger",
"path": "src/main/java/com/wuhit/Logger.java",
"snippet": "public final class Logger {\n\n private String ruciaHome;\n\n private String fileName;\n\n private String separator;\n\n private FileWriter fileWriter;\n\n private void initFileWriter() {\n String parentDir =\n ruciaHome + separator + \"logs\" + separator + LocalDate.now().format(DTFUtil.YYYY_MM_DD);\n File parentDirFile = Paths.get(parentDir).toFile();\n if (parentDirFile.exists() == false) {\n parentDirFile.mkdirs();\n }\n\n String logPath = parentDir + separator + fileName + \".log\";\n\n File logFile = Paths.get(logPath).toFile();\n\n if (logFile.exists() == false) {\n try {\n logFile.createNewFile();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n try {\n fileWriter = new FileWriter(logFile, true);\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n private void write(String log) {\n try {\n fileWriter.write(log + \"\\n\");\n fileWriter.flush();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n public void info(String log) {\n log = LocalDateTime.now().format(DTFUtil.YYYY_MM_DD_HH_MM_SS_SSS) + \": \" + log;\n System.out.println(log);\n this.write(log);\n }\n\n public void error(String log) {\n log = LocalDateTime.now().format(DTFUtil.YYYY_MM_DD_HH_MM_SS_SSS) + \": \" + log;\n System.err.println(log);\n this.write(log);\n }\n\n public void destroy() {\n try {\n fileWriter.close();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n public Logger(String ruciaHome, String fileName, String separator) {\n this.ruciaHome = ruciaHome;\n this.fileName = fileName;\n this.separator = separator;\n this.initFileWriter();\n }\n}"
},
{
"identifier": "SlashException",
"path": "src/main/java/com/wuhit/SlashException.java",
"snippet": "public class SlashException extends RuntimeException {\n public SlashException(String message) {\n super(message);\n }\n}"
},
{
"identifier": "StringUtils",
"path": "src/main/java/com/wuhit/StringUtils.java",
"snippet": "public final class StringUtils {\n public static boolean isNotBlank(String value) {\n return value != null && !value.trim().isEmpty();\n }\n\n public static boolean isBlank(String value) {\n return value == null || value.trim().isEmpty();\n }\n}"
},
{
"identifier": "UserInfo",
"path": "src/main/java/com/wuhit/configure/UserInfo.java",
"snippet": "public class UserInfo implements com.jcraft.jsch.UserInfo, UIKeyboardInteractive {\n\n private BaseMFA mfa;\n\n @Override\n public String[] promptKeyboardInteractive(\n String destination, String name, String instruction, String[] prompt, boolean[] echo) {\n\n\n if ((prompt[0].contains(\"OTP Code\") || prompt[0].contains(\"Verification code\")) && mfa != null) {\n System.out.println(STR.\"\\u001B[32m\\{destination} \\{prompt[0]}\\u001B[0m\");\n String otpCode = mfa.otpCode();\n\n String prevOtpCode = OTPCodeStore.get();\n\n if (StringUtils.isBlank(prevOtpCode) || prevOtpCode.equals(otpCode) == false) {\n System.out.println(STR.\"\\u001B[32m\\{otpCode}\\u001B[0m\");\n OTPCodeStore.set(otpCode);\n return new String[]{otpCode};\n }\n }\n\n\n Scanner scanner = new Scanner(System.in);\n System.out.println(STR.\"\\u001B[32m\\{destination} \\{prompt[0]}\\u001B[0m\");\n String input = scanner.nextLine().trim();\n\n return new String[]{input};\n\n }\n\n @Override\n public String getPassphrase() {\n return null;\n }\n\n @Override\n public String getPassword() {\n return null;\n }\n\n @Override\n public boolean promptPassword(String message) {\n return true;\n }\n\n @Override\n public boolean promptPassphrase(String message) {\n return true;\n }\n\n @Override\n public boolean promptYesNo(String message) {\n return true;\n }\n\n @Override\n public void showMessage(String message) {\n System.err.println(message);\n }\n\n public UserInfo(BaseMFA mfa) {\n this.mfa = mfa;\n }\n\n private UserInfo() {\n }\n}"
},
{
"identifier": "BaseMFA",
"path": "src/main/java/com/wuhit/mfa/BaseMFA.java",
"snippet": "public abstract class BaseMFA {\n\n private String secret;\n\n\n public abstract String otpCode();\n\n\n public BaseMFA(String secret) {\n this.secret = secret;\n }\n\n private BaseMFA() {\n\n }\n}"
},
{
"identifier": "GoogleMFA",
"path": "src/main/java/com/wuhit/mfa/GoogleMFA.java",
"snippet": "public class GoogleMFA extends BaseMFA {\n\n private GoogleAuthenticatorKey key;\n private GoogleAuthenticator auth = new GoogleAuthenticator();\n\n public GoogleMFA(String secret) {\n super(secret);\n key = new GoogleAuthenticatorKey.Builder(secret).build();\n }\n\n public String otpCode() {\n return String.valueOf(auth.getTotpPassword(key.getKey()));\n }\n}"
}
] | import com.jcraft.jsch.*;
import com.wuhit.Logger;
import com.wuhit.SlashException;
import com.wuhit.StringUtils;
import com.wuhit.configure.*;
import com.wuhit.configure.UserInfo;
import com.wuhit.mfa.BaseMFA;
import com.wuhit.mfa.GoogleMFA;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List; | 1,671 | package com.wuhit.core;
public class SshClient {
private Ssh ssh;
private Logger logger;
private JSch jSch;
private Session session;
private ChannelSftp channelSftp = null;
private List<String> ignoreFiles = Arrays.asList(".DS_Store", "__MACOSX");
private BaseMFA mfa;
private void initMFAAuth() {
if (ssh.mfa() != null && StringUtils.isNotBlank(ssh.mfa().secret())) {
mfa = new GoogleMFA(ssh.mfa().secret());
}
}
public void connect() {
jSch = new JSch();
String user = ssh.user();
String host = ssh.host();
try {
session = jSch.getSession(user, host, ssh.port());
session.setConfig("StrictHostKeyChecking", "no");
session.setPassword(ssh.password());
session.setUserInfo(new UserInfo(mfa));
session.connect(10 * 1000);
} catch (JSchException e) { | package com.wuhit.core;
public class SshClient {
private Ssh ssh;
private Logger logger;
private JSch jSch;
private Session session;
private ChannelSftp channelSftp = null;
private List<String> ignoreFiles = Arrays.asList(".DS_Store", "__MACOSX");
private BaseMFA mfa;
private void initMFAAuth() {
if (ssh.mfa() != null && StringUtils.isNotBlank(ssh.mfa().secret())) {
mfa = new GoogleMFA(ssh.mfa().secret());
}
}
public void connect() {
jSch = new JSch();
String user = ssh.user();
String host = ssh.host();
try {
session = jSch.getSession(user, host, ssh.port());
session.setConfig("StrictHostKeyChecking", "no");
session.setPassword(ssh.password());
session.setUserInfo(new UserInfo(mfa));
session.connect(10 * 1000);
} catch (JSchException e) { | throw new SlashException(e.getMessage()); | 1 | 2023-12-13 03:35:39+00:00 | 4k |
conductor-oss/conductor-community | index/es7-persistence/src/main/java/com/netflix/conductor/es7/dao/query/parser/Expression.java | [
{
"identifier": "AbstractNode",
"path": "index/es7-persistence/src/main/java/com/netflix/conductor/es7/dao/query/parser/internal/AbstractNode.java",
"snippet": "public abstract class AbstractNode {\n\n public static final Pattern WHITESPACE = Pattern.compile(\"\\\\s\");\n\n protected static Set<Character> comparisonOprs = new HashSet<Character>();\n\n static {\n comparisonOprs.add('>');\n comparisonOprs.add('<');\n comparisonOprs.add('=');\n }\n\n protected InputStream is;\n\n protected AbstractNode(InputStream is) throws ParserException {\n this.is = is;\n this.parse();\n }\n\n protected boolean isNumber(String test) {\n try {\n // If you can convert to a big decimal value, then it is a number.\n new BigDecimal(test);\n return true;\n\n } catch (NumberFormatException e) {\n // Ignore\n }\n return false;\n }\n\n protected boolean isBoolOpr(byte[] buffer) {\n if (buffer.length > 1 && buffer[0] == 'O' && buffer[1] == 'R') {\n return true;\n } else if (buffer.length > 2 && buffer[0] == 'A' && buffer[1] == 'N' && buffer[2] == 'D') {\n return true;\n }\n return false;\n }\n\n protected boolean isComparisonOpr(byte[] buffer) {\n if (buffer[0] == 'I' && buffer[1] == 'N') {\n return true;\n } else if (buffer[0] == '!' && buffer[1] == '=') {\n return true;\n } else {\n return comparisonOprs.contains((char) buffer[0]);\n }\n }\n\n protected byte[] peek(int length) throws Exception {\n return read(length, true);\n }\n\n protected byte[] read(int length) throws Exception {\n return read(length, false);\n }\n\n protected String readToken() throws Exception {\n skipWhitespace();\n StringBuilder sb = new StringBuilder();\n while (is.available() > 0) {\n char c = (char) peek(1)[0];\n if (c == ' ' || c == '\\t' || c == '\\n' || c == '\\r') {\n is.skip(1);\n break;\n } else if (c == '=' || c == '>' || c == '<' || c == '!') {\n // do not skip\n break;\n }\n sb.append(c);\n is.skip(1);\n }\n return sb.toString().trim();\n }\n\n protected boolean isNumeric(char c) {\n if (c == '-' || c == 'e' || (c >= '0' && c <= '9') || c == '.') {\n return true;\n }\n return false;\n }\n\n protected void assertExpected(byte[] found, String expected) throws ParserException {\n assertExpected(new String(found), expected);\n }\n\n protected void assertExpected(String found, String expected) throws ParserException {\n if (!found.equals(expected)) {\n throw new ParserException(\"Expected \" + expected + \", found \" + found);\n }\n }\n\n protected void assertExpected(char found, char expected) throws ParserException {\n if (found != expected) {\n throw new ParserException(\"Expected \" + expected + \", found \" + found);\n }\n }\n\n protected static void efor(int length, FunctionThrowingException<Integer> consumer)\n throws Exception {\n for (int i = 0; i < length; i++) {\n consumer.accept(i);\n }\n }\n\n protected abstract void _parse() throws Exception;\n\n // Public stuff here\n private void parse() throws ParserException {\n // skip white spaces\n skipWhitespace();\n try {\n _parse();\n } catch (Exception e) {\n System.out.println(\"\\t\" + this.getClass().getSimpleName() + \"->\" + this.toString());\n if (!(e instanceof ParserException)) {\n throw new ParserException(\"Error parsing\", e);\n } else {\n throw (ParserException) e;\n }\n }\n skipWhitespace();\n }\n\n // Private methods\n\n private byte[] read(int length, boolean peekOnly) throws Exception {\n byte[] buf = new byte[length];\n if (peekOnly) {\n is.mark(length);\n }\n efor(length, (Integer c) -> buf[c] = (byte) is.read());\n if (peekOnly) {\n is.reset();\n }\n return buf;\n }\n\n protected void skipWhitespace() throws ParserException {\n try {\n while (is.available() > 0) {\n byte c = peek(1)[0];\n if (c == ' ' || c == '\\t' || c == '\\n' || c == '\\r') {\n // skip\n read(1);\n } else {\n break;\n }\n }\n } catch (Exception e) {\n throw new ParserException(e.getMessage(), e);\n }\n }\n}"
},
{
"identifier": "BooleanOp",
"path": "index/es7-persistence/src/main/java/com/netflix/conductor/es7/dao/query/parser/internal/BooleanOp.java",
"snippet": "public class BooleanOp extends AbstractNode {\n\n private String value;\n\n public BooleanOp(InputStream is) throws ParserException {\n super(is);\n }\n\n @Override\n protected void _parse() throws Exception {\n byte[] buffer = peek(3);\n if (buffer.length > 1 && buffer[0] == 'O' && buffer[1] == 'R') {\n this.value = \"OR\";\n } else if (buffer.length > 2 && buffer[0] == 'A' && buffer[1] == 'N' && buffer[2] == 'D') {\n this.value = \"AND\";\n } else {\n throw new ParserException(\"No valid boolean operator found...\");\n }\n read(this.value.length());\n }\n\n @Override\n public String toString() {\n return \" \" + value + \" \";\n }\n\n public String getOperator() {\n return value;\n }\n\n public boolean isAnd() {\n return \"AND\".equals(value);\n }\n\n public boolean isOr() {\n return \"OR\".equals(value);\n }\n}"
},
{
"identifier": "ParserException",
"path": "index/es7-persistence/src/main/java/com/netflix/conductor/es7/dao/query/parser/internal/ParserException.java",
"snippet": "@SuppressWarnings(\"serial\")\npublic class ParserException extends Exception {\n\n public ParserException(String message) {\n super(message);\n }\n\n public ParserException(String message, Throwable cause) {\n super(message, cause);\n }\n}"
}
] | import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import com.netflix.conductor.es7.dao.query.parser.internal.AbstractNode;
import com.netflix.conductor.es7.dao.query.parser.internal.BooleanOp;
import com.netflix.conductor.es7.dao.query.parser.internal.ParserException; | 1,870 | /*
* <p>
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.netflix.conductor.es7.dao.query.parser;
/**
* @author Viren
*/
public class Expression extends AbstractNode implements FilterProvider {
private NameValue nameVal;
private GroupedExpression ge;
| /*
* <p>
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.netflix.conductor.es7.dao.query.parser;
/**
* @author Viren
*/
public class Expression extends AbstractNode implements FilterProvider {
private NameValue nameVal;
private GroupedExpression ge;
| private BooleanOp op; | 1 | 2023-12-08 06:06:20+00:00 | 4k |
zhouyqxy/aurora_Lite | src/main/java/com/aurora/aspect/ExceptionLogAspect.java | [
{
"identifier": "ExceptionLog",
"path": "src/main/java/com/aurora/entity/ExceptionLog.java",
"snippet": "@Data\n@Builder\n@NoArgsConstructor\n@AllArgsConstructor\n@TableName(\"t_exception_log\")\npublic class ExceptionLog {\n\n @TableId(type = IdType.AUTO)\n private Integer id;\n\n private String optUri;\n\n private String optMethod;\n\n private String requestMethod;\n\n private String requestParam;\n\n private String optDesc;\n\n private String exceptionInfo;\n\n private String ipAddress;\n\n private String ipSource;\n\n @TableField(exist=false)\n private Boolean unknownException;\n\n @TableField(fill = FieldFill.INSERT)\n private LocalDateTime createTime;\n\n}"
},
{
"identifier": "ExceptionLogEvent",
"path": "src/main/java/com/aurora/event/ExceptionLogEvent.java",
"snippet": "public class ExceptionLogEvent extends ApplicationEvent {\n public ExceptionLogEvent(ExceptionLog exceptionLog) {\n super(exceptionLog);\n }\n}"
},
{
"identifier": "BizException",
"path": "src/main/java/com/aurora/exception/BizException.java",
"snippet": "@Getter\n@AllArgsConstructor\npublic class BizException extends RuntimeException {\n\n private Integer code = StatusCodeEnum.FAIL.getCode();\n\n private final String message;\n\n public BizException(String message) {\n this.message = message;\n }\n\n public BizException(StatusCodeEnum statusCodeEnum) {\n this.code = statusCodeEnum.getCode();\n this.message = statusCodeEnum.getDesc();\n }\n\n}"
},
{
"identifier": "ExceptionUtil",
"path": "src/main/java/com/aurora/util/ExceptionUtil.java",
"snippet": "public class ExceptionUtil {\n\n public static String getTrace(Throwable t) {\n StringWriter stringWriter = new StringWriter();\n PrintWriter writer = new PrintWriter(stringWriter);\n t.printStackTrace(writer);\n StringBuffer buffer = stringWriter.getBuffer();\n return buffer.toString();\n }\n\n}"
},
{
"identifier": "IpUtil",
"path": "src/main/java/com/aurora/util/IpUtil.java",
"snippet": "@Slf4j\n@Component\npublic class IpUtil {\n\n private static DbSearcher searcher;\n\n private static Method method;\n\n public static String getIpAddress(HttpServletRequest request) {\n String ipAddress = request.getHeader(\"X-Real-IP\");\n\n if (\"127.0.0.1\".equals(ipAddress)) {\n ipAddress = request.getHeader(\"x-natapp-ip\");\n }\n if (ipAddress == null || ipAddress.length() == 0 || \"unknown\".equalsIgnoreCase(ipAddress)) {\n ipAddress = request.getHeader(\"x-forwarded-for\");\n }\n if (ipAddress == null || ipAddress.length() == 0 || \"unknown\".equalsIgnoreCase(ipAddress)) {\n ipAddress = request.getHeader(\"Proxy-Client-IP\");\n }\n if (ipAddress == null || ipAddress.length() == 0 || \"unknown\".equalsIgnoreCase(ipAddress)) {\n ipAddress = request.getHeader(\"WL-Proxy-Client-IP\");\n }\n if (ipAddress == null || ipAddress.length() == 0 || \"unknown\".equalsIgnoreCase(ipAddress)) {\n ipAddress = request.getHeader(\"HTTP_CLIENT_IP\");\n }\n if (ipAddress == null || ipAddress.length() == 0 || \"unknown\".equalsIgnoreCase(ipAddress)) {\n ipAddress = request.getHeader(\"HTTP_X_FORWARDED_FOR\");\n }\n if (ipAddress == null || ipAddress.length() == 0 || \"unknown\".equalsIgnoreCase(ipAddress)) {\n ipAddress = request.getRemoteAddr();\n if (\"127.0.0.1\".equals(ipAddress) || \"0:0:0:0:0:0:0:1\".equals(ipAddress)) {\n //根据网卡取本机配置的IP\n InetAddress inet = null;\n try {\n inet = InetAddress.getLocalHost();\n } catch (UnknownHostException e) {\n log.error(\"getIpAddress exception:\", e);\n }\n assert inet != null;\n ipAddress = inet.getHostAddress();\n }\n }\n return StringUtils.substringBefore(ipAddress, \",\");\n }\n\n @PostConstruct\n private void initIp2regionResource() throws Exception {\n InputStream inputStream = new ClassPathResource(\"/ip/ip2region.db\").getInputStream();\n byte[] dbBinStr = FileCopyUtils.copyToByteArray(inputStream);\n DbConfig dbConfig = new DbConfig();\n searcher = new DbSearcher(dbConfig, dbBinStr);\n method = searcher.getClass().getMethod(\"memorySearch\", String.class);\n }\n\n public static String getIpSource(String ipAddress) {\n if (StringUtils.isBlank(ipAddress)|| !Util.isIpAddress(ipAddress) || \"127.0.0.1\".equals(ipAddress)) {\n log.error(\"Error: Invalid ip address [{}]\",ipAddress);\n return ipAddress;\n }\n try {\n DataBlock dataBlock = (DataBlock) method.invoke(searcher, ipAddress);\n String ipInfo = dataBlock.getRegion();\n if (!StringUtils.isEmpty(ipInfo)) {\n ipInfo = ipInfo.replace(\"|0\", \"\");\n ipInfo = ipInfo.replace(\"0|\", \"\");\n return ipInfo;\n }\n } catch (Exception e) {\n log.error(\"getCityInfo exception:\", e);\n }\n return \"\";\n }\n\n public static String getIpProvince(String ipSource) {\n if (StringUtils.isBlank(ipSource)) {\n return CommonConstant.UNKNOWN;\n }\n String[] strings = ipSource.split(\"\\\\|\");\n if (strings.length > 1 && strings[1].endsWith(\"省\")) {\n return StringUtils.substringBefore(strings[1], \"省\");\n }\n return strings[0];\n }\n\n public static UserAgent getUserAgent(HttpServletRequest request) {\n return UserAgent.parseUserAgentString(request.getHeader(\"User-Agent\"));\n }\n\n}"
}
] | import com.alibaba.fastjson.JSON;
import com.aurora.entity.ExceptionLog;
import com.aurora.event.ExceptionLogEvent;
import com.aurora.exception.BizException;
import com.aurora.util.ExceptionUtil;
import com.aurora.util.IpUtil;
import io.swagger.annotations.ApiOperation;
import lombok.extern.log4j.Log4j2;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Objects; | 1,924 | package com.aurora.aspect;
@Aspect
@Component
@Log4j2
public class ExceptionLogAspect {
@Autowired
private ApplicationContext applicationContext;
@Pointcut("execution(* com.aurora.controller..*.*(..))")
public void exceptionLogPointcut() {
}
@AfterThrowing(value = "exceptionLogPointcut()", throwing = "e")
public void saveExceptionLog(JoinPoint joinPoint, Exception e) {
String errMsg = "未知异常 ";
ExceptionLog exceptionLog = new ExceptionLog();
if (e instanceof BizException) {
errMsg = e.getMessage();
}else{
exceptionLog.setUnknownException(true);
}
log.error(errMsg, e);
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
HttpServletRequest request = (HttpServletRequest) Objects.requireNonNull(requestAttributes).resolveReference(RequestAttributes.REFERENCE_REQUEST);
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
ApiOperation apiOperation = method.getAnnotation(ApiOperation.class);
exceptionLog.setOptUri(Objects.requireNonNull(request).getRequestURI());
String className = joinPoint.getTarget().getClass().getName();
String methodName = method.getName();
methodName = className + "." + methodName;
exceptionLog.setOptMethod(methodName);
exceptionLog.setRequestMethod(Objects.requireNonNull(request).getMethod());
if (joinPoint.getArgs().length > 0) {
if (joinPoint.getArgs()[0] instanceof MultipartFile) {
exceptionLog.setRequestParam("file");
} else {
exceptionLog.setRequestParam(JSON.toJSONString(joinPoint.getArgs()));
}
}
if (Objects.nonNull(apiOperation)) {
exceptionLog.setOptDesc(apiOperation.value());
} else {
exceptionLog.setOptDesc("");
}
exceptionLog.setExceptionInfo(ExceptionUtil.getTrace(e));
String ipAddress = IpUtil.getIpAddress(request);
exceptionLog.setIpAddress(ipAddress);
exceptionLog.setIpSource(IpUtil.getIpSource(ipAddress)); | package com.aurora.aspect;
@Aspect
@Component
@Log4j2
public class ExceptionLogAspect {
@Autowired
private ApplicationContext applicationContext;
@Pointcut("execution(* com.aurora.controller..*.*(..))")
public void exceptionLogPointcut() {
}
@AfterThrowing(value = "exceptionLogPointcut()", throwing = "e")
public void saveExceptionLog(JoinPoint joinPoint, Exception e) {
String errMsg = "未知异常 ";
ExceptionLog exceptionLog = new ExceptionLog();
if (e instanceof BizException) {
errMsg = e.getMessage();
}else{
exceptionLog.setUnknownException(true);
}
log.error(errMsg, e);
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
HttpServletRequest request = (HttpServletRequest) Objects.requireNonNull(requestAttributes).resolveReference(RequestAttributes.REFERENCE_REQUEST);
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
ApiOperation apiOperation = method.getAnnotation(ApiOperation.class);
exceptionLog.setOptUri(Objects.requireNonNull(request).getRequestURI());
String className = joinPoint.getTarget().getClass().getName();
String methodName = method.getName();
methodName = className + "." + methodName;
exceptionLog.setOptMethod(methodName);
exceptionLog.setRequestMethod(Objects.requireNonNull(request).getMethod());
if (joinPoint.getArgs().length > 0) {
if (joinPoint.getArgs()[0] instanceof MultipartFile) {
exceptionLog.setRequestParam("file");
} else {
exceptionLog.setRequestParam(JSON.toJSONString(joinPoint.getArgs()));
}
}
if (Objects.nonNull(apiOperation)) {
exceptionLog.setOptDesc(apiOperation.value());
} else {
exceptionLog.setOptDesc("");
}
exceptionLog.setExceptionInfo(ExceptionUtil.getTrace(e));
String ipAddress = IpUtil.getIpAddress(request);
exceptionLog.setIpAddress(ipAddress);
exceptionLog.setIpSource(IpUtil.getIpSource(ipAddress)); | applicationContext.publishEvent(new ExceptionLogEvent(exceptionLog)); | 1 | 2023-12-05 03:38:51+00:00 | 4k |
khaHesham/Match-Reservation-System | Api/src/main/java/com/premierleague/reservation/api/controllers/UserController.java | [
{
"identifier": "UserDTO",
"path": "Api/src/main/java/com/premierleague/reservation/api/dtos/UserDTO.java",
"snippet": "@Setter\n@Getter\npublic class UserDTO implements Serializable {\n\n @Setter\n private Long id;\n\n @Setter\n private String username;\n\n @Setter\n private String firstName;\n\n @Setter\n private String lastName;\n\n @Setter\n private String email;\n\n @Setter\n private String city;\n\n @Setter\n private String birthDate;\n\n @Setter\n private Role role;\n\n @Setter\n private String Address;\n \n}"
},
{
"identifier": "UnauthorizedException",
"path": "Api/src/main/java/com/premierleague/reservation/api/exceptions/UnauthorizedException.java",
"snippet": "public class UnauthorizedException extends RuntimeException{\n public UnauthorizedException(String message) {\n super(message);\n }\n}"
},
{
"identifier": "UserMapper",
"path": "Api/src/main/java/com/premierleague/reservation/api/mappers/UserMapper.java",
"snippet": "@Mapper(componentModel = \"spring\")\npublic interface UserMapper {\n\n User toEntity(UserDTO userDTO);\n\n UserDTO toDTO(User user);\n\n List<UserDTO> toDTOs(List<User> users);\n}"
},
{
"identifier": "User",
"path": "Api/src/main/java/com/premierleague/reservation/api/models/User.java",
"snippet": "@Data\n@Builder\n@NoArgsConstructor\n@AllArgsConstructor\n@Entity\n@Table(name = \"users\")\npublic class User implements UserDetails {\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n @Column(name = \"id\", nullable = false)\n private Long id;\n\n @Column(name = \"username\", unique = true)\n private String username;\n\n @Column(name = \"first_name\")\n private String firstName;\n\n @Column(name = \"last_name\")\n private String lastName;\n\n @Column(name = \"password\")\n private String password;\n\n @Column(name = \"email\",unique = true)\n private String email;\n\n @Column(name = \"city\")\n private String city;\n\n @Column(name = \"requested_role\")\n private boolean requestedRole = false;\n\n @Column(name = \"birth_date\")\n private String birthDate;\n\n @Column(name = \"address\")\n private String Address;\n\n @Enumerated(EnumType.STRING)\n private Role role;\n\n @Override\n public Collection<? extends GrantedAuthority> getAuthorities() {\n return List.of(new SimpleGrantedAuthority(role.name()));\n }\n\n @Override\n public String getPassword() {\n return password;\n }\n\n @Override\n public String getUsername() {\n return username;\n }\n\n @Override\n public boolean isAccountNonExpired() {\n return true;\n }\n\n @Override\n public boolean isAccountNonLocked() {\n return true;\n }\n\n @Override\n public boolean isCredentialsNonExpired() {\n return true;\n }\n\n @Override\n public boolean isEnabled() {\n return true;\n }\n}"
},
{
"identifier": "UserService",
"path": "Api/src/main/java/com/premierleague/reservation/api/service/UserService.java",
"snippet": "@Service\npublic class UserService {\n @Autowired\n private UserRepository userRepository;\n @Autowired\n private UserMapper userMapper;\n\n @Autowired\n private AuthenticationService authenticationService;\n\n public UserDTO userProfile(String username) {\n Optional<User> user = Optional.ofNullable(userRepository.findUserByUsername(username)\n .orElseThrow(() -> new RuntimeException(\"User not found\")));\n\n return userMapper.toDTO(user.get());\n }\n\n\n public UserDTO updateUser(UserDTO userDTO) {\n if (!userRepository.existsById(userDTO.getId())) {\n throw new RuntimeException(\"User not found with id: \" + userDTO.getId());\n }\n\n User user = userRepository.save(userMapper.toEntity(userDTO));\n return userMapper.toDTO(user);\n }\n\n public void deleteUser(Long id) {\n if (!userRepository.existsById(id)) {\n throw new RuntimeException(\"User not found with id: \" + id);\n }\n\n // check if iam an admin\n if(!authenticationService.getRole().equals(\"ADMIN\")){\n throw new UnauthorizedException(\"You are not authorized to perform this action\");\n }\n\n\n userRepository.deleteById(id);\n }\n\n public User getUserById(Long userId) {\n Optional<User> user = userRepository.findById(userId);\n if (!user.isPresent()) {\n throw new RuntimeException(\"User not found with id: \" + userId);\n }\n return user.get();\n }\n\n public User getUserByUsername(String username) {\n Optional<User> user = userRepository.findUserByUsername(username);\n if (!user.isPresent()) {\n throw new RuntimeException(\"User not found with username: \" + username);\n }\n return user.get();\n }\n\n public void approveUser(Long id) {\n if (!userRepository.existsById(id)) {\n throw new RuntimeException(\"User not found with id: \" + id);\n }\n\n // check if iam an admin\n if(!authenticationService.getRole().equals(\"ADMIN\")){\n throw new UnauthorizedException(\"You are not authorized to perform this action\");\n }\n\n User user = userRepository.findById(id).get();\n\n if (!user.isRequestedRole()) {\n throw new RuntimeException(\"User did not request a role\");\n }\n\n user.setRole(Role.valueOf(\"EFA_MANAGER\"));\n userRepository.save(user);\n }\n\n public boolean requestManager() {\n String username = authenticationService.getUsername();\n User user = userRepository.findUserByUsername(username).get();\n\n user.setRequestedRole(true);\n userRepository.save(user);\n\n return true;\n }\n}"
}
] | import com.premierleague.reservation.api.dtos.UserDTO;
import com.premierleague.reservation.api.exceptions.UnauthorizedException;
import com.premierleague.reservation.api.mappers.UserMapper;
import com.premierleague.reservation.api.models.User;
import com.premierleague.reservation.api.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*; | 1,752 | package com.premierleague.reservation.api.controllers;
@RestController
@RequestMapping("/api/v1/user")
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/profile/{username}")
public ResponseEntity<UserDTO> userProfile(@PathVariable String username) {
try {
return new ResponseEntity<>((userService.userProfile(username)), HttpStatus.OK);
} catch (RuntimeException e) {
System.out.println(e.getMessage());
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
} catch (Exception e) {
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
@PutMapping("/update")
public ResponseEntity<UserDTO> updateUser(@RequestBody UserDTO user) {
try {
return new ResponseEntity<>(userService.updateUser(user), HttpStatus.OK);
} catch (RuntimeException e) {
System.out.println(e.getMessage());
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
} catch (Exception e) {
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
// TODO: add admin role check
@DeleteMapping("/delete/{id}")
public ResponseEntity<String> deleteUser(@PathVariable("id") Long id) {
try {
// need to check if the user performing this action is an admin
// else throw unauthorized exception
userService.deleteUser(id);
return new ResponseEntity<>("User deleted successfully", HttpStatus.OK); | package com.premierleague.reservation.api.controllers;
@RestController
@RequestMapping("/api/v1/user")
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/profile/{username}")
public ResponseEntity<UserDTO> userProfile(@PathVariable String username) {
try {
return new ResponseEntity<>((userService.userProfile(username)), HttpStatus.OK);
} catch (RuntimeException e) {
System.out.println(e.getMessage());
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
} catch (Exception e) {
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
@PutMapping("/update")
public ResponseEntity<UserDTO> updateUser(@RequestBody UserDTO user) {
try {
return new ResponseEntity<>(userService.updateUser(user), HttpStatus.OK);
} catch (RuntimeException e) {
System.out.println(e.getMessage());
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
} catch (Exception e) {
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
// TODO: add admin role check
@DeleteMapping("/delete/{id}")
public ResponseEntity<String> deleteUser(@PathVariable("id") Long id) {
try {
// need to check if the user performing this action is an admin
// else throw unauthorized exception
userService.deleteUser(id);
return new ResponseEntity<>("User deleted successfully", HttpStatus.OK); | } catch (UnauthorizedException e) { | 1 | 2023-12-05 18:40:40+00:00 | 4k |
blueokanna/ReverseCoin | src/main/java/ReverseCoinBlockChainGeneration/NewBlockCreation.java | [
{
"identifier": "PerformRingSign",
"path": "src/main/java/BlockModel/PerformRingSign.java",
"snippet": "public class PerformRingSign implements Serializable {\n\n private static final long serialVersionUID = 1145141919810L;\n\n private KeyPair[] generateKeyPairs(int numKeyPairs) throws NoSuchAlgorithmException {\n KeyPair[] keyPairs = new KeyPair[numKeyPairs];\n KeyPairGenerator keyGen = KeyPairGenerator.getInstance(\"EC\");\n SecureRandom random = new SecureRandom();\n keyGen.initialize(256, random);\n\n for (int i = 0; i < numKeyPairs; i++) {\n keyPairs[i] = keyGen.generateKeyPair();\n }\n return keyPairs;\n }\n\n public byte[] performRingSign(String data, int numKeyPairs, int signerIndex) {\n try {\n int numMembers = generateKeyPairs(numKeyPairs).length;\n KeyPair[] keyPairs = generateKeyPairs(numKeyPairs);\n List<PublicKey> publicKeys = new ArrayList<>();\n\n for (int i = 0; i < numMembers; i++) {\n if (i != signerIndex) {\n publicKeys.add(keyPairs[i].getPublic());\n }\n }\n\n Signature signature = Signature.getInstance(\"SHA3-256withECDSA\");\n signature.initSign(keyPairs[signerIndex].getPrivate());\n signature.update(data.getBytes());\n\n for (byte[] sig : publicKeysToBytes(publicKeys)) {\n signature.update(sig);\n }\n\n return signature.sign();\n } catch (InvalidKeyException | SignatureException | NoSuchAlgorithmException ex) {\n ex.printStackTrace();\n }\n return null;\n }\n\n public boolean verifyRingSign(byte[] data, byte[] signature, KeyPair[] publicKeys) {\n try {\n int numMembers = publicKeys.length;\n Signature sig = Signature.getInstance(\"SHA3-256withECDSA\");\n\n for (int i = 0; i < numMembers; i++) {\n sig.initVerify(publicKeys[i].getPublic());\n sig.update(data);\n\n if (i < numMembers - 1) {\n sig.update(signature);\n }\n\n if (sig.verify(signature)) {\n return true;\n }\n }\n } catch (InvalidKeyException | SignatureException | NoSuchAlgorithmException ex) {\n ex.printStackTrace();\n }\n return false;\n }\n\n private byte[][] publicKeysToBytes(List<PublicKey> publicKeys) {\n byte[][] bytes = new byte[publicKeys.size()][];\n for (int i = 0; i < publicKeys.size(); i++) {\n bytes[i] = publicKeys.get(i).getEncoded();\n }\n return bytes;\n }\n}"
},
{
"identifier": "ReverseCoinBlock",
"path": "src/main/java/BlockModel/ReverseCoinBlock.java",
"snippet": "public class ReverseCoinBlock implements Serializable, ReverseCoinBlockInterface {\n\n private static final long serialVersionUID = 1145141919810L;\n private byte version;\n private int index;\n private String PreviousHash;\n private CopyOnWriteArrayList<ReverseCoinTransaction> TransactionsData;\n private String TransactionHash;\n private long TimeStamp;\n private long nonce;\n private int difficulty;\n private String thisBlockHash;\n\n @Override\n public byte getVersion() {\n return version;\n }\n\n @Override\n public void setVersion(byte version) {\n this.version = version;\n }\n\n @Override\n public int getIndex() {\n return index;\n }\n\n @Override\n public void setIndex(int index) {\n this.index = index;\n }\n\n @Override\n public String getPreviousHash() {\n return PreviousHash;\n }\n\n @Override\n public void setPreviousHash(String PreviousHash) {\n this.PreviousHash = PreviousHash;\n }\n\n @Override\n public String getTransactionHash() {\n return TransactionHash;\n }\n\n @Override\n public void setTransactionHash(String TransactionHash) {\n this.TransactionHash = TransactionHash;\n } \n\n @Override\n public CopyOnWriteArrayList<ReverseCoinTransaction> getTransactionsData() {\n return TransactionsData;\n }\n\n @Override\n public void setTransactionsData(CopyOnWriteArrayList<ReverseCoinTransaction> TransactionsData) {\n this.TransactionsData = TransactionsData;\n }\n\n @Override\n public long getTimeStamp() {\n return TimeStamp;\n }\n\n @Override\n public void setTimeStamp(long TimeStamp) {\n this.TimeStamp = TimeStamp;\n }\n\n @Override\n public int getDifficulty() {\n return difficulty;\n }\n\n @Override\n public void setDifficulty(int difficulty) {\n this.difficulty = difficulty;\n }\n\n @Override\n public long getNonce() {\n return nonce;\n }\n\n @Override\n public void setNonce(long nonce) {\n this.nonce = nonce;\n }\n\n @Override\n public String getThisBlockHash() {\n return thisBlockHash;\n }\n\n @Override\n public void setThisBlockHash(String thisBlockHash) {\n this.thisBlockHash = thisBlockHash;\n }\n\n @Override\n public String toBlockJsonString(ReverseCoinBlock blocks) {\n return new GsonBuilder().create().toJson(blocks);\n }\n\n}"
},
{
"identifier": "ReverseCoinTransaction",
"path": "src/main/java/BlockModel/ReverseCoinTransaction.java",
"snippet": "public class ReverseCoinTransaction implements Serializable ,TransactionInterface{\n\n private static final long serialVersionUID = 1145141919810L;\n private String Sender;\n private String receiver;\n private double amount;\n private double Txfee;\n private String signature;\n\n public ReverseCoinTransaction() {\n\n }\n public ReverseCoinTransaction(String Sender, String receiver, double amount, double Txfee) {\n this.Sender = Sender;\n this.receiver = receiver;\n this.amount = amount;\n this.Txfee = Txfee;\n }\n public ReverseCoinTransaction(String Sender, String receiver, double amount, double Txfee, String signature) {\n this.Sender = Sender;\n this.receiver = receiver;\n this.amount = amount;\n this.Txfee = Txfee;\n this.signature = signature;\n }\n\n private LinkedHashMap<String, Object> JsonMap() {\n LinkedHashMap<String, Object> map = new LinkedHashMap<>();\n map.put(\"Sender\", Sender);\n map.put(\"Receiver\", receiver);\n map.put(\"Amount\", amount);\n map.put(\"GasFee\", Txfee);\n map.put(\"Signature\", signature);\n return map;\n }\n\n @Override\n public String getSender() {\n return Sender;\n }\n\n @Override\n public void setSender(String Sender) {\n this.Sender = Sender;\n }\n\n @Override\n public String getReceiver() {\n return receiver;\n }\n\n @Override\n public void setReceiver(String receiver) {\n this.receiver = receiver;\n }\n\n @Override\n public double getAmount() {\n return amount;\n }\n\n @Override\n public void setAmount(double amount) {\n this.amount = amount;\n }\n\n @Override\n public double getTxfee() {\n return Txfee;\n }\n\n @Override\n public void setTxfee(double Txfee) {\n this.Txfee = Txfee;\n }\n\n @Override\n public String getSignature() {\n return signature;\n }\n\n @Override\n public void setSignature(String signature) {\n this.signature = signature;\n }\n\n @Override\n public String toJsonTransactionString() {\n Gson gson = new GsonBuilder().setPrettyPrinting().create();\n return gson.toJson(JsonMap());\n }\n\n}"
},
{
"identifier": "TimeStampGenerator",
"path": "src/main/java/BlockModel/TimeStampGenerator.java",
"snippet": "public class TimeStampGenerator {\n\n public long TimeToSync() {\n long timestamp = Instant.now().toEpochMilli();\n try {\n if (getNTPTime() - timestamp < 1000) {\n return timestamp;\n } else {\n return getNTPTime();\n }\n } catch (IOException e) {\n System.out.println(\"Failed to sync time: \" + e.getMessage());\n return timestamp;\n }\n }\n\n private long getNTPTime() throws IOException {\n int port = 123;\n InetAddress address = InetAddress.getByName(\"ntp.aliyun.com\");\n\n try (DatagramSocket socket = new DatagramSocket()) {\n byte[] buf = new byte[48];\n buf[0] = 0x1B;\n DatagramPacket requestPacket = new DatagramPacket(buf, buf.length, address, port);\n socket.send(requestPacket);\n\n DatagramPacket responsePacket = new DatagramPacket(new byte[48], 48);\n socket.receive(responsePacket);\n\n byte[] rawData = responsePacket.getData();\n long secondsSince1900 = 0;\n for (int i = 40; i <= 43; i++) {\n secondsSince1900 = (secondsSince1900 << 8) | (rawData[i] & 0xff);\n }\n return (secondsSince1900 - 2208988800L) * 1000;\n }\n }\n}"
},
{
"identifier": "NewReverseCoinBlockInterface",
"path": "src/main/java/ConnectionAPI/NewReverseCoinBlockInterface.java",
"snippet": "public interface NewReverseCoinBlockInterface {\n\n boolean addNewBlocks(ReverseCoinBlock newBlock, ReverseCoinChainConfigInterface config);\n\n boolean checkPetaBlock(ReverseCoinBlock newBlock, ReverseCoinBlock previousBlock, ReverseCoinChainConfigInterface config);\n\n ReverseCoinBlock generatedNewBlock(String preHash, CopyOnWriteArrayList<ReverseCoinTransaction> TransactionsData, String TransactionHash, long nonce, String setBlockHash, ReverseCoinChainConfigInterface config);\n\n void updatePetaChain(CopyOnWriteArrayList<ReverseCoinBlock> newChain, ReverseCoinChainConfigInterface config);\n\n boolean isUpdateBlockChain(CopyOnWriteArrayList<ReverseCoinBlock> petachain, ReverseCoinChainConfigInterface config);\n \n boolean isSortedByIndex(ReverseCoinChainConfigInterface config);\n\n boolean checkBlocksHash(String hash, String target, ReverseCoinChainConfigInterface config);\n\n}"
},
{
"identifier": "ReverseCoinChainConfigInterface",
"path": "src/main/java/ConnectionAPI/ReverseCoinChainConfigInterface.java",
"snippet": "public interface ReverseCoinChainConfigInterface {\n\n int getDifficulty();\n\n int getPorts();\n\n String getAddressPort();\n\n CopyOnWriteArrayList<ReverseCoinBlock> getBlockList();\n\n CopyOnWriteArrayList<ReverseCoinTransaction> getTransactionsList();\n\n CopyOnWriteArrayList<WebSocket> getSocketsList();\n\n ReverseCoinBlock getLatestBlock();\n \n String SHA3with256Hash(String input);\n\n void setDifficulty(int difficulty);\n\n void setPorts(int ports);\n\n void setAddressPort(String AddressPort);\n\n void setBlockList(CopyOnWriteArrayList<ReverseCoinBlock> BlockList);\n\n void setTransactionsList(CopyOnWriteArrayList<ReverseCoinTransaction> TransactionsList);\n\n void setSocketsList(CopyOnWriteArrayList<WebSocket> socketsList);\n}"
},
{
"identifier": "ReverseCoinBlockInterface",
"path": "src/main/java/ConnectionAPI/ReverseCoinBlockInterface.java",
"snippet": "public interface ReverseCoinBlockInterface {\n\n byte getVersion();\n\n int getIndex();\n\n String getPreviousHash();\n\n String getTransactionHash();\n\n CopyOnWriteArrayList<ReverseCoinTransaction> getTransactionsData();\n\n long getTimeStamp();\n\n int getDifficulty();\n\n long getNonce();\n\n String getThisBlockHash();\n\n String toBlockJsonString(ReverseCoinBlock blocks);\n\n void setVersion(byte version);\n\n void setIndex(int index);\n\n void setPreviousHash(String PreviousHash);\n\n void setTransactionHash(String TransactionHash);\n\n void setTransactionsData(CopyOnWriteArrayList<ReverseCoinTransaction> TransactionHash);\n\n void setTimeStamp(long TimeStamp);\n\n void setDifficulty(int difficulty);\n\n void setNonce(long nonce);\n\n void setThisBlockHash(String thisBlockHash);\n\n}"
}
] | import BlockModel.PerformRingSign;
import BlockModel.ReverseCoinBlock;
import BlockModel.ReverseCoinTransaction;
import BlockModel.TimeStampGenerator;
import com.google.gson.GsonBuilder;
import java.security.SecureRandom;
import java.util.Base64;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import ConnectionAPI.NewReverseCoinBlockInterface;
import ConnectionAPI.ReverseCoinChainConfigInterface;
import ConnectionAPI.ReverseCoinBlockInterface; | 3,086 | package ReverseCoinBlockChainGeneration;
public class NewBlockCreation implements NewReverseCoinBlockInterface {
private final String previousHash = "0000000000000000000000000000000000000000000000000000000000000000"; | package ReverseCoinBlockChainGeneration;
public class NewBlockCreation implements NewReverseCoinBlockInterface {
private final String previousHash = "0000000000000000000000000000000000000000000000000000000000000000"; | private volatile long timestamp = new TimeStampGenerator().TimeToSync(); | 3 | 2023-12-11 05:18:04+00:00 | 4k |
Patbox/PolyDecorations | src/main/java/eu/pb4/polydecorations/ui/UiResourceCreator.java | [
{
"identifier": "ModInit",
"path": "src/main/java/eu/pb4/polydecorations/ModInit.java",
"snippet": "public class ModInit implements ModInitializer {\n\tpublic static final String ID = \"polydecorations\";\n\tpublic static final String VERSION = FabricLoader.getInstance().getModContainer(ID).get().getMetadata().getVersion().getFriendlyString();\n\tpublic static final Logger LOGGER = LoggerFactory.getLogger(\"PolyDecorations\");\n public static final boolean DEV_ENV = FabricLoader.getInstance().isDevelopmentEnvironment();\n public static final boolean DEV_MODE = VERSION.contains(\"-dev.\") || DEV_ENV;\n @SuppressWarnings(\"PointlessBooleanExpression\")\n\tpublic static final boolean DYNAMIC_ASSETS = true && DEV_ENV;\n\n public static Identifier id(String path) {\n\t\treturn new Identifier(ID, path);\n\t}\n\n\t@Override\n\tpublic void onInitialize() {\n\t\tif (VERSION.contains(\"-dev.\")) {\n\t\t\tLOGGER.warn(\"=====================================================\");\n\t\t\tLOGGER.warn(\"You are using development version of PolyDecorations!\");\n\t\t\tLOGGER.warn(\"Support is limited, as features might be unfinished!\");\n\t\t\tLOGGER.warn(\"You are on your own!\");\n\t\t\tLOGGER.warn(\"=====================================================\");\n\t\t}\n\n\t\tDecorationsBlocks.register();\n\t\tDecorationsBlockEntities.register();\n\t\tDecorationsItems.register();\n\t\tDecorationsEntities.register();\n\t\tDecorationsRecipeTypes.register();\n\t\tDecorationsRecipeSerializers.register();\n\t\tDecorationsUtil.register();\n\t\tDebugData.register();\n\n\t\tinitModels();\n\t\tUiResourceCreator.setup();\n\t\tGuiTextures.register();\n\t\tPolydexCompat.register();\n\t\tPolymerResourcePackUtils.addModAssets(ID);\n\t\tPolymerResourcePackUtils.markAsRequired();\n\n\t}\n\n\t@SuppressWarnings(\"ResultOfMethodCallIgnored\")\n\tprivate void initModels() {\n\t\tWallAttachedLanternBlock.Model.MODEL.isEmpty();\n\t\tBrazierBlock.Model.UNLIT.isEmpty();\n\t\tGlobeBlock.Model.GLOBE_BASE.isEmpty();\n\t}\n}"
},
{
"identifier": "ResourceUtils",
"path": "src/main/java/eu/pb4/polydecorations/util/ResourceUtils.java",
"snippet": "public class ResourceUtils {\n\n public static BufferedImage getTexture(Identifier identifier) {\n try {\n return ImageIO.read(getJarStream(\"assets/\" + identifier.getNamespace() + \"/textures/\" + identifier.getPath() +\".png\"));\n } catch (IOException e) {\n e.printStackTrace();\n return new BufferedImage(16, 16, BufferedImage.TYPE_INT_ARGB);\n }\n }\n\n public static byte[] getJarData(String jarPath) {\n for (var basePath : FabricLoader.getInstance().getModContainer(ModInit.ID).get().getRootPaths()) {\n var path = basePath.resolve(jarPath);\n if (Files.exists(path)) {\n try {\n return Files.readAllBytes(path);\n } catch (Throwable e) {\n }\n }\n }\n return null;\n }\n\n public static InputStream getJarStream(String jarPath) {\n for (var basePath : FabricLoader.getInstance().getModContainer(ModInit.ID).get().getRootPaths()) {\n var path = basePath.resolve(jarPath);\n if (Files.exists(path)) {\n try {\n return Files.newInputStream(path);\n } catch (Throwable e) {\n }\n }\n }\n return null;\n }\n}"
},
{
"identifier": "id",
"path": "src/main/java/eu/pb4/polydecorations/util/DecorationsUtil.java",
"snippet": "public static Identifier id(String path) {\n return new Identifier(ModInit.ID, path);\n}"
}
] | import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import eu.pb4.polydecorations.ModInit;
import eu.pb4.polydecorations.util.ResourceUtils;
import eu.pb4.polymer.resourcepack.api.AssetPaths;
import eu.pb4.polymer.resourcepack.api.PolymerModelData;
import eu.pb4.polymer.resourcepack.api.PolymerResourcePackUtils;
import eu.pb4.sgui.api.elements.GuiElementBuilder;
import it.unimi.dsi.fastutil.chars.*;
import it.unimi.dsi.fastutil.objects.Object2ObjectMap;
import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap;
import net.minecraft.item.Item;
import net.minecraft.item.Items;
import net.minecraft.nbt.NbtCompound;
import net.minecraft.text.Style;
import net.minecraft.text.Text;
import net.minecraft.util.Identifier;
import net.minecraft.util.Pair;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.function.BiConsumer;
import java.util.function.Function;
import java.util.function.IntFunction;
import java.util.function.Supplier;
import static eu.pb4.polydecorations.util.DecorationsUtil.id; | 2,437 | package eu.pb4.polydecorations.ui;
public class UiResourceCreator {
public static final String BASE_MODEL = "minecraft:item/generated";
public static final String X32_MODEL = "polydecorations:sgui/button_32";
public static final String X32_RIGHT_MODEL = "polydecorations:sgui/button_32_right";
private static final Style STYLE = Style.EMPTY.withColor(0xFFFFFF).withFont(id("gui"));
private static final String ITEM_TEMPLATE = """
{
"parent": "|BASE|",
"textures": {
"layer0": "|ID|"
}
}
""".replace(" ", "").replace("\n", "");
private static final List<SlicedTexture> VERTICAL_PROGRESS = new ArrayList<>();
private static final List<SlicedTexture> HORIZONTAL_PROGRESS = new ArrayList<>();
private static final List<Pair<PolymerModelData, String>> SIMPLE_MODEL = new ArrayList<>();
private static final Char2IntMap SPACES = new Char2IntOpenHashMap();
private static final Char2ObjectMap<Identifier> TEXTURES = new Char2ObjectOpenHashMap<>();
private static final Object2ObjectMap<Pair<Character, Character>, Identifier> TEXTURES_POLYDEX = new Object2ObjectOpenHashMap<>();
private static final List<String> TEXTURES_NUMBERS = new ArrayList<>();
private static char character = 'a';
private static final char CHEST_SPACE0 = character++;
private static final char CHEST_SPACE1 = character++;
public static Supplier<GuiElementBuilder> icon16(String path) {
var model = genericIconRaw(Items.ALLIUM, path, BASE_MODEL);
return () -> new GuiElementBuilder(model.item()).setName(Text.empty()).hideFlags().setCustomModelData(model.value());
}
public static Supplier<GuiElementBuilder> icon32(String path) {
var model = genericIconRaw(Items.ALLIUM, path, X32_MODEL);
return () -> new GuiElementBuilder(model.item()).setName(Text.empty()).hideFlags().setCustomModelData(model.value());
}
public static IntFunction<GuiElementBuilder> icon32Color(String path) {
var model = genericIconRaw(Items.LEATHER_LEGGINGS, path, X32_MODEL);
return (i) -> {
var b = new GuiElementBuilder(model.item()).setName(Text.empty()).hideFlags().setCustomModelData(model.value());
var display = new NbtCompound();
display.putInt("color", i);
b.getOrCreateNbt().put("display", display);
return b;
};
}
public static IntFunction<GuiElementBuilder> icon16(String path, int size) {
var models = new PolymerModelData[size];
for (var i = 0; i < size; i++) {
models[i] = genericIconRaw(Items.ALLIUM, path + "_" + i, BASE_MODEL);
}
return (i) -> new GuiElementBuilder(models[i].item()).setName(Text.empty()).hideFlags().setCustomModelData(models[i].value());
}
public static IntFunction<GuiElementBuilder> horizontalProgress16(String path, int start, int stop, boolean reverse) {
return genericProgress(path, start, stop, reverse, BASE_MODEL, HORIZONTAL_PROGRESS);
}
public static IntFunction<GuiElementBuilder> horizontalProgress32(String path, int start, int stop, boolean reverse) {
return genericProgress(path, start, stop, reverse, X32_MODEL, HORIZONTAL_PROGRESS);
}
public static IntFunction<GuiElementBuilder> horizontalProgress32Right(String path, int start, int stop, boolean reverse) {
return genericProgress(path, start, stop, reverse, X32_RIGHT_MODEL, HORIZONTAL_PROGRESS);
}
public static IntFunction<GuiElementBuilder> verticalProgress32(String path, int start, int stop, boolean reverse) {
return genericProgress(path, start, stop, reverse, X32_MODEL, VERTICAL_PROGRESS);
}
public static IntFunction<GuiElementBuilder> verticalProgress32Right(String path, int start, int stop, boolean reverse) {
return genericProgress(path, start, stop, reverse, X32_RIGHT_MODEL, VERTICAL_PROGRESS);
}
public static IntFunction<GuiElementBuilder> verticalProgress16(String path, int start, int stop, boolean reverse) {
return genericProgress(path, start, stop, reverse, BASE_MODEL, VERTICAL_PROGRESS);
}
public static IntFunction<GuiElementBuilder> genericProgress(String path, int start, int stop, boolean reverse, String base, List<SlicedTexture> progressType) {
var models = new PolymerModelData[stop - start];
progressType.add(new SlicedTexture(path, start, stop, reverse));
for (var i = start; i < stop; i++) {
models[i - start] = genericIconRaw(Items.ALLIUM, "gen/" + path + "_" + i, base);
}
return (i) -> new GuiElementBuilder(models[i].item()).setName(Text.empty()).hideFlags().setCustomModelData(models[i].value());
}
public static PolymerModelData genericIconRaw(Item item, String path, String base) {
var model = PolymerResourcePackUtils.requestModel(item, elementPath(path));
SIMPLE_MODEL.add(new Pair<>(model, base));
return model;
}
private static Identifier elementPath(String path) {
return id("sgui/elements/" + path);
}
public static Function<Text, Text> background(String path) {
var builder = new StringBuilder().append(CHEST_SPACE0);
var c = (character++);
builder.append(c);
builder.append(CHEST_SPACE1);
TEXTURES.put(c, id("sgui/" + path));
return new TextBuilders(Text.literal(builder.toString()).setStyle(STYLE));
}
public static Pair<Text, Text> polydexBackground(String path) {
var c = (character++);
var d = (character++);
TEXTURES_POLYDEX.put(new Pair<>(c, d), id("sgui/polydex/" + path));
return new Pair<>(
Text.literal(Character.toString(c)).setStyle(STYLE),
Text.literal(Character.toString(d)).setStyle(STYLE)
);
}
public static void setup() {
SPACES.put(CHEST_SPACE0, -8);
SPACES.put(CHEST_SPACE1, -168);
| package eu.pb4.polydecorations.ui;
public class UiResourceCreator {
public static final String BASE_MODEL = "minecraft:item/generated";
public static final String X32_MODEL = "polydecorations:sgui/button_32";
public static final String X32_RIGHT_MODEL = "polydecorations:sgui/button_32_right";
private static final Style STYLE = Style.EMPTY.withColor(0xFFFFFF).withFont(id("gui"));
private static final String ITEM_TEMPLATE = """
{
"parent": "|BASE|",
"textures": {
"layer0": "|ID|"
}
}
""".replace(" ", "").replace("\n", "");
private static final List<SlicedTexture> VERTICAL_PROGRESS = new ArrayList<>();
private static final List<SlicedTexture> HORIZONTAL_PROGRESS = new ArrayList<>();
private static final List<Pair<PolymerModelData, String>> SIMPLE_MODEL = new ArrayList<>();
private static final Char2IntMap SPACES = new Char2IntOpenHashMap();
private static final Char2ObjectMap<Identifier> TEXTURES = new Char2ObjectOpenHashMap<>();
private static final Object2ObjectMap<Pair<Character, Character>, Identifier> TEXTURES_POLYDEX = new Object2ObjectOpenHashMap<>();
private static final List<String> TEXTURES_NUMBERS = new ArrayList<>();
private static char character = 'a';
private static final char CHEST_SPACE0 = character++;
private static final char CHEST_SPACE1 = character++;
public static Supplier<GuiElementBuilder> icon16(String path) {
var model = genericIconRaw(Items.ALLIUM, path, BASE_MODEL);
return () -> new GuiElementBuilder(model.item()).setName(Text.empty()).hideFlags().setCustomModelData(model.value());
}
public static Supplier<GuiElementBuilder> icon32(String path) {
var model = genericIconRaw(Items.ALLIUM, path, X32_MODEL);
return () -> new GuiElementBuilder(model.item()).setName(Text.empty()).hideFlags().setCustomModelData(model.value());
}
public static IntFunction<GuiElementBuilder> icon32Color(String path) {
var model = genericIconRaw(Items.LEATHER_LEGGINGS, path, X32_MODEL);
return (i) -> {
var b = new GuiElementBuilder(model.item()).setName(Text.empty()).hideFlags().setCustomModelData(model.value());
var display = new NbtCompound();
display.putInt("color", i);
b.getOrCreateNbt().put("display", display);
return b;
};
}
public static IntFunction<GuiElementBuilder> icon16(String path, int size) {
var models = new PolymerModelData[size];
for (var i = 0; i < size; i++) {
models[i] = genericIconRaw(Items.ALLIUM, path + "_" + i, BASE_MODEL);
}
return (i) -> new GuiElementBuilder(models[i].item()).setName(Text.empty()).hideFlags().setCustomModelData(models[i].value());
}
public static IntFunction<GuiElementBuilder> horizontalProgress16(String path, int start, int stop, boolean reverse) {
return genericProgress(path, start, stop, reverse, BASE_MODEL, HORIZONTAL_PROGRESS);
}
public static IntFunction<GuiElementBuilder> horizontalProgress32(String path, int start, int stop, boolean reverse) {
return genericProgress(path, start, stop, reverse, X32_MODEL, HORIZONTAL_PROGRESS);
}
public static IntFunction<GuiElementBuilder> horizontalProgress32Right(String path, int start, int stop, boolean reverse) {
return genericProgress(path, start, stop, reverse, X32_RIGHT_MODEL, HORIZONTAL_PROGRESS);
}
public static IntFunction<GuiElementBuilder> verticalProgress32(String path, int start, int stop, boolean reverse) {
return genericProgress(path, start, stop, reverse, X32_MODEL, VERTICAL_PROGRESS);
}
public static IntFunction<GuiElementBuilder> verticalProgress32Right(String path, int start, int stop, boolean reverse) {
return genericProgress(path, start, stop, reverse, X32_RIGHT_MODEL, VERTICAL_PROGRESS);
}
public static IntFunction<GuiElementBuilder> verticalProgress16(String path, int start, int stop, boolean reverse) {
return genericProgress(path, start, stop, reverse, BASE_MODEL, VERTICAL_PROGRESS);
}
public static IntFunction<GuiElementBuilder> genericProgress(String path, int start, int stop, boolean reverse, String base, List<SlicedTexture> progressType) {
var models = new PolymerModelData[stop - start];
progressType.add(new SlicedTexture(path, start, stop, reverse));
for (var i = start; i < stop; i++) {
models[i - start] = genericIconRaw(Items.ALLIUM, "gen/" + path + "_" + i, base);
}
return (i) -> new GuiElementBuilder(models[i].item()).setName(Text.empty()).hideFlags().setCustomModelData(models[i].value());
}
public static PolymerModelData genericIconRaw(Item item, String path, String base) {
var model = PolymerResourcePackUtils.requestModel(item, elementPath(path));
SIMPLE_MODEL.add(new Pair<>(model, base));
return model;
}
private static Identifier elementPath(String path) {
return id("sgui/elements/" + path);
}
public static Function<Text, Text> background(String path) {
var builder = new StringBuilder().append(CHEST_SPACE0);
var c = (character++);
builder.append(c);
builder.append(CHEST_SPACE1);
TEXTURES.put(c, id("sgui/" + path));
return new TextBuilders(Text.literal(builder.toString()).setStyle(STYLE));
}
public static Pair<Text, Text> polydexBackground(String path) {
var c = (character++);
var d = (character++);
TEXTURES_POLYDEX.put(new Pair<>(c, d), id("sgui/polydex/" + path));
return new Pair<>(
Text.literal(Character.toString(c)).setStyle(STYLE),
Text.literal(Character.toString(d)).setStyle(STYLE)
);
}
public static void setup() {
SPACES.put(CHEST_SPACE0, -8);
SPACES.put(CHEST_SPACE1, -168);
| if (ModInit.DYNAMIC_ASSETS) { | 0 | 2023-12-10 16:20:36+00:00 | 4k |
i-moonlight/Movie_Manager | backend/src/main/java/ch/xxx/moviemanager/usecase/service/JwtTokenService.java | [
{
"identifier": "Role",
"path": "backend/src/main/java/ch/xxx/moviemanager/domain/common/Role.java",
"snippet": "public enum Role implements GrantedAuthority{\n\tUSERS, GUEST;\n\n\t@Override\n\tpublic String getAuthority() {\t\t\n\t\treturn this.name();\n\t}\n\t\n}"
},
{
"identifier": "AuthenticationException",
"path": "backend/src/main/java/ch/xxx/moviemanager/domain/exceptions/AuthenticationException.java",
"snippet": "public class AuthenticationException extends RuntimeException {\n\n\tprivate static final long serialVersionUID = -4778173207515812187L;\n\t\n\tpublic AuthenticationException(String message) {\n\t\tsuper(message);\n\t}\n\n\tpublic AuthenticationException(String message, Throwable th) {\n\t\tsuper(message, th);\n\t}\n}"
},
{
"identifier": "RevokedToken",
"path": "backend/src/main/java/ch/xxx/moviemanager/domain/model/entity/RevokedToken.java",
"snippet": "@Entity\npublic class RevokedToken extends EntityBase {\n\t@NotBlank\n\t@Size(max=255)\n\tprivate String name;\n\t@NotBlank\n\t@Size(max=255)\n\tprivate String uuid;\n\t@NotNull\t\n\tprivate LocalDateTime lastLogout;\n\t\n\tpublic RevokedToken() {\t\t\n\t}\n\n\tpublic RevokedToken(String name, String uuid, LocalDateTime lastLogout) {\n\t\tsuper();\n\t\tthis.name = name;\n\t\tthis.uuid = uuid;\n\t\tthis.lastLogout = lastLogout;\n\t}\n\n\tpublic String getName() {\n\t\treturn name;\n\t}\n\n\tpublic void setName(String name) {\n\t\tthis.name = name;\n\t}\n\n\tpublic LocalDateTime getLastLogout() {\n\t\treturn lastLogout;\n\t}\n\n\tpublic void setLastLogout(LocalDateTime lastLogout) {\n\t\tthis.lastLogout = lastLogout;\n\t}\n\n\tpublic String getUuid() {\n\t\treturn uuid;\n\t}\n\n\tpublic void setUuid(String uuid) {\n\t\tthis.uuid = uuid;\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\tfinal int prime = 31;\n\t\tint result = super.hashCode();\n\t\tresult = prime * result + Objects.hash(lastLogout, name, uuid);\n\t\treturn result;\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj)\n\t\t\treturn true;\n\t\tif (!super.equals(obj))\n\t\t\treturn false;\n\t\tif (getClass() != obj.getClass())\n\t\t\treturn false;\n\t\tRevokedToken other = (RevokedToken) obj;\n\t\treturn Objects.equals(lastLogout, other.lastLogout) && Objects.equals(name, other.name)\n\t\t\t\t&& Objects.equals(uuid, other.uuid);\n\t}\n}"
},
{
"identifier": "JwtUtils",
"path": "backend/src/main/java/ch/xxx/moviemanager/domain/utils/JwtUtils.java",
"snippet": "public class JwtUtils {\n\tpublic static final String AUTHORIZATION = HttpHeaders.AUTHORIZATION.toLowerCase();\n\tpublic static final String TOKENAUTHKEY = \"auth\";\n\tpublic static final String TOKENLASTMSGKEY = \"lastmsg\";\n\tpublic static final String UUID = \"uuid\";\n\tpublic static final String BEARER = \"Bearer \";\n\tpublic static final String AUTHORITY = \"authority\";\n\n\tpublic static Optional<String> extractToken(Map<String,String> headers) {\n\t\tString authStr = headers.get(AUTHORIZATION);\n\t\treturn extractToken(Optional.ofNullable(authStr));\n\t}\n\n\tprivate static Optional<String> extractToken(Optional<String> authStr) {\n\t\tif (authStr.isPresent()) {\n\t\t\tauthStr = Optional.ofNullable(authStr.get().startsWith(BEARER) ? authStr.get().substring(7) : null);\n\t\t}\n\t\treturn authStr;\n\t}\n\n\tpublic static Optional<Jws<Claims>> getClaims(Optional<String> token, Key jwtTokenKey) {\n\t\tif (!token.isPresent()) {\n\t\t\treturn Optional.empty();\n\t\t}\n\t\treturn Optional.of(Jwts.parserBuilder().setSigningKey(jwtTokenKey).build().parseClaimsJws(token.get()));\n\t}\n\t\n\tpublic static String getTokenRoles(Map<String,String> headers, Key jwtTokenKey) {\n\t\tOptional<String> tokenStr = extractToken(headers);\n\t\tOptional<Jws<Claims>> claims = JwtUtils.getClaims(tokenStr, jwtTokenKey);\n\t\tif (claims.isPresent() && new Date().before(claims.get().getBody().getExpiration())) {\n\t\t\treturn claims.get().getBody().get(TOKENAUTHKEY).toString();\n\t\t}\n\t\treturn \"\";\n\t}\n\n\tpublic static TokenSubjectRole getTokenUserRoles(Map<String,String> headers,\n\t\t\tKey jwtTokenKey) {\n\t\tOptional<String> tokenStr = extractToken(headers);\n\t\tOptional<Jws<Claims>> claims = JwtUtils.getClaims(tokenStr, jwtTokenKey);\n\t\tif (claims.isPresent() && new Date().before(claims.get().getBody().getExpiration())) {\n\t\t\treturn new TokenSubjectRole(claims.get().getBody().getSubject(),\n\t\t\t\t\tclaims.get().getBody().get(TOKENAUTHKEY).toString());\n\t\t}\n\t\treturn new TokenSubjectRole(null, null);\n\t}\n\n\tpublic static boolean checkToken(HttpServletRequest request, Key jwtTokenKey) {\n\t\tOptional<String> tokenStr = JwtUtils\n\t\t\t\t.extractToken(Optional.ofNullable(request.getHeader(JwtUtils.AUTHORIZATION)));\n\t\tOptional<Jws<Claims>> claims = JwtUtils.getClaims(tokenStr, jwtTokenKey);\n\t\tif (claims.isPresent() && new Date().before(claims.get().getBody().getExpiration())\n\t\t\t\t&& claims.get().getBody().get(TOKENAUTHKEY).toString().contains(Role.USERS.name())\n\t\t\t\t&& !claims.get().getBody().get(TOKENAUTHKEY).toString().contains(Role.GUEST.name())) {\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n}"
}
] | import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.Base64;
import java.util.Collection;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.stream.Collectors;
import jakarta.annotation.PostConstruct;
import javax.crypto.SecretKey;
import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.AuthorizationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Service;
import ch.xxx.moviemanager.domain.common.Role;
import ch.xxx.moviemanager.domain.exceptions.AuthenticationException;
import ch.xxx.moviemanager.domain.model.entity.RevokedToken;
import ch.xxx.moviemanager.domain.utils.JwtUtils;
import ch.xxx.moviemanager.domain.utils.TokenSubjectRole;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.JwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys; | 1,949 | /* Copyright 2019 Sven Loesekann
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package ch.xxx.moviemanager.usecase.service;
@Service
public class JwtTokenService {
private static final Logger LOG = LoggerFactory.getLogger(JwtTokenService.class);
public record UserNameUuid(String userName, String uuid) {
}
private final List<UserNameUuid> loggedOutUsers = new CopyOnWriteArrayList<>();
@Value("${security.jwt.token.secret-key}")
private String secretKey;
@Value("${security.jwt.token.expire-length}")
private long validityInMilliseconds; // 1 min
private SecretKey jwtTokenKey;
@PostConstruct
public void init() {
this.jwtTokenKey = Keys
.hmacShaKeyFor(Base64.getUrlDecoder().decode(secretKey.getBytes(StandardCharsets.ISO_8859_1)));
}
public void updateLoggedOutUsers(List<RevokedToken> revokedTokens) {
this.loggedOutUsers.clear();
this.loggedOutUsers.addAll(revokedTokens.stream()
.map(myRevokedToken -> new UserNameUuid(myRevokedToken.getName(), myRevokedToken.getUuid())).toList());
}
public TokenSubjectRole getTokenUserRoles(Map<String, String> headers) { | /* Copyright 2019 Sven Loesekann
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package ch.xxx.moviemanager.usecase.service;
@Service
public class JwtTokenService {
private static final Logger LOG = LoggerFactory.getLogger(JwtTokenService.class);
public record UserNameUuid(String userName, String uuid) {
}
private final List<UserNameUuid> loggedOutUsers = new CopyOnWriteArrayList<>();
@Value("${security.jwt.token.secret-key}")
private String secretKey;
@Value("${security.jwt.token.expire-length}")
private long validityInMilliseconds; // 1 min
private SecretKey jwtTokenKey;
@PostConstruct
public void init() {
this.jwtTokenKey = Keys
.hmacShaKeyFor(Base64.getUrlDecoder().decode(secretKey.getBytes(StandardCharsets.ISO_8859_1)));
}
public void updateLoggedOutUsers(List<RevokedToken> revokedTokens) {
this.loggedOutUsers.clear();
this.loggedOutUsers.addAll(revokedTokens.stream()
.map(myRevokedToken -> new UserNameUuid(myRevokedToken.getName(), myRevokedToken.getUuid())).toList());
}
public TokenSubjectRole getTokenUserRoles(Map<String, String> headers) { | return JwtUtils.getTokenUserRoles(headers, this.jwtTokenKey); | 3 | 2023-12-11 13:53:51+00:00 | 4k |
i-moonlight/Suricate | src/test/java/com/michelin/suricate/services/api/PersonalAccessTokenServiceTest.java | [
{
"identifier": "PersonalAccessToken",
"path": "src/main/java/com/michelin/suricate/model/entities/PersonalAccessToken.java",
"snippet": "@Entity\n@Getter\n@Setter\n@ToString(callSuper = true)\n@NoArgsConstructor\npublic class PersonalAccessToken extends AbstractAuditingEntity<Long> {\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private Long id;\n\n @Column(nullable = false, unique = true)\n private String name;\n\n @Column(nullable = false, unique = true)\n private Long checksum;\n\n @ToString.Exclude\n @ManyToOne\n @PrimaryKeyJoinColumn(name = \"userId\", referencedColumnName = \"ID\")\n private User user;\n\n /**\n * Hashcode method.\n * Do not use lombok @EqualsAndHashCode method as it calls super method\n * then call the self-defined child Hashcode method\n *\n * @return The hash code\n */\n @Override\n public int hashCode() {\n return super.hashCode();\n }\n\n /**\n * Equals method.\n * Do not use lombok @EqualsAndHashCode method as it calls super method\n * then call the self-defined child Equals method\n *\n * @param other The other object to compare\n * @return true if equals, false otherwise\n */\n @Override\n public boolean equals(Object other) {\n return super.equals(other);\n }\n}"
},
{
"identifier": "Role",
"path": "src/main/java/com/michelin/suricate/model/entities/Role.java",
"snippet": "@Entity(name = \"Role\")\n@Getter\n@Setter\n@ToString\n@NoArgsConstructor\npublic class Role extends AbstractEntity<Long> {\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private Long id;\n\n @Column(nullable = false, unique = true)\n private String name;\n\n @Column(nullable = false)\n private String description;\n\n @ToString.Exclude\n @ManyToMany(mappedBy = \"roles\")\n private Set<User> users = new LinkedHashSet<>();\n\n /**\n * Hashcode method.\n * Do not use lombok @EqualsAndHashCode method as it calls super method\n * then call the self-defined child Hashcode method\n *\n * @return The hash code\n */\n @Override\n public int hashCode() {\n return super.hashCode();\n }\n\n /**\n * Equals method.\n * Do not use lombok @EqualsAndHashCode method as it calls super method\n * then call the self-defined child Equals method\n *\n * @param other The other object to compare\n * @return true if equals, false otherwise\n */\n @Override\n public boolean equals(Object other) {\n return super.equals(other);\n }\n}"
},
{
"identifier": "User",
"path": "src/main/java/com/michelin/suricate/model/entities/User.java",
"snippet": "@Entity\n@Table(name = \"users\")\n@Getter\n@Setter\n@ToString\n@NoArgsConstructor\npublic class User extends AbstractEntity<Long> {\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private Long id;\n\n @Column(nullable = false, unique = true)\n private String username;\n\n @Column\n private String password;\n\n @Column\n private String firstname;\n\n @Column\n private String lastname;\n\n @Column(unique = true)\n private String email;\n\n @Column\n private String avatarUrl;\n\n @Enumerated(value = EnumType.STRING)\n @Column(name = \"auth_mode\", nullable = false, length = 20)\n private AuthenticationProvider authenticationMethod;\n\n @ToString.Exclude\n @ManyToMany\n @JoinTable(name = \"user_role\", joinColumns = {@JoinColumn(name = \"user_id\")}, inverseJoinColumns = {\n @JoinColumn(name = \"role_id\")})\n private Set<Role> roles = new LinkedHashSet<>();\n\n @ToString.Exclude\n @ManyToMany(mappedBy = \"users\")\n private Set<Project> projects = new LinkedHashSet<>();\n\n @ToString.Exclude\n @OneToMany(mappedBy = \"user\", cascade = CascadeType.REMOVE)\n private Set<UserSetting> userSettings = new LinkedHashSet<>();\n\n /**\n * Hashcode method.\n * Do not use lombok @EqualsAndHashCode method as it calls super method\n * then call the self-defined child Hashcode method\n *\n * @return The hash code\n */\n @Override\n public int hashCode() {\n return super.hashCode();\n }\n\n /**\n * Equals method.\n * Do not use lombok @EqualsAndHashCode method as it calls super method\n * then call the self-defined child Equals method\n *\n * @param other The other object to compare\n * @return true if equals, false otherwise\n */\n @Override\n public boolean equals(Object other) {\n return super.equals(other);\n }\n}"
},
{
"identifier": "PersonalAccessTokenRepository",
"path": "src/main/java/com/michelin/suricate/repositories/PersonalAccessTokenRepository.java",
"snippet": "@Repository\npublic interface PersonalAccessTokenRepository\n extends CrudRepository<PersonalAccessToken, Long>, JpaSpecificationExecutor<PersonalAccessToken> {\n /**\n * Find all tokens of given user.\n *\n * @param user The user\n * @return The user tokens\n */\n List<PersonalAccessToken> findAllByUser(User user);\n\n /**\n * Find a token by given name and user.\n *\n * @param name The token name\n * @param user The user\n * @return The token\n */\n Optional<PersonalAccessToken> findByNameAndUser(String name, User user);\n\n /**\n * Find a token by given checksum.\n *\n * @param checksum The token checksum\n * @return The token\n */\n @EntityGraph(attributePaths = \"user.roles\")\n Optional<PersonalAccessToken> findByChecksum(Long checksum);\n}"
},
{
"identifier": "LocalUser",
"path": "src/main/java/com/michelin/suricate/security/LocalUser.java",
"snippet": "@Getter\n@Setter\n@EqualsAndHashCode(callSuper = true)\npublic class LocalUser extends User implements OAuth2User, OidcUser {\n /**\n * The user.\n */\n private com.michelin.suricate.model.entities.User user;\n\n /**\n * The OAuth2/OIDC attributes.\n */\n private Map<String, Object> attributes;\n\n /**\n * The OIDC token.\n */\n private OidcIdToken idToken;\n\n /**\n * The OIDC user info.\n */\n private OidcUserInfo userInfo;\n\n /**\n * Constructor.\n *\n * @param user The user entity\n * @param attributes The OAuth2 attributes\n */\n public LocalUser(com.michelin.suricate.model.entities.User user, Map<String, Object> attributes) {\n super(user.getUsername(), user.getPassword() == null ? StringUtils.EMPTY : user.getPassword(), true, true, true,\n true,\n user.getRoles().stream().map(role -> new SimpleGrantedAuthority(role.getName()))\n .toList());\n this.user = user;\n this.attributes = attributes;\n }\n\n /**\n * Constructor.\n *\n * @param user The user entity\n * @param attributes The OAuth2 attributes\n */\n public LocalUser(com.michelin.suricate.model.entities.User user, Map<String, Object> attributes,\n OidcIdToken idToken, OidcUserInfo userInfo) {\n super(user.getUsername(), user.getPassword() == null ? StringUtils.EMPTY : user.getPassword(), true, true, true,\n true,\n user.getRoles().stream().map(role -> new SimpleGrantedAuthority(role.getName()))\n .toList());\n this.user = user;\n this.attributes = attributes;\n this.idToken = idToken;\n this.userInfo = userInfo;\n }\n\n /**\n * Get the OAuth2 attributes.\n *\n * @return The OAuth2 attributes\n */\n @Override\n public Map<String, Object> getAttributes() {\n return attributes;\n }\n\n /**\n * Get the username.\n *\n * @return The username\n */\n @Override\n public String getName() {\n return user.getUsername();\n }\n\n @Override\n public Map<String, Object> getClaims() {\n return this.attributes;\n }\n\n @Override\n public OidcUserInfo getUserInfo() {\n return this.userInfo;\n }\n\n @Override\n public OidcIdToken getIdToken() {\n return this.idToken;\n }\n}"
}
] | import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.argThat;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import com.michelin.suricate.model.entities.PersonalAccessToken;
import com.michelin.suricate.model.entities.Role;
import com.michelin.suricate.model.entities.User;
import com.michelin.suricate.repositories.PersonalAccessTokenRepository;
import com.michelin.suricate.security.LocalUser;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension; | 2,273 | package com.michelin.suricate.services.api;
@ExtendWith(MockitoExtension.class)
class PersonalAccessTokenServiceTest {
@Mock
private PersonalAccessTokenRepository personalAccessTokenRepository;
@InjectMocks
private PersonalAccessTokenService personalAccessTokenService;
@Test
void shouldFindAllByUser() { | package com.michelin.suricate.services.api;
@ExtendWith(MockitoExtension.class)
class PersonalAccessTokenServiceTest {
@Mock
private PersonalAccessTokenRepository personalAccessTokenRepository;
@InjectMocks
private PersonalAccessTokenService personalAccessTokenService;
@Test
void shouldFindAllByUser() { | PersonalAccessToken personalAccessToken = new PersonalAccessToken(); | 0 | 2023-12-11 11:28:37+00:00 | 4k |
NaerQAQ/js4bukkit | src/main/java/org/js4bukkit/thread/annotations/impl/AutoStartTaskProcessorImpl.java | [
{
"identifier": "AnnotatedClassProcessorInterface",
"path": "src/main/java/org/js4bukkit/annotations/processors/interfaces/AnnotatedClassProcessorInterface.java",
"snippet": "public interface AnnotatedClassProcessorInterface {\n /**\n * 处理前调用的方法。\n */\n void before();\n\n /**\n * 对带有指定注解的类进行处理。\n *\n * @param clazz 带有指定注解的类对象\n * @throws Exception 可能的抛出异常,将交由 {@link #exception(Class, Exception)} 方法处理\n */\n void process(Class<?> clazz) throws Exception;\n\n /**\n * 处理 {@link #process(Class)} 方法抛出的异常。\n *\n * @param clazz 抛出异常的带有指定注解的类对象\n * @param exception 抛出的异常\n */\n void exception(Class<?> clazz, Exception exception);\n\n /**\n * 当所有类都处理完毕后调用的方法\n */\n void after();\n}"
},
{
"identifier": "Scheduler",
"path": "src/main/java/org/js4bukkit/thread/Scheduler.java",
"snippet": "@Setter\n@Getter\n@Accessors(chain = true)\npublic class Scheduler {\n /**\n * {@link Runnable} 对象。\n *\n * <p>\n * 若没有使用 {@link BukkitRunnable} 中的一些方法,则推荐直接传入 {@link Runnable} 对象。\n * </p>\n *\n * @see BukkitRunnable\n */\n private Runnable runnable;\n\n /**\n * {@link BukkitRunnable} 对象。\n */\n private BukkitRunnable bukkitRunnable;\n\n /**\n * 任务类型。\n */\n private SchedulerTypeEnum schedulerTypeEnum;\n\n /**\n * 任务执行模式。\n */\n private SchedulerExecutionMode schedulerExecutionMode;\n\n /**\n * 延迟。\n *\n * <p>\n * 仅在 {@link #schedulerTypeEnum} 为非 {@link SchedulerTypeEnum#RUN} 时有用。\n * </p>\n */\n private int delay;\n\n /**\n * 重复间隔。\n *\n * <p>\n * 仅在 {@link #schedulerTypeEnum} 为非 {@link SchedulerTypeEnum#RUN} 时有用。\n * </p>\n */\n private int period;\n\n /**\n * 运行任务调度器,根据设定的参数执行相应的任务。\n */\n public void run() {\n BukkitRunnable finalBukkitRunnable;\n\n Js4Bukkit js4Bukkit = Js4Bukkit.getInstance();\n\n // 如果传入的为 runnable 则转换为 bukkit runnable\n if (runnable == null) {\n finalBukkitRunnable = bukkitRunnable;\n } else {\n finalBukkitRunnable = new BukkitRunnable() {\n @Override\n public void run() {\n runnable.run();\n }\n };\n }\n\n switch (schedulerTypeEnum) {\n case RUN:\n if (schedulerExecutionMode == SchedulerExecutionMode.SYNC) {\n finalBukkitRunnable.runTask(js4Bukkit);\n } else {\n finalBukkitRunnable.runTaskAsynchronously(js4Bukkit);\n }\n return;\n\n case LATER:\n if (schedulerExecutionMode == SchedulerExecutionMode.SYNC) {\n finalBukkitRunnable.runTaskLater(js4Bukkit, delay);\n } else {\n finalBukkitRunnable.runTaskLaterAsynchronously(js4Bukkit, delay);\n }\n return;\n\n case TIMER:\n if (schedulerExecutionMode == SchedulerExecutionMode.SYNC) {\n finalBukkitRunnable.runTaskTimer(js4Bukkit, delay, period);\n } else {\n finalBukkitRunnable.runTaskTimerAsynchronously(js4Bukkit, delay, period);\n }\n return;\n\n case NEW_THREAD:\n if (schedulerExecutionMode == SchedulerExecutionMode.SYNC) {\n finalBukkitRunnable.runTask(js4Bukkit);\n } else {\n new Thread(finalBukkitRunnable).start();\n }\n }\n }\n}"
},
{
"identifier": "SchedulerExecutionMode",
"path": "src/main/java/org/js4bukkit/thread/enums/SchedulerExecutionMode.java",
"snippet": "public enum SchedulerExecutionMode {\n /**\n * 同步执行。\n */\n SYNC,\n\n /**\n * 异步执行。\n */\n ASYNC\n}"
},
{
"identifier": "SchedulerTypeEnum",
"path": "src/main/java/org/js4bukkit/thread/enums/SchedulerTypeEnum.java",
"snippet": "public enum SchedulerTypeEnum {\n /**\n * 直接运行。\n */\n RUN,\n\n /**\n * 重复运行。\n */\n TIMER,\n\n /**\n * 延迟运行。\n */\n LATER,\n\n /**\n * 新建线程\n */\n NEW_THREAD\n}"
},
{
"identifier": "QuickUtils",
"path": "src/main/java/org/js4bukkit/utils/common/text/QuickUtils.java",
"snippet": "@UtilityClass\npublic class QuickUtils {\n /**\n * 向控制台发送输出消息。\n *\n * @param consoleMessageTypeEnum 信息类型\n * @param message 要处理的发向控制台的字符串\n * @param params 替换的可选参数\n */\n public static void sendMessage(ConsoleMessageTypeEnum consoleMessageTypeEnum, String message, String... params) {\n StringBuilder prefix = new StringBuilder()\n .append(\"&f[&6Js4Bukkit&f] \");\n\n switch (consoleMessageTypeEnum) {\n case DEBUG:\n prefix.append(\"&e[DEBUG] &e\");\n break;\n\n case ERROR:\n prefix.append(\"&4[ERROR] &c\");\n break;\n\n case NORMAL:\n prefix.append(\"&f\");\n break;\n\n default:\n case NO_PREFIX:\n prefix.setLength(0);\n break;\n }\n\n Bukkit.getConsoleSender().sendMessage(\n StringUtils.handle(prefix + message, params)\n );\n }\n\n /**\n * 读取语言配置文件内对应键值字符串列表,向命令发送者发送输出消息。\n *\n * @param commandSender 命令发送者\n * @param key 键值\n * @param params 替换的可选参数\n */\n public static void sendMessageByKey(CommandSender commandSender, String key, String... params) {\n Yaml yaml = ConfigManager.getLanguage();\n\n List<String> messages = StringUtils.handle(\n yaml.getStringList(key), params\n );\n\n messages.forEach(commandSender::sendMessage);\n }\n\n /**\n * 读取语言配置文件内对应键值字符串列表,向控制台发送输出消息。\n *\n * @param consoleMessageTypeEnum 信息类型\n * @param key 键值\n * @param params 替换的可选参数\n */\n public static void sendMessageByKey(ConsoleMessageTypeEnum consoleMessageTypeEnum, String key, String... params) {\n Yaml yaml = ConfigManager.getLanguage();\n\n List<String> messages = StringUtils.handle(\n yaml.getStringList(key), params\n );\n\n messages.forEach(message -> sendMessage(consoleMessageTypeEnum, message));\n }\n}"
},
{
"identifier": "ConsoleMessageTypeEnum",
"path": "src/main/java/org/js4bukkit/utils/common/text/enums/ConsoleMessageTypeEnum.java",
"snippet": "public enum ConsoleMessageTypeEnum {\n /**\n * 普通信息。\n */\n NORMAL,\n\n /**\n * 调试信息。\n */\n DEBUG,\n\n /**\n * 错误信息。\n */\n ERROR,\n\n /**\n * 无前缀信息。\n */\n NO_PREFIX\n}"
}
] | import org.bukkit.scheduler.BukkitRunnable;
import org.js4bukkit.annotations.processors.annotations.AutoAnnotationProcessor;
import org.js4bukkit.annotations.processors.interfaces.AnnotatedClassProcessorInterface;
import org.js4bukkit.thread.Scheduler;
import org.js4bukkit.thread.annotations.AutoStartTask;
import org.js4bukkit.thread.enums.SchedulerExecutionMode;
import org.js4bukkit.thread.enums.SchedulerTypeEnum;
import org.js4bukkit.utils.common.text.QuickUtils;
import org.js4bukkit.utils.common.text.enums.ConsoleMessageTypeEnum; | 2,280 | package org.js4bukkit.thread.annotations.impl;
/**
* {@link AutoStartTask} 注解处理器。
*
* @author NaerQAQ
* @version 1.0
* @since 2023/12/29
*/
@AutoAnnotationProcessor(
annotationClass = AutoStartTask.class
)
@SuppressWarnings("unused")
public class AutoStartTaskProcessorImpl implements AnnotatedClassProcessorInterface {
/**
* 处理前调用的方法。
*/
@Override
public void before() {
}
/**
* 对带有指定注解的类进行处理。
*
* @param clazz 带有指定注解的类对象
* @throws Exception 可能的抛出异常,将交由 {@link #exception(Class, Exception)} 方法处理
*/
@Override
public void process(Class<?> clazz) throws Exception {
String className = clazz.getName();
AutoStartTask annotation = clazz.getAnnotation(AutoStartTask.class);
BukkitRunnable bukkitRunnable = (BukkitRunnable) clazz.getDeclaredConstructor().newInstance();
int delay = annotation.delay();
int period = annotation.period();
SchedulerTypeEnum schedulerTypeEnum = annotation.schedulerTypeEnum();
SchedulerExecutionMode schedulerExecutionMode = annotation.schedulerExecutionMode();
| package org.js4bukkit.thread.annotations.impl;
/**
* {@link AutoStartTask} 注解处理器。
*
* @author NaerQAQ
* @version 1.0
* @since 2023/12/29
*/
@AutoAnnotationProcessor(
annotationClass = AutoStartTask.class
)
@SuppressWarnings("unused")
public class AutoStartTaskProcessorImpl implements AnnotatedClassProcessorInterface {
/**
* 处理前调用的方法。
*/
@Override
public void before() {
}
/**
* 对带有指定注解的类进行处理。
*
* @param clazz 带有指定注解的类对象
* @throws Exception 可能的抛出异常,将交由 {@link #exception(Class, Exception)} 方法处理
*/
@Override
public void process(Class<?> clazz) throws Exception {
String className = clazz.getName();
AutoStartTask annotation = clazz.getAnnotation(AutoStartTask.class);
BukkitRunnable bukkitRunnable = (BukkitRunnable) clazz.getDeclaredConstructor().newInstance();
int delay = annotation.delay();
int period = annotation.period();
SchedulerTypeEnum schedulerTypeEnum = annotation.schedulerTypeEnum();
SchedulerExecutionMode schedulerExecutionMode = annotation.schedulerExecutionMode();
| new Scheduler() | 1 | 2023-12-14 13:50:24+00:00 | 4k |
Rainnny7/Feather | src/main/java/me/braydon/feather/database/impl/redis/RedisRepository.java | [
{
"identifier": "Document",
"path": "src/main/java/me/braydon/feather/data/Document.java",
"snippet": "@ThreadSafe @Getter @ToString\npublic class Document<V> {\n /**\n * The key to use for the id field.\n */\n @NonNull private final String idKey;\n \n /**\n * The key of this document.\n */\n @NonNull private final Object key;\n \n /**\n * The mapped data of this document.\n * <p>\n * The key of this key-value pair is the identifier\n * for the field within this document. The value is\n * a tuple that contains the Java field, as well as\n * the field value.\n * </p>\n *\n * @see V for value type\n */\n private final Map<String, Tuple<java.lang.reflect.Field, V>> mappedData = Collections.synchronizedMap(new LinkedHashMap<>());\n \n public Document(@NonNull Object element) {\n Class<?> clazz = element.getClass(); // Get the element class\n String idKey = null; // The key for the id field\n for (java.lang.reflect.Field field : clazz.getDeclaredFields()) {\n // Field is missing the @Field annotation, skip it\n if (!field.isAnnotationPresent(Field.class)) {\n continue;\n }\n field.setAccessible(true); // Make our field accessible\n String key = FieldUtils.extractKey(field); // The key of the database field\n \n // The field is annotated with @Id, save it for later\n if (field.isAnnotationPresent(Id.class)) {\n idKey = key;\n }\n Class<?> fieldType = field.getType(); // The type of the field\n try {\n Object value = field.get(element); // The value of the field\n \n if (field.isAnnotationPresent(Serializable.class)) { // Serialize the field if @Serializable is present\n value = FeatherSettings.getGson().toJson(field.get(element));\n } else if (fieldType == UUID.class) { // Convert UUIDs into strings\n value = value.toString();\n }\n \n mappedData.put(key, new Tuple<>(field, (V) value)); // Store in our map\n } catch (IllegalAccessException ex) {\n throw new RuntimeException(ex);\n }\n }\n assert idKey != null; // We need an id key\n this.idKey = idKey; // Set our id key\n \n Tuple<java.lang.reflect.Field, V> key = mappedData.get(idKey); // Get the id from the data map\n if (key == null) { // The element is missing an id field\n throw new IllegalArgumentException(\"No @Id annotated field found in \" + clazz.getSimpleName());\n }\n this.key = key.getRight();\n }\n \n /**\n * Turn this document into a map.\n *\n * @return the mapped data\n * @see #mappedData for stored data\n */\n @NonNull\n public Map<String, V> toMappedData() {\n Map<String, V> mappedData = new LinkedHashMap<>(); // The mapped data\n for (Map.Entry<String, Tuple<java.lang.reflect.Field, V>> entry : this.mappedData.entrySet()) {\n mappedData.put(entry.getKey(), entry.getValue().getRight());\n }\n return mappedData;\n }\n}"
},
{
"identifier": "Repository",
"path": "src/main/java/me/braydon/feather/database/Repository.java",
"snippet": "@AllArgsConstructor @Getter(AccessLevel.PROTECTED)\npublic abstract class Repository<D extends IDatabase<?, ?>, ID, E> {\n /**\n * The database this repository belongs to.\n *\n * @see D for database\n */\n @NonNull private final D database;\n \n /**\n * The class for the entity this repository uses.\n *\n * @see E for entity\n */\n @NonNull private final Class<? extends E> entityClass;\n \n /**\n * Get the entity with the given id.\n *\n * @param id the entity id\n * @return the entity with the id, null if none\n * @see ID for id\n * @see E for entity\n */\n public abstract E find(@NonNull ID id);\n \n /**\n * Get all entities within this repository.\n *\n * @return the entities\n * @see E for entity\n */\n public abstract List<E> findAll();\n \n /**\n * Save the given entity to the database.\n *\n * @param entity the entity to save\n * @see E for entity\n */\n public void save(@NonNull E entity) {\n saveAll(entity);\n }\n \n /**\n * Save the given entities.\n *\n * @param entities the entities to save\n * @see E for entity\n */\n public abstract void saveAll(@NonNull E... entities);\n \n /**\n * Get the amount of stored entities.\n *\n * @return the amount of stored entities\n * @see E for entity\n */\n public abstract long count();\n \n /**\n * Drop the entity with the given id.\n *\n * @param id the entity id to drop\n * @see ID for id\n * @see E for entity\n */\n public abstract void dropById(@NonNull ID id);\n \n /**\n * Drop the given entity.\n *\n * @param entity the entity to drop\n * @see E for entity\n */\n public abstract void drop(@NonNull E entity);\n \n /**\n * Construct a new entity from the given mapped data.\n *\n * @param mappedData the mapped data to parse\n * @return the created entity, null if none\n * @see E for entity\n */\n protected final E newEntity(Map<String, ?> mappedData) {\n if (mappedData == null) { // No mapped data given\n return null;\n }\n try {\n Constructor<? extends E> constructor = entityClass.getConstructor(); // Get the no args constructor\n E entity = constructor.newInstance(); // Create the entity\n \n // Get the field tagged with @Id\n for (Field field : entityClass.getDeclaredFields()) {\n String key = FieldUtils.extractKey(field); // The key of the database field\n Class<?> type = field.getType(); // The type of the field\n Object value = mappedData.get(key); // The value of the field\n \n // Field is serializable and is a string, deserialize it using Gson\n if (field.isAnnotationPresent(Serializable.class) && value.getClass() == String.class) {\n value = FeatherSettings.getGson().fromJson((String) value, type);\n } else if (type == UUID.class && value != null) { // Type is a UUID, convert it\n value = UUID.fromString((String) value);\n }\n \n // Set the value of the field\n field.setAccessible(true);\n field.set(entity, value);\n }\n return entity;\n } catch (NoSuchMethodException ex) { // We need our no args constructor\n throw new IllegalStateException(\"Entity \" + entityClass.getName() + \" is missing no args constructor\");\n } catch (InvocationTargetException | InstantiationException | IllegalAccessException ex) {\n ex.printStackTrace();\n }\n return null;\n }\n}"
}
] | import io.lettuce.core.api.sync.RedisCommands;
import lombok.NonNull;
import me.braydon.feather.data.Document;
import me.braydon.feather.database.Repository;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List; | 2,335 | /*
* Copyright (c) 2023 Braydon (Rainnny). All rights reserved.
*
* For inquiries, please contact [email protected]
*/
package me.braydon.feather.database.impl.redis;
/**
* The {@link Redis} {@link Repository} implementation.
*
* @author Braydon
* @param <ID> the identifier for type for entities
* @param <E> the entity type this repository stores
*/
public class RedisRepository<ID, E> extends Repository<Redis, ID, E> {
/**
* The prefix to use for keys in this repository.
*/
@NonNull private final String keyPrefix;
public RedisRepository(@NonNull Redis database, @NonNull Class<? extends E> entityClass, @NonNull String keyPrefix) {
super(database, entityClass);
this.keyPrefix = keyPrefix.trim();
if (this.keyPrefix.isEmpty()) { // Missing a key prefix
throw new IllegalArgumentException("Missing key prefix");
}
}
/**
* Get the entity with the given id.
*
* @param id the entity id
* @return the entity with the id, null if none
* @see ID for id
* @see E for entity
*/
@Override
public E find(@NonNull ID id) {
return newEntity(getDatabase().getBootstrap().sync().hgetall(keyPrefix + ":" + id));
}
/**
* Get all entities within this repository.
*
* @return the entities
* @see E for entity
*/
@Override
public List<E> findAll() {
RedisCommands<String, String> commands = getDatabase().getBootstrap().sync(); // The sync command executor
List<E> entities = new ArrayList<>(); // The entities to return
for (String key : commands.keys(keyPrefix + ":*")) {
entities.add(newEntity(commands.hgetall(key)));
}
return Collections.unmodifiableList(entities);
}
/**
* Save the given entities.
*
* @param entities the entities to save
* @see E for entity
*/
@Override
public void saveAll(@NonNull E... entities) {
boolean multi = entities.length > 1; // Should we run multiple commands?
RedisCommands<String, String> commands = getDatabase().getBootstrap().sync(); // The sync command executor
if (multi) { // Prepare for setting the entities
commands.multi();
}
for (E entity : entities) { // Set our entities | /*
* Copyright (c) 2023 Braydon (Rainnny). All rights reserved.
*
* For inquiries, please contact [email protected]
*/
package me.braydon.feather.database.impl.redis;
/**
* The {@link Redis} {@link Repository} implementation.
*
* @author Braydon
* @param <ID> the identifier for type for entities
* @param <E> the entity type this repository stores
*/
public class RedisRepository<ID, E> extends Repository<Redis, ID, E> {
/**
* The prefix to use for keys in this repository.
*/
@NonNull private final String keyPrefix;
public RedisRepository(@NonNull Redis database, @NonNull Class<? extends E> entityClass, @NonNull String keyPrefix) {
super(database, entityClass);
this.keyPrefix = keyPrefix.trim();
if (this.keyPrefix.isEmpty()) { // Missing a key prefix
throw new IllegalArgumentException("Missing key prefix");
}
}
/**
* Get the entity with the given id.
*
* @param id the entity id
* @return the entity with the id, null if none
* @see ID for id
* @see E for entity
*/
@Override
public E find(@NonNull ID id) {
return newEntity(getDatabase().getBootstrap().sync().hgetall(keyPrefix + ":" + id));
}
/**
* Get all entities within this repository.
*
* @return the entities
* @see E for entity
*/
@Override
public List<E> findAll() {
RedisCommands<String, String> commands = getDatabase().getBootstrap().sync(); // The sync command executor
List<E> entities = new ArrayList<>(); // The entities to return
for (String key : commands.keys(keyPrefix + ":*")) {
entities.add(newEntity(commands.hgetall(key)));
}
return Collections.unmodifiableList(entities);
}
/**
* Save the given entities.
*
* @param entities the entities to save
* @see E for entity
*/
@Override
public void saveAll(@NonNull E... entities) {
boolean multi = entities.length > 1; // Should we run multiple commands?
RedisCommands<String, String> commands = getDatabase().getBootstrap().sync(); // The sync command executor
if (multi) { // Prepare for setting the entities
commands.multi();
}
for (E entity : entities) { // Set our entities | Document<String> document = new Document<>(entity); // Create a document from the entity | 0 | 2023-12-12 04:20:32+00:00 | 4k |
litongjava/ai-server | whisper-asr/whisper-asr-server/src/main/java/com/litongjava/aio/server/tio/controller/WhisperAsrController.java | [
{
"identifier": "WhisperSegment",
"path": "whisper-asr/whisper-asr-service/src/main/java/com/litongjava/ai/server/model/WhisperSegment.java",
"snippet": "public class WhisperSegment {\n private long start, end;\n private String sentence;\n\n public WhisperSegment() {\n }\n\n public WhisperSegment(long start, long end, String sentence) {\n this.start = start;\n this.end = end;\n this.sentence = sentence;\n }\n\n public long getStart() {\n return start;\n }\n\n public long getEnd() {\n return end;\n }\n\n public String getSentence() {\n return sentence;\n }\n\n public void setStart(long start) {\n this.start = start;\n }\n\n public void setEnd(long end) {\n this.end = end;\n }\n\n public void setSentence(String sentence) {\n this.sentence = sentence;\n }\n\n @Override\n public String toString() {\n return \"[\" + start + \" --> \" + end + \"]:\" + sentence;\n }\n}"
},
{
"identifier": "WhisperCppBaseService",
"path": "whisper-asr/whisper-asr-service/src/main/java/com/litongjava/ai/server/service/WhisperCppBaseService.java",
"snippet": "@Slf4j\npublic class WhisperCppBaseService {\n private TextService textService = Aop.get(TextService.class);\n\n public List<WhisperSegment> index(URL url, WhisperFullParams params) {\n\n try {\n float[] floats = WhisperAudioUtils.toAudioData(url);\n log.info(\"floats size:{}\", floats.length);\n\n List<WhisperSegment> segments = LocalBaseWhisper.INSTANCE.fullTranscribeWithTime(floats, floats.length, params);\n log.info(\"size:{}\", segments.size());\n return segments;\n } catch (UnsupportedAudioFileException | IOException e) {\n e.printStackTrace();\n }\n\n return null;\n\n }\n\n public List<WhisperSegment> index(byte[] data, WhisperFullParams params) {\n float[] floats = WhisperAudioUtils.toFloat(data);\n return LocalBaseWhisper.INSTANCE.fullTranscribeWithTime(floats, params);\n }\n\n public StringBuffer outputSrt(URL url, WhisperFullParams params) throws IOException {\n List<WhisperSegment> segments = this.index(url, params);\n return textService.generateSrt(segments);\n }\n\n public StringBuffer outputVtt(URL url, WhisperFullParams params) throws IOException {\n List<WhisperSegment> segments = this.index(url, params);\n return textService.generateVtt(segments);\n }\n\n public StringBuffer outputLrc(URL url, WhisperFullParams params) throws IOException {\n List<WhisperSegment> segments = this.index(url, params);\n return textService.generateLrc(segments);\n }\n\n public Object index(byte[] data, String inputType, String outputType)\n throws IOException, UnsupportedAudioFileException {\n return index(data, inputType, outputType, null);\n }\n\n public Object index(byte[] data, String inputType, String outputType, WhisperFullParams params)\n throws IOException, UnsupportedAudioFileException {\n log.info(\"intputType:{},outputType:{}\", inputType, outputType);\n AudioType audioType = AudioType.fromString(inputType);\n TextType textType = TextType.fromString(outputType);\n if (audioType == AudioType.MP3) {\n // 进行格式转换\n log.info(\"进行格式转换:{}\", \"mp3\");\n data = Aop.get(Mp3Util.class).convertToWav(data, 16000, 1);\n }\n List<WhisperSegment> segments = index(data, params);\n if (textType == TextType.SRT) {\n return textService.generateSrt(segments).toString();\n } else if (textType == TextType.VTT) {\n return textService.generateVtt(segments).toString();\n } else if (textType == TextType.LRC) {\n return textService.generateLrc(segments).toString();\n }\n return segments;\n }\n}"
},
{
"identifier": "WhisperCppLargeService",
"path": "whisper-asr/whisper-asr-service/src/main/java/com/litongjava/ai/server/service/WhisperCppLargeService.java",
"snippet": "@Slf4j\npublic class WhisperCppLargeService {\n private TextService textService = Aop.get(TextService.class);\n\n public List<WhisperSegment> index(URL url,WhisperFullParams params) {\n\n try {\n float[] floats = WhisperAudioUtils.toAudioData(url);\n log.info(\"floats size:{}\", floats.length);\n\n List<WhisperSegment> segments = LocalLargeWhisper.INSTANCE.fullTranscribeWithTime(floats, floats.length,params);\n log.info(\"size:{}\", segments.size());\n return segments;\n } catch (UnsupportedAudioFileException | IOException e) {\n e.printStackTrace();\n }\n\n return null;\n\n }\n \n public List<WhisperSegment> index(byte[] data, WhisperFullParams params) {\n float[] floats = WhisperAudioUtils.toFloat(data);\n return LocalLargeWhisper.INSTANCE.fullTranscribeWithTime(floats, params);\n }\n\n public StringBuffer outputSrt(URL url,WhisperFullParams params) throws IOException {\n List<WhisperSegment> segments = this.index(url,params);\n return textService.generateSrt(segments);\n }\n\n public StringBuffer outputVtt(URL url,WhisperFullParams params) throws IOException {\n List<WhisperSegment> segments = this.index(url,params);\n return textService.generateVtt(segments);\n }\n\n public StringBuffer outputLrc(URL url,WhisperFullParams params) throws IOException {\n List<WhisperSegment> segments = this.index(url,params);\n return textService.generateLrc(segments);\n }\n\n public Object index(byte[] data, String inputType, String outputType)\n throws IOException, UnsupportedAudioFileException {\n return index(data, inputType, outputType, null);\n }\n\n public Object index(byte[] data, String inputType, String outputType, WhisperFullParams params)\n throws IOException, UnsupportedAudioFileException {\n log.info(\"intputType:{},outputType:{}\", inputType, outputType);\n AudioType audioType = AudioType.fromString(inputType);\n TextType textType = TextType.fromString(outputType);\n if (audioType == AudioType.MP3) {\n // 进行格式转换\n log.info(\"进行格式转换:{}\", \"mp3\");\n data = Aop.get(Mp3Util.class).convertToWav(data, 16000, 1);\n }\n List<WhisperSegment> segments = index(data, params);\n if (textType == TextType.SRT) {\n return textService.generateSrt(segments).toString();\n } else if (textType == TextType.VTT) {\n return textService.generateVtt(segments).toString();\n } else if (textType == TextType.LRC) {\n return textService.generateLrc(segments).toString();\n }\n return segments;\n }\n}"
},
{
"identifier": "WhisperCppService",
"path": "whisper-asr/whisper-asr-service/src/main/java/com/litongjava/ai/server/service/WhisperCppService.java",
"snippet": "@Slf4j\npublic class WhisperCppService {\n private TextService textService = Aop.get(TextService.class);\n\n public List<WhisperSegment> index(URL url,WhisperFullParams params) {\n\n try {\n float[] floats = WhisperAudioUtils.toAudioData(url);\n log.info(\"floats size:{}\", floats.length);\n\n List<WhisperSegment> segments = LocalWhisper.INSTANCE.fullTranscribeWithTime(floats, floats.length, params);\n log.info(\"size:{}\", segments.size());\n return segments;\n } catch (UnsupportedAudioFileException | IOException e) {\n e.printStackTrace();\n }\n\n return null;\n\n }\n\n public List<WhisperSegment> index(byte[] data, WhisperFullParams params) {\n float[] floats = WhisperAudioUtils.toFloat(data);\n return LocalLargeWhisper.INSTANCE.fullTranscribeWithTime(floats, params);\n }\n\n public StringBuffer outputSrt(URL url,WhisperFullParams params) throws IOException {\n List<WhisperSegment> segments = this.index(url,params);\n return textService.generateSrt(segments);\n }\n\n public StringBuffer outputVtt(URL url,WhisperFullParams params) throws IOException {\n List<WhisperSegment> segments = this.index(url,params);\n return textService.generateVtt(segments);\n }\n\n public StringBuffer outputLrc(URL url,WhisperFullParams params) throws IOException {\n List<WhisperSegment> segments = this.index(url,params);\n return textService.generateLrc(segments);\n }\n\n public Object index(byte[] data, String inputType, String outputType)\n throws IOException, UnsupportedAudioFileException {\n return index(data, inputType, outputType, null);\n }\n\n public Object index(byte[] data, String inputType, String outputType, WhisperFullParams params)\n throws IOException, UnsupportedAudioFileException {\n log.info(\"intputType:{},outputType:{}\", inputType, outputType);\n AudioType audioType = AudioType.fromString(inputType);\n TextType textType = TextType.fromString(outputType);\n if (audioType == AudioType.MP3) {\n // 进行格式转换\n log.info(\"进行格式转换:{}\", \"mp3\");\n data = Aop.get(Mp3Util.class).convertToWav(data, 16000, 1);\n }\n List<WhisperSegment> segments = index(data, params);\n if (textType == TextType.SRT) {\n return textService.generateSrt(segments).toString();\n } else if (textType == TextType.VTT) {\n return textService.generateVtt(segments).toString();\n } else if (textType == TextType.LRC) {\n return textService.generateLrc(segments).toString();\n }\n return segments;\n }\n}"
}
] | import java.net.URL;
import java.util.List;
import com.litongjava.ai.server.model.WhisperSegment;
import com.litongjava.ai.server.service.WhisperCppBaseService;
import com.litongjava.ai.server.service.WhisperCppLargeService;
import com.litongjava.ai.server.service.WhisperCppService;
import com.litongjava.jfinal.aop.Aop;
import com.litongjava.tio.http.common.HttpRequest;
import com.litongjava.tio.http.common.HttpResponse;
import com.litongjava.tio.http.common.UploadFile;
import com.litongjava.tio.http.server.annotation.EnableCORS;
import com.litongjava.tio.http.server.annotation.RequestPath;
import com.litongjava.tio.http.server.util.Resps;
import com.litongjava.tio.utils.resp.Resp;
import cn.hutool.core.util.ClassUtil;
import io.github.givimad.whisperjni.WhisperFullParams; | 3,257 | package com.litongjava.aio.server.tio.controller;
@EnableCORS
@RequestPath("/whispser/asr")
public class WhisperAsrController {
private WhisperCppService whisperCppService = Aop.get(WhisperCppService.class);
private WhisperCppBaseService whisperCppBaseService = Aop.get(WhisperCppBaseService.class);
private WhisperCppLargeService whisperCppLargeService = Aop.get(WhisperCppLargeService.class);
@RequestPath(value = "/rec")
public HttpResponse index(HttpRequest request, UploadFile file, String inputType, String outputType,
String outputFormat, WhisperFullParams params) throws Exception {
if (file != null) {
Object data = whisperCppService.index(file.getData(), inputType, outputType, params);
if ("txt".equals(outputFormat)) {
if (data instanceof String) {
return Resps.txt(request, (String) data);
}
} else {
return Resps.json(request, Resp.ok(data));
}
} else {
return Resps.json(request, Resp.fail("uplod file can't be null"));
}
return Resps.json(request, Resp.fail("unknow error"));
}
@RequestPath(value = "/rec/base")
public HttpResponse recBase(HttpRequest request, UploadFile file, String inputType, String outputType,
String outputFormat, WhisperFullParams params) throws Exception {
if (file != null) {
Object data = whisperCppBaseService.index(file.getData(), inputType, outputType, params);
if ("txt".equals(outputFormat)) {
if (data instanceof String) {
return Resps.txt(request, (String) data);
}
} else {
return Resps.json(request, Resp.ok(data));
}
} else {
return Resps.json(request, Resp.fail("uplod file can't be null"));
}
return Resps.json(request, Resp.fail("unknow error"));
}
@RequestPath(value = "/rec/large")
public HttpResponse recLarge(UploadFile file, String inputType, String outputType, String outputFormat,
HttpRequest request, WhisperFullParams params) throws Exception {
if (file != null) {
Object data = whisperCppLargeService.index(file.getData(), inputType, outputType, params);
if ("txt".equals(outputFormat)) {
if (data instanceof String) {
return Resps.txt(request, (String) data);
}
} else {
return Resps.json(request, Resp.ok(data));
}
} else {
return Resps.json(request, Resp.fail("uplod file can't be null"));
}
return Resps.json(request, Resp.fail("unknow error"));
}
@RequestPath("/test")
public HttpResponse test(HttpRequest request, WhisperFullParams params) {
// String urlStr = "https://raw.githubusercontent.com/litongjava/whisper.cpp/master/samples/jfk.wav";
URL resource = ClassUtil.getClassLoader().getResource("audios/jfk.wav");
if (resource != null) { | package com.litongjava.aio.server.tio.controller;
@EnableCORS
@RequestPath("/whispser/asr")
public class WhisperAsrController {
private WhisperCppService whisperCppService = Aop.get(WhisperCppService.class);
private WhisperCppBaseService whisperCppBaseService = Aop.get(WhisperCppBaseService.class);
private WhisperCppLargeService whisperCppLargeService = Aop.get(WhisperCppLargeService.class);
@RequestPath(value = "/rec")
public HttpResponse index(HttpRequest request, UploadFile file, String inputType, String outputType,
String outputFormat, WhisperFullParams params) throws Exception {
if (file != null) {
Object data = whisperCppService.index(file.getData(), inputType, outputType, params);
if ("txt".equals(outputFormat)) {
if (data instanceof String) {
return Resps.txt(request, (String) data);
}
} else {
return Resps.json(request, Resp.ok(data));
}
} else {
return Resps.json(request, Resp.fail("uplod file can't be null"));
}
return Resps.json(request, Resp.fail("unknow error"));
}
@RequestPath(value = "/rec/base")
public HttpResponse recBase(HttpRequest request, UploadFile file, String inputType, String outputType,
String outputFormat, WhisperFullParams params) throws Exception {
if (file != null) {
Object data = whisperCppBaseService.index(file.getData(), inputType, outputType, params);
if ("txt".equals(outputFormat)) {
if (data instanceof String) {
return Resps.txt(request, (String) data);
}
} else {
return Resps.json(request, Resp.ok(data));
}
} else {
return Resps.json(request, Resp.fail("uplod file can't be null"));
}
return Resps.json(request, Resp.fail("unknow error"));
}
@RequestPath(value = "/rec/large")
public HttpResponse recLarge(UploadFile file, String inputType, String outputType, String outputFormat,
HttpRequest request, WhisperFullParams params) throws Exception {
if (file != null) {
Object data = whisperCppLargeService.index(file.getData(), inputType, outputType, params);
if ("txt".equals(outputFormat)) {
if (data instanceof String) {
return Resps.txt(request, (String) data);
}
} else {
return Resps.json(request, Resp.ok(data));
}
} else {
return Resps.json(request, Resp.fail("uplod file can't be null"));
}
return Resps.json(request, Resp.fail("unknow error"));
}
@RequestPath("/test")
public HttpResponse test(HttpRequest request, WhisperFullParams params) {
// String urlStr = "https://raw.githubusercontent.com/litongjava/whisper.cpp/master/samples/jfk.wav";
URL resource = ClassUtil.getClassLoader().getResource("audios/jfk.wav");
if (resource != null) { | List<WhisperSegment> list = whisperCppService.index(resource, params); | 0 | 2023-12-13 15:12:36+00:00 | 4k |
i-moonlight/Beluga | server/src/main/java/com/amnesica/belugaproject/services/trails/AircraftTrailService.java | [
{
"identifier": "StaticValues",
"path": "server/src/main/java/com/amnesica/belugaproject/config/StaticValues.java",
"snippet": "public class StaticValues {\n // Lokale Feeder - Scheduler\n public static final int INTERVAL_UPDATE_LOCAL_FEEDER = 2000; // 2 Sekunden\n public static final int INTERVAL_LOCAL_PLANES_TO_HISTORY = 600000; // 10 Minuten\n public static final int INTERVAL_REMOVE_OLD_TRAILS_LOCAL = 600000; // 10 Minuten\n public static final long INTERVAL_REMOVE_OLD_DATA = 2592000000L; // 30 Tage\n public static final String INTERVAL_REMOVE_OLD_TRAILS_FROM_HISTORY = \"0 0 2 * * ?\"; // cron expression: every day at 02:00 a.m.\n public static final int RETENTION_DAYS_TRAILS_IN_HISTORY = 2; // 2 Tage\n public static final String INTERVAL_REMOVE_OLD_AIRCRAFT_FROM_HISTORY = \"0 0 1 * * ?\"; // cron expression: every day at 01:00 a.m.\n public static final int RETENTION_DAYS_AIRCRAFT_IN_HISTORY = 30; // 30 Tage\n\n // Opensky-Network - Scheduler\n public static final int INTERVAL_UPDATE_OPENSKY = 5000; // 5 Sekunden\n public static final int INTERVAL_REMOVE_OLD_PLANES_OPENSKY = 600000; // 10 Minuten\n\n // ISS - Scheduler\n public static final int INTERVAL_UPDATE_ISS = 2000; // 2 Sekunden\n public static final int INTERVAL_REMOVE_OLD_TRAILS_ISS = 600000; // 10 Minuten\n}"
},
{
"identifier": "AircraftSuperclass",
"path": "server/src/main/java/com/amnesica/belugaproject/entities/aircraft/AircraftSuperclass.java",
"snippet": "@Data\n@JsonInclude(JsonInclude.Include.NON_NULL)\n@MappedSuperclass\n@TypeDefs({@TypeDef(name = \"string-array\", typeClass = StringArrayType.class),\n @TypeDef(name = \"list-array\", typeClass = ListArrayType.class),\n @TypeDef(name = \"jsonb\", typeClass = JsonBinaryType.class)})\npublic class AircraftSuperclass {\n @Id\n private String hex;\n private Double latitude;\n private Double longitude;\n private Integer altitude;\n private Integer track;\n private String type;\n private String registration;\n private Boolean onGround;\n private Integer speed;\n private String squawk;\n private String flightId;\n private Integer verticalRate;\n private Double rssi;\n private String category;\n private Integer temperature;\n private Integer windSpeed;\n private Integer windFromDirection;\n private String destination;\n private String origin;\n private Double distance;\n private Boolean autopilotEngaged;\n private Integer elipsoidalAltitude;\n private Double selectedQnh;\n private Integer selectedAltitude;\n private Integer selectedHeading;\n\n // Liste mit Feeder, welches Flugzeug zur Zeit empfangen\n @Type(type = \"list-array\")\n @Column(name = \"feeder_list\", columnDefinition = \"text[]\")\n private List<String> feederList;\n\n // Zuletzt gesehen\n private Integer lastSeen;\n\n // Quelle (ADS-B oder MLAT)\n @Type(type = \"list-array\")\n @Column(name = \"source_list\", columnDefinition = \"text[]\")\n private List<String> sourceList;\n\n // Source in der aktuellen Iteration eines Feeder (temporärer Wert)\n private String sourceCurrentFeeder;\n\n // Alter des Flugzeugs\n private Integer age;\n\n // Mehr Flugzeug-Information aus Datenbank-Tabelle AircraftData\n private String fullType; // manufacturerName + model\n private String serialNumber;\n private String lineNumber;\n private String operatorIcao;\n private String testReg;\n private String registered;\n private String regUntil;\n private String status;\n private String built;\n private String firstFlightDate;\n private String icaoAircraftType;\n private String engines;\n\n // Callsign des Operators\n private String operatorCallsign;\n\n // Name des Operators\n private String operatorName;\n\n // Land des Operators\n private String operatorCountry;\n\n // Flagge des Landes des Operators\n private String operatorCountryFlag;\n\n // IATA-Code des Operators\n private String operatorIata;\n\n // Registrierungs-Code \"Regions-Bezeichnung\"\n private String regCodeName;\n\n // Flagge des Registrierungs-Code\n private String regCodeNameFlag;\n\n // Boolean, ob Flugzeug aus der tempStorageAircraftList stammt\n private Boolean reenteredAircraft = false;\n\n // Zustand des Flugzeugs (\"increasing, descending, onGround, flying\")\n private String aircraftState;\n\n // Letztes Update des Flugzeugs von einem Feeder als timestamp\n private Long lastUpdate;\n\n // Photo-Url\n private String urlPhotoDirect;\n\n // Url zur Website, wo Photo ist\n private String urlPhotoWebsite;\n\n // Photograph des Bildes von urlPhotoDirect\n private String photoPhotographer;\n\n // Boolean, ob Flugzeug von Opensky ist\n private Boolean isFromOpensky = false;\n\n // Konstruktor\n public AircraftSuperclass(String hex, double latitude, double longitude) {\n this.hex = hex;\n this.latitude = latitude;\n this.longitude = longitude;\n }\n\n public AircraftSuperclass() {\n // Benötiger, leerer Konstruktor\n }\n\n /**\n * Hinweis: Nur in Copy-Konstrukt verwenden!\n *\n * @param feederList List<String>\n */\n public void setFeederList(List<String> feederList) {\n this.feederList = feederList;\n }\n\n /**\n * Fügt einen Feeder zur Liste an Feedern hinzu. Wenn feederList null ist, wird\n * eine neue Liste erzeugt\n *\n * @param feeder String\n */\n public void addFeederToFeederList(String feeder) {\n if (feederList == null) {\n feederList = new ArrayList<String>();\n }\n\n feederList.add(feeder);\n }\n\n /**\n * Entfernt alle Einträge aus der Liste\n */\n public void clearFeederList() {\n if (feederList != null) {\n feederList.clear();\n }\n }\n\n /**\n * Fügt ein Source-Element zu der Liste an Sources hinzu oder bearbeitet ein\n * vorhandenes Element, wenn der Feeder bereits in der Liste vorhanden ist\n *\n * @param feeder String\n */\n public void addSourceToSourceList(String feeder) {\n if (sourceList == null) {\n sourceList = new ArrayList<String>();\n }\n\n if (sourceCurrentFeeder != null && !sourceCurrentFeeder.isEmpty() && feeder != null && !feeder.isEmpty()) {\n String element = feeder + \":\" + sourceCurrentFeeder;\n\n boolean elementExistsBefore = false;\n // Wenn der Feeder bereits ein Element in der Liste hat, bearbeite dies\n for (int i = 0; i < sourceList.size(); i++) {\n if (sourceList.get(i).startsWith(feeder)) {\n elementExistsBefore = true;\n sourceList.set(i, element);\n }\n }\n // Wenn der Feeder noch kein Element von dem Feeder hatte, füge es hinzu\n if (!elementExistsBefore) {\n sourceList.add(element);\n }\n }\n }\n\n /**\n * Entfernt alle Einträge aus der Liste\n */\n public void clearSourceList() {\n if (sourceList != null) {\n sourceList.clear();\n }\n }\n\n @Override\n public int hashCode() {\n final int prime = 31;\n int result = 1;\n result = prime * result + ((hex == null) ? 0 : hex.hashCode());\n return result;\n }\n\n /**\n * Equals-Methode, welche zwei Flugzeuge nur nach dem hex vergleicht\n */\n @Override\n public boolean equals(Object obj) {\n if (this == obj)\n return true;\n if (obj == null)\n return false;\n if (getClass() != obj.getClass())\n return false;\n AircraftSuperclass other = (AircraftSuperclass) obj;\n if (hex == null) {\n return other.hex == null;\n } else return hex.equalsIgnoreCase(other.hex);\n }\n}"
},
{
"identifier": "AircraftTrail",
"path": "server/src/main/java/com/amnesica/belugaproject/entities/trails/AircraftTrail.java",
"snippet": "@Entity\n@Table(indexes = {@Index(name = \"idx_ac_trail_hex_timestampAsc\", columnList = \"hex, timestamp ASC\"),\n @Index(name = \"idx_ac_trail_timestamp\", columnList = \"timestamp\"),\n @Index(name = \"idx_ac_trail_hex\", columnList = \"hex\"),\n @Index(name = \"idx_ac_trail_hex_feeder_timestampAsc\", columnList = \"hex, feeder, timestamp ASC\")})\npublic class AircraftTrail extends TrailSuperclass {\n public AircraftTrail() {\n // Benötiger, leerer Konstruktor\n }\n\n public AircraftTrail(String hex, Double longitude, Double latitude, Integer altitude, Boolean reenteredAircraft,\n Long timestamp, String feeder, String source) {\n super(hex, longitude, latitude, altitude, reenteredAircraft, timestamp, feeder, source);\n }\n}"
},
{
"identifier": "AircraftTrailRepository",
"path": "server/src/main/java/com/amnesica/belugaproject/repositories/trails/AircraftTrailRepository.java",
"snippet": "@Repository\npublic interface AircraftTrailRepository extends CrudRepository<AircraftTrail, String> {\n List<AircraftTrail> findAllByHexOrderByTimestampAsc(String hex);\n\n List<AircraftTrail> findAllByTimestampLessThanEqual(long time);\n\n List<AircraftTrail> findAllByHexAndFeederOrderByTimestampAsc(String hex, String feeder);\n\n AircraftTrail findFirstByHexAndFeederOrderByTimestampDesc(String hex, String feeder);\n}"
}
] | import com.amnesica.belugaproject.config.StaticValues;
import com.amnesica.belugaproject.entities.aircraft.AircraftSuperclass;
import com.amnesica.belugaproject.entities.trails.AircraftTrail;
import com.amnesica.belugaproject.repositories.trails.AircraftTrailRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import java.util.List; | 2,633 | package com.amnesica.belugaproject.services.trails;
@Slf4j
@Service
public class AircraftTrailService {
@Autowired
private AircraftTrailRepository aircraftTrailRepository;
@Autowired
private HistoryAircraftTrailService historyAircraftTrailService;
/**
* Speichert einen Trail im AircraftTrailRepository
*
* @param aircraft AircraftSuperclass
* @param feederName String
*/ | package com.amnesica.belugaproject.services.trails;
@Slf4j
@Service
public class AircraftTrailService {
@Autowired
private AircraftTrailRepository aircraftTrailRepository;
@Autowired
private HistoryAircraftTrailService historyAircraftTrailService;
/**
* Speichert einen Trail im AircraftTrailRepository
*
* @param aircraft AircraftSuperclass
* @param feederName String
*/ | public void addTrail(AircraftSuperclass aircraft, String feederName) { | 1 | 2023-12-11 11:37:46+00:00 | 4k |
MeteorLite/hotlite-launcher | src/main/java/net/runelite/launcher/Launcher.java | [
{
"identifier": "Artifact",
"path": "src/main/java/net/runelite/launcher/beans/Artifact.java",
"snippet": "@Data\npublic class Artifact\n{\n\tprivate String name;\n\tprivate String path;\n\tprivate String hash;\n\tprivate int size;\n\tprivate Diff[] diffs;\n\tprivate Platform[] platform;\n}"
},
{
"identifier": "Bootstrap",
"path": "src/main/java/net/runelite/launcher/beans/Bootstrap.java",
"snippet": "@Data\npublic class Bootstrap\n{\n\tprivate Artifact[] artifacts;\n\n\tprivate String[] clientJvm9Arguments;\n\n\tprivate String[] clientJvm17Arguments;\n\tprivate String[] clientJvm17WindowsArguments;\n\tprivate String[] clientJvm17MacArguments;\n\n\tprivate String[] launcherJvm11WindowsArguments;\n\tprivate String[] launcherJvm11MacArguments;\n\tprivate String[] launcherJvm11Arguments;\n\n\tprivate String[] launcherJvm17WindowsArguments;\n\tprivate String[] launcherJvm17MacArguments;\n\tprivate String[] launcherJvm17Arguments;\n\n\tprivate String requiredLauncherVersion;\n\tprivate String requiredJVMVersion;\n\n\tprivate Map<String, String> launcherWindowsEnv;\n\tprivate Map<String, String> launcherMacEnv;\n\tprivate Map<String, String> launcherLinuxEnv;\n\n\tprivate Update[] updates;\n}"
},
{
"identifier": "Diff",
"path": "src/main/java/net/runelite/launcher/beans/Diff.java",
"snippet": "@Data\npublic class Diff\n{\n\tprivate String name;\n\tprivate String from;\n\tprivate String fromHash;\n\tprivate String hash;\n\tprivate String path;\n\tprivate int size;\n}"
},
{
"identifier": "Platform",
"path": "src/main/java/net/runelite/launcher/beans/Platform.java",
"snippet": "@Data\npublic class Platform\n{\n\tprivate String name;\n\tprivate String arch;\n}"
}
] | import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import com.google.archivepatcher.applier.FileByFileV1DeltaApplier;
import com.google.archivepatcher.shared.DefaultDeflateCompatibilityWindow;
import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import com.google.common.collect.Streams;
import com.google.common.hash.HashCode;
import com.google.common.hash.HashFunction;
import com.google.common.hash.Hashing;
import com.google.common.hash.HashingOutputStream;
import com.google.common.io.ByteStreams;
import com.google.gson.Gson;
import java.io.*;
import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.nio.file.Files;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.Signature;
import java.security.SignatureException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Properties;
import java.util.Set;
import java.util.function.IntConsumer;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.zip.GZIPInputStream;
import javax.swing.*;
import joptsimple.OptionException;
import joptsimple.OptionParser;
import joptsimple.OptionSet;
import lombok.extern.slf4j.Slf4j;
import net.runelite.launcher.beans.Artifact;
import net.runelite.launcher.beans.Bootstrap;
import net.runelite.launcher.beans.Diff;
import net.runelite.launcher.beans.Platform;
import org.slf4j.LoggerFactory; | 3,239 | final var hardwareAccelMode = settings.hardwareAccelerationMode == HardwareAccelerationMode.AUTO ?
HardwareAccelerationMode.defaultMode(OS.getOs()) : settings.hardwareAccelerationMode;
jvmProps.putAll(hardwareAccelMode.toParams(OS.getOs()));
// As of JDK-8243269 (11.0.8) and JDK-8235363 (14), AWT makes macOS dark mode support opt-in so interfaces
// with hardcoded foreground/background colours don't get broken by system settings. Considering the native
// Aqua we draw consists a window border and an about box, it's safe to say we can opt in.
if (OS.getOs() == OS.OSType.MacOS)
{
jvmProps.put("apple.awt.application.appearance", "system");
}
// Stream launcher version
jvmProps.put(LauncherProperties.getVersionKey(), LauncherProperties.getVersion());
if (settings.isSkipTlsVerification())
{
jvmProps.put("runelite.insecure-skip-tls-verification", "true");
}
log.info("RuneLite Launcher version {}", LauncherProperties.getVersion());
log.info("Launcher configuration:" + System.lineSeparator() + "{}", settings.configurationStr());
log.info("OS name: {}, version: {}, arch: {}", System.getProperty("os.name"), System.getProperty("os.version"), System.getProperty("os.arch"));
log.info("Using hardware acceleration mode: {}", hardwareAccelMode);
// java2d properties have to be set prior to the graphics environment startup
setJvmParams(jvmProps);
if (settings.isSkipTlsVerification())
{
TrustManagerUtil.setupInsecureTrustManager();
}
else
{
TrustManagerUtil.setupTrustManager();
}
if (postInstall)
{
postInstall();
return;
}
SplashScreen.init();
SplashScreen.stage(0, "Preparing", "Setting up environment");
// Print out system info
if (log.isDebugEnabled())
{
final RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean();
log.debug("Command line arguments: {}", String.join(" ", args));
// This includes arguments from _JAVA_OPTIONS, which are parsed after command line flags and applied to
// the global VM args
log.debug("Java VM arguments: {}", String.join(" ", runtime.getInputArguments()));
log.debug("Java Environment:");
final Properties p = System.getProperties();
final Enumeration<Object> keys = p.keys();
while (keys.hasMoreElements())
{
final String key = (String) keys.nextElement();
final String value = (String) p.get(key);
log.debug(" {}: {}", key, value);
}
}
SplashScreen.stage(.05, null, "Downloading bootstrap");
Bootstrap bootstrap;
try
{
bootstrap = getBootstrap();
}
catch (IOException | VerificationException | CertificateException | SignatureException | InvalidKeyException | NoSuchAlgorithmException ex)
{
log.error("error fetching bootstrap", ex);
String extract = CertPathExtractor.extract(ex);
if (extract != null)
{
log.error("untrusted certificate chain: {}", extract);
}
SwingUtilities.invokeLater(() -> FatalErrorDialog.showNetErrorWindow("downloading the bootstrap", ex));
return;
}
SplashScreen.stage(.07, null, "Checking for updates");
Updater.update(bootstrap, settings, args);
SplashScreen.stage(.10, null, "Tidying the cache");
if (jvmOutdated(bootstrap))
{
// jvmOutdated opens an error dialog
return;
}
// update packr vmargs to the launcher vmargs from bootstrap.
PackrConfig.updateLauncherArgs(bootstrap);
if (!REPO_DIR.exists() && !REPO_DIR.mkdirs())
{
log.error("unable to create repo directory {}", REPO_DIR);
SwingUtilities.invokeLater(() -> new FatalErrorDialog("Unable to create RuneLite directory " + REPO_DIR.getAbsolutePath() + ". Check your filesystem permissions are correct.").open());
return;
}
// Determine artifacts for this OS
List<Artifact> artifacts = Arrays.stream(bootstrap.getArtifacts())
.filter(a ->
{
if (a.getPlatform() == null)
{
return true;
}
final String os = System.getProperty("os.name");
final String arch = System.getProperty("os.arch"); | /*
* Copyright (c) 2016-2018, Adam <[email protected]>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. 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.
*
* 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 net.runelite.launcher;
@Slf4j
public class Launcher
{
private static final File RUNELITE_DIR = new File(System.getProperty("user.home"), ".runelite");
public static final File LOGS_DIR = new File(RUNELITE_DIR, "logs");
private static final File REPO_DIR = new File(RUNELITE_DIR, "repository2");
public static final File CRASH_FILES = new File(LOGS_DIR, "jvm_crash_pid_%p.log");
private static final String USER_AGENT = "RuneLite/" + LauncherProperties.getVersion();
static final String LAUNCHER_EXECUTABLE_NAME_WIN = "RuneLite.exe";
static final String LAUNCHER_EXECUTABLE_NAME_OSX = "RuneLite";
private static final File HOTLITE_DIR = new File(RUNELITE_DIR, "hotlite");
private static final File LIBS_DIR = new File(HOTLITE_DIR, "libs");
public static String rlVersion;
public static File hotlitePatchDir;
public static void main(String[] args) throws IOException {
OptionParser parser = new OptionParser(false);
parser.allowsUnrecognizedOptions();
parser.accepts("postinstall", "Perform post-install tasks");
parser.accepts("debug", "Enable debug logging");
parser.accepts("nodiff", "Always download full artifacts instead of diffs");
parser.accepts("insecure-skip-tls-verification", "Disable TLS certificate and hostname verification");
parser.accepts("scale", "Custom scale factor for Java 2D").withRequiredArg();
parser.accepts("noupdate", "Skips the launcher self-update");
parser.accepts("help", "Show this text (use -- --help for client help)").forHelp();
parser.accepts("classpath", "Classpath for the client").withRequiredArg();
parser.accepts("J", "JVM argument (FORK or JVM launch mode only)").withRequiredArg();
parser.accepts("configure", "Opens configuration GUI");
parser.accepts("launch-mode", "JVM launch method (JVM, FORK, REFLECT)")
.withRequiredArg()
.ofType(LaunchMode.class);
parser.accepts("hw-accel", "Java 2D hardware acceleration mode (OFF, DIRECTDRAW, OPENGL, METAL)")
.withRequiredArg()
.ofType(HardwareAccelerationMode.class);
parser.accepts("mode", "Alias of hw-accel")
.withRequiredArg()
.ofType(HardwareAccelerationMode.class);
if (OS.getOs() == OS.OSType.MacOS)
{
// Parse macos PSN, eg: -psn_0_352342
parser.accepts("p").withRequiredArg();
}
final OptionSet options;
try
{
options = parser.parse(args);
}
catch (OptionException ex)
{
log.error("unable to parse arguments", ex);
SwingUtilities.invokeLater(() ->
new FatalErrorDialog("RuneLite was unable to parse the provided application arguments: " + ex.getMessage())
.open());
throw ex;
}
if (options.has("help"))
{
try
{
parser.printHelpOn(System.out);
}
catch (IOException e)
{
log.error(null, e);
}
System.exit(0);
}
if (options.has("configure"))
{
ConfigurationFrame.open();
return;
}
final LauncherSettings settings = LauncherSettings.loadSettings();
settings.apply(options);
final boolean postInstall = options.has("postinstall");
// Setup logging
LOGS_DIR.mkdirs();
if (settings.isDebug())
{
final Logger logger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
logger.setLevel(Level.DEBUG);
}
initDll();
// RTSS triggers off of the CreateWindow event, so this needs to be in place early, prior to splash screen
initDllBlacklist();
try
{
if (options.has("classpath"))
{
TrustManagerUtil.setupTrustManager();
// being called from ForkLauncher. All JVM options are already set.
var classpathOpt = String.valueOf(options.valueOf("classpath"));
var classpath = Streams.stream(Splitter.on(File.pathSeparatorChar)
.split(classpathOpt))
.map(name -> new File(REPO_DIR, name))
.collect(Collectors.toList());
updateLibs();
classpathSwap(classpath, options, false);
try
{
ReflectionLauncher.launch(classpath, getClientArgs(settings));
}
catch (Exception e)
{
log.error("error launching client", e);
}
return;
}
final Map<String, String> jvmProps = new LinkedHashMap<>();
if (settings.scale != null)
{
// This calls SetProcessDPIAware(). Since the RuneLite.exe manifest is DPI unaware
// Windows will scale the application if this isn't called. Thus the default scaling
// mode is Windows scaling due to being DPI unaware.
// https://docs.microsoft.com/en-us/windows/win32/hidpi/high-dpi-desktop-application-development-on-windows
jvmProps.put("sun.java2d.dpiaware", "true");
// This sets the Java 2D scaling factor, overriding the default behavior of detecting the scale via
// GetDpiForMonitor.
jvmProps.put("sun.java2d.uiScale", Double.toString(settings.scale));
}
final var hardwareAccelMode = settings.hardwareAccelerationMode == HardwareAccelerationMode.AUTO ?
HardwareAccelerationMode.defaultMode(OS.getOs()) : settings.hardwareAccelerationMode;
jvmProps.putAll(hardwareAccelMode.toParams(OS.getOs()));
// As of JDK-8243269 (11.0.8) and JDK-8235363 (14), AWT makes macOS dark mode support opt-in so interfaces
// with hardcoded foreground/background colours don't get broken by system settings. Considering the native
// Aqua we draw consists a window border and an about box, it's safe to say we can opt in.
if (OS.getOs() == OS.OSType.MacOS)
{
jvmProps.put("apple.awt.application.appearance", "system");
}
// Stream launcher version
jvmProps.put(LauncherProperties.getVersionKey(), LauncherProperties.getVersion());
if (settings.isSkipTlsVerification())
{
jvmProps.put("runelite.insecure-skip-tls-verification", "true");
}
log.info("RuneLite Launcher version {}", LauncherProperties.getVersion());
log.info("Launcher configuration:" + System.lineSeparator() + "{}", settings.configurationStr());
log.info("OS name: {}, version: {}, arch: {}", System.getProperty("os.name"), System.getProperty("os.version"), System.getProperty("os.arch"));
log.info("Using hardware acceleration mode: {}", hardwareAccelMode);
// java2d properties have to be set prior to the graphics environment startup
setJvmParams(jvmProps);
if (settings.isSkipTlsVerification())
{
TrustManagerUtil.setupInsecureTrustManager();
}
else
{
TrustManagerUtil.setupTrustManager();
}
if (postInstall)
{
postInstall();
return;
}
SplashScreen.init();
SplashScreen.stage(0, "Preparing", "Setting up environment");
// Print out system info
if (log.isDebugEnabled())
{
final RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean();
log.debug("Command line arguments: {}", String.join(" ", args));
// This includes arguments from _JAVA_OPTIONS, which are parsed after command line flags and applied to
// the global VM args
log.debug("Java VM arguments: {}", String.join(" ", runtime.getInputArguments()));
log.debug("Java Environment:");
final Properties p = System.getProperties();
final Enumeration<Object> keys = p.keys();
while (keys.hasMoreElements())
{
final String key = (String) keys.nextElement();
final String value = (String) p.get(key);
log.debug(" {}: {}", key, value);
}
}
SplashScreen.stage(.05, null, "Downloading bootstrap");
Bootstrap bootstrap;
try
{
bootstrap = getBootstrap();
}
catch (IOException | VerificationException | CertificateException | SignatureException | InvalidKeyException | NoSuchAlgorithmException ex)
{
log.error("error fetching bootstrap", ex);
String extract = CertPathExtractor.extract(ex);
if (extract != null)
{
log.error("untrusted certificate chain: {}", extract);
}
SwingUtilities.invokeLater(() -> FatalErrorDialog.showNetErrorWindow("downloading the bootstrap", ex));
return;
}
SplashScreen.stage(.07, null, "Checking for updates");
Updater.update(bootstrap, settings, args);
SplashScreen.stage(.10, null, "Tidying the cache");
if (jvmOutdated(bootstrap))
{
// jvmOutdated opens an error dialog
return;
}
// update packr vmargs to the launcher vmargs from bootstrap.
PackrConfig.updateLauncherArgs(bootstrap);
if (!REPO_DIR.exists() && !REPO_DIR.mkdirs())
{
log.error("unable to create repo directory {}", REPO_DIR);
SwingUtilities.invokeLater(() -> new FatalErrorDialog("Unable to create RuneLite directory " + REPO_DIR.getAbsolutePath() + ". Check your filesystem permissions are correct.").open());
return;
}
// Determine artifacts for this OS
List<Artifact> artifacts = Arrays.stream(bootstrap.getArtifacts())
.filter(a ->
{
if (a.getPlatform() == null)
{
return true;
}
final String os = System.getProperty("os.name");
final String arch = System.getProperty("os.arch"); | for (Platform platform : a.getPlatform()) | 3 | 2023-12-06 17:41:41+00:00 | 4k |
fiber-net-gateway/fiber-net-gateway | fiber-gateway-common/src/main/java/io/fiber/net/common/HttpExchange.java | [
{
"identifier": "Maybe",
"path": "fiber-gateway-common/src/main/java/io/fiber/net/common/async/Maybe.java",
"snippet": "public interface Maybe<T> {\n\n interface Emitter<T> {\n void onSuccess(T t);\n\n void onError(Throwable t);\n\n void onComplete();\n\n boolean isDisposed();\n }\n\n interface Observer<T> {\n void onSubscribe(Disposable d);\n\n void onSuccess(T t);\n\n void onError(Throwable e);\n\n void onComplete();\n\n Scheduler scheduler();\n }\n\n interface OnSubscribe<T> {\n\n void subscribe(Emitter<T> emitter) throws Throwable;\n }\n\n void subscribe(Observer<? super T> observer);\n\n default Maybe<T> onNotify(BiConsumer<? super T, Throwable> onNotify) {\n return new OnNotifyWrapMaybe<>(onNotify, this);\n }\n\n default <U> Maybe<U> map(Function<? super T, ? extends U> function) {\n return new MappedMaybe<>(function, this);\n }\n\n default Disposable subscribe(java.util.function.BiConsumer<T, Throwable> consumer) {\n FuncMaybeObserver<T> tFuncMaybeObserver = new FuncMaybeObserver<>(consumer);\n subscribe(tFuncMaybeObserver);\n return tFuncMaybeObserver.getDisposable();\n }\n\n\n static <T> Maybe<T> create(OnSubscribe<T> onSubscribe) {\n return new MaybeCreate<>(onSubscribe);\n }\n\n @SuppressWarnings(\"unchecked\")\n static <T> Maybe<T> ofErr(Throwable err) {\n return (Maybe<T>) new ErrMaybe(err);\n }\n}"
},
{
"identifier": "Observable",
"path": "fiber-gateway-common/src/main/java/io/fiber/net/common/async/Observable.java",
"snippet": "public interface Observable<T> {\n\n interface Emitter<T> {\n\n void onNext(T value);\n\n void onError(Throwable error);\n\n void onComplete();\n\n boolean isDisposed();\n\n }\n\n interface Observer<T> {\n void onSubscribe(Disposable d);\n\n void onNext(T t);\n\n void onError(Throwable e);\n\n void onComplete();\n\n Scheduler scheduler();\n }\n\n @FunctionalInterface\n interface OnSubscribe<T> {\n\n void subscribe(Emitter<T> emitter) throws Throwable;\n }\n\n static <T> Observable<T> create(OnSubscribe<T> source) {\n return new ObservableCreate<>(source);\n }\n\n void subscribe(Observer<? super T> observer);\n\n default Maybe<T> toMaybe(Function2<? super T, ? super T, ? extends T> merge,\n Consumer<? super T> disFunc) {\n return new ObToMaybe<>(this, merge, disFunc);\n }\n\n @SuppressWarnings(\"unchecked\")\n default Maybe<T> toMaybe() {\n return toMaybe((Function2<? super T, ? super T, ? extends T>) Functions.getUseLaterMerger(),\n Functions.getNoopConsumer());\n }\n\n}"
}
] | import io.fiber.net.common.async.Maybe;
import io.fiber.net.common.async.Observable;
import io.netty.buffer.ByteBuf;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger; | 1,654 | package io.fiber.net.common;
public abstract class HttpExchange {
/**
* 尽量把 HttpExchange 这个类的性能优化得非常好
*
* @param <T>
*/
public static final class Attr<T> {
private static final AtomicInteger _ID_GEN = new AtomicInteger();
private static int ATTR_CAP = 8; // 不必使用volatile
private static int currentCap() {
return ATTR_CAP = _ID_GEN.get() + 2;// 留意下一个buffer。
}
private final int id;
private Attr() {
this.id = _ID_GEN.getAndIncrement();
// 这里可能产生并发问题,不过没关系,使用 attr 的时候会修正这个值。而且流有buffer
ATTR_CAP = Integer.max(ATTR_CAP, _ID_GEN.get() + 2);
}
public void set(HttpExchange input, T value) {
Object[] arr;
if ((arr = input.attrs) == null) {
arr = input.attrs = new Object[ATTR_CAP];
}
int idx;
if ((idx = this.id) >= arr.length) {
int cap = Attr.currentCap();
assert cap > arr.length;
arr = input.attrs = Arrays.copyOf(arr, cap);
}
arr[idx] = value;
}
@SuppressWarnings("unchecked")
public T get(HttpExchange input) {
Object[] arr;
int idx;
if ((arr = input.attrs) == null || (idx = this.id) >= arr.length) {
return null;
}
return (T) arr[idx];
}
@SuppressWarnings("unchecked")
public T remove(HttpExchange input) {
Object[] arr;
int idx;
if ((arr = input.attrs) == null || (idx = this.id) >= arr.length) {
return null;
}
T old = (T) arr[idx];
arr[idx] = null;
return old;
}
@Override
public int hashCode() {
return id;
}
}
/**
* 不要乱调用 !!!!!!!!
* <pre>
* private static final Input.Attr<ObjectNode> AUDIT_LOG = Input.createAttr();
*
* ObjectNode node = AUDIT_LOG.get(input);
* AUDIT_LOG.set(input, value);
* </pre>
*
* @param <T> KEY,
* @return attr !!!保存到全局,不要随意创建!!!否则会照成内存泄漏或者溢出
*/
public static <T> Attr<T> createAttr() {
return new Attr<>();
}
private Object[] attrs;
public abstract String getPath();
public abstract String getQuery();
public abstract String getUri();
public abstract void setRequestHeader(String name, String value);
public abstract void addRequestHeader(String name, String value);
public abstract String getRequestHeader(String name);
public abstract List<String> getRequestHeaderList(String name);
public abstract Collection<String> getRequestHeaderNames();
public abstract void setResponseHeader(String name, String value);
public abstract void addResponseHeader(String name, String value);
public abstract void removeResponseHeader(String name);
public abstract String getResponseHeader(String name);
public abstract List<String> getResponseHeaderList(String name);
public abstract Collection<String> getResponseHeaderNames();
public abstract HttpMethod getRequestMethod();
public abstract void writeJson(int status, Object result) throws FiberException;
public abstract void writeRawBytes(int status, ByteBuf buf) throws FiberException;
public void writeRawBytes(int status, Observable<ByteBuf> bufOb) throws FiberException {
writeRawBytes(status, bufOb, false);
}
public abstract void writeRawBytes(int status, Observable<ByteBuf> bufOb, boolean flush) throws FiberException;
public abstract boolean isResponseWrote();
public abstract void discardReqBody();
public abstract Observable<ByteBuf> readReqBody();
| package io.fiber.net.common;
public abstract class HttpExchange {
/**
* 尽量把 HttpExchange 这个类的性能优化得非常好
*
* @param <T>
*/
public static final class Attr<T> {
private static final AtomicInteger _ID_GEN = new AtomicInteger();
private static int ATTR_CAP = 8; // 不必使用volatile
private static int currentCap() {
return ATTR_CAP = _ID_GEN.get() + 2;// 留意下一个buffer。
}
private final int id;
private Attr() {
this.id = _ID_GEN.getAndIncrement();
// 这里可能产生并发问题,不过没关系,使用 attr 的时候会修正这个值。而且流有buffer
ATTR_CAP = Integer.max(ATTR_CAP, _ID_GEN.get() + 2);
}
public void set(HttpExchange input, T value) {
Object[] arr;
if ((arr = input.attrs) == null) {
arr = input.attrs = new Object[ATTR_CAP];
}
int idx;
if ((idx = this.id) >= arr.length) {
int cap = Attr.currentCap();
assert cap > arr.length;
arr = input.attrs = Arrays.copyOf(arr, cap);
}
arr[idx] = value;
}
@SuppressWarnings("unchecked")
public T get(HttpExchange input) {
Object[] arr;
int idx;
if ((arr = input.attrs) == null || (idx = this.id) >= arr.length) {
return null;
}
return (T) arr[idx];
}
@SuppressWarnings("unchecked")
public T remove(HttpExchange input) {
Object[] arr;
int idx;
if ((arr = input.attrs) == null || (idx = this.id) >= arr.length) {
return null;
}
T old = (T) arr[idx];
arr[idx] = null;
return old;
}
@Override
public int hashCode() {
return id;
}
}
/**
* 不要乱调用 !!!!!!!!
* <pre>
* private static final Input.Attr<ObjectNode> AUDIT_LOG = Input.createAttr();
*
* ObjectNode node = AUDIT_LOG.get(input);
* AUDIT_LOG.set(input, value);
* </pre>
*
* @param <T> KEY,
* @return attr !!!保存到全局,不要随意创建!!!否则会照成内存泄漏或者溢出
*/
public static <T> Attr<T> createAttr() {
return new Attr<>();
}
private Object[] attrs;
public abstract String getPath();
public abstract String getQuery();
public abstract String getUri();
public abstract void setRequestHeader(String name, String value);
public abstract void addRequestHeader(String name, String value);
public abstract String getRequestHeader(String name);
public abstract List<String> getRequestHeaderList(String name);
public abstract Collection<String> getRequestHeaderNames();
public abstract void setResponseHeader(String name, String value);
public abstract void addResponseHeader(String name, String value);
public abstract void removeResponseHeader(String name);
public abstract String getResponseHeader(String name);
public abstract List<String> getResponseHeaderList(String name);
public abstract Collection<String> getResponseHeaderNames();
public abstract HttpMethod getRequestMethod();
public abstract void writeJson(int status, Object result) throws FiberException;
public abstract void writeRawBytes(int status, ByteBuf buf) throws FiberException;
public void writeRawBytes(int status, Observable<ByteBuf> bufOb) throws FiberException {
writeRawBytes(status, bufOb, false);
}
public abstract void writeRawBytes(int status, Observable<ByteBuf> bufOb, boolean flush) throws FiberException;
public abstract boolean isResponseWrote();
public abstract void discardReqBody();
public abstract Observable<ByteBuf> readReqBody();
| public abstract Maybe<ByteBuf> readFullReqBody(); | 0 | 2023-12-08 15:18:05+00:00 | 4k |
sigbla/sigbla-pds | src/test/java/sigbla/app/pds/collection/mutable/MutableTreeMap.java | [
{
"identifier": "Builder",
"path": "src/main/java/sigbla/app/pds/collection/Builder.java",
"snippet": "public interface Builder<E, R> {\n @NotNull\n Builder<E, R> add(E element);\n\n @NotNull\n Builder<E, R> addAll(@NotNull Traversable<E> elements);\n\n @NotNull\n Builder<E, R> addAll(@NotNull java.lang.Iterable<E> elements);\n\n @NotNull\n Builder<E, R> addAll(@NotNull Iterator<E> iterator);\n\n @NotNull\n Builder<E, R> addAll(E e1, E e2, E... es);\n\n @NotNull\n R build();\n}"
},
{
"identifier": "BuilderFactory",
"path": "src/main/java/sigbla/app/pds/collection/BuilderFactory.java",
"snippet": "public interface BuilderFactory<E, R> {\n @NotNull\n Builder<E, R> newBuilder();\n}"
},
{
"identifier": "Map",
"path": "src/main/java/sigbla/app/pds/collection/Map.java",
"snippet": "@SuppressWarnings(\"NullableProblems\")\npublic interface Map<K, V> extends Iterable<Pair<K, V>> {\n /**\n * Returns a map with the value specified associated to the key specified.\n * <p>If value already exists for the key, it will be replaced.\n */\n @NotNull\n Map<K, V> put(@NotNull K key, V value);\n\n /**\n * Returns the value associated with the key or {@code null} if the no value exists with the key specified.\n */\n @Nullable\n V get(@NotNull K key);\n\n /**\n * Returns a map with the value associated with the key removed if it exists.\n */\n @NotNull\n Map<K, V> remove(@NotNull K key);\n\n /**\n * Returns the keys for this map.\n */\n @NotNull\n Iterable<K> keys();\n\n /**\n * Returns the values for this map.\n */\n @NotNull\n Iterable<V> values();\n\n /**\n * Returns true if this map contains the specified key.\n */\n boolean containsKey(@NotNull K key);\n\n /**\n * Returns an immutable view of this map as an instance of {@link java.util.Map}.\n */\n @NotNull\n java.util.Map<K, V> asMap();\n}"
},
{
"identifier": "Pair",
"path": "src/main/java/sigbla/app/pds/collection/Pair.java",
"snippet": "public class Pair<C1, C2> {\n private final C1 component1;\n private final C2 component2;\n\n public Pair(C1 component1, C2 component2) {\n this.component1 = component1;\n this.component2 = component2;\n }\n\n public C1 component1() {\n return component1;\n }\n\n public C2 component2() {\n return component2;\n }\n\n @Override\n public String toString() {\n return \"(\" + component1 + \", \" + component2 + \")\";\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (o == null || getClass() != o.getClass()) return false;\n\n Pair pair = (Pair) o;\n return !(component1 != null ? !component1.equals(pair.component1) : pair.component1 != null)\n && !(component2 != null ? !component2.equals(pair.component2) : pair.component2 != null);\n }\n\n @Override\n public int hashCode() {\n int result = component1 != null ? component1.hashCode() : 0;\n result = 31 * result + (component2 != null ? component2.hashCode() : 0);\n return result;\n }\n}"
},
{
"identifier": "SortedMap",
"path": "src/main/java/sigbla/app/pds/collection/SortedMap.java",
"snippet": "public interface SortedMap<K, V> extends Map<K, V> {\n @NotNull\n SortedMap<K, V> put(@NotNull K key, V value);\n\n @NotNull\n SortedMap<K, V> remove(@NotNull K key);\n\n /**\n * Returns the bottom of the map starting from the key specified.\n *\n * @param inclusive if true, the key will be included in the result, otherwise it will be excluded\n */\n @NotNull\n SortedMap<K, V> from(@NotNull K key, boolean inclusive);\n\n /**\n * Returns the top of the map up until the key specified.\n *\n * @param inclusive if true, the key will be included in the result, otherwise it will be excluded\n */\n @NotNull\n SortedMap<K, V> to(@NotNull K key, boolean inclusive);\n\n /**\n * Returns a subset of the map between the {@code from} and {@code to} keys specified.\n *\n * @param fromInclusive if true, the key will be included in the result, otherwise it will be excluded\n * @param toInclusive if true, the key will be included in the result, otherwise it will be excluded\n */\n @NotNull\n SortedMap<K, V> range(@NotNull K from, boolean fromInclusive, @NotNull K to, boolean toInclusive);\n\n /**\n * Returns the comparator associated with this map, or {@code null} if the default ordering is used.\n */\n Comparator<? super K> comparator();\n\n /**\n * Returns the first entry in the map or {@code null} if the map is empty.\n */\n @Nullable\n Pair<K, V> first();\n\n /**\n * Returns the last entry in the map or {@code null} if the map is empty.\n */\n @Nullable\n Pair<K, V> last();\n\n /**\n * Returns a map containing all elements in this map, excluding the first {@code number} of elements.\n */\n @NotNull\n SortedMap<K, V> drop(int number);\n\n /**\n * Returns a list containing the first {@code number} of elements from this list.\n */\n @NotNull\n SortedMap<K, V> take(int number);\n\n /**\n * Returns an immutable view of this map as an instance of {@code java.util.SortedMap}.\n */\n @NotNull\n java.util.SortedMap<K, V> asSortedMap();\n}"
},
{
"identifier": "AbstractSortedMap",
"path": "src/main/java/sigbla/app/pds/collection/internal/base/AbstractSortedMap.java",
"snippet": "public abstract class AbstractSortedMap<K, V> extends AbstractMap<K, V> implements SortedMap<K, V> {\n @NotNull\n @Override\n public SortedMap<K, V> from(@NotNull K key, boolean inclusive) {\n Pair<K, V> last = last();\n if (last == null) return this;\n return range(key, inclusive, last.component1(), true);\n }\n\n @NotNull\n @Override\n public SortedMap<K, V> to(@NotNull K key, boolean inclusive) {\n Pair<K, V> first = first();\n if (first == null) return this;\n return range(first.component1(), true, key, inclusive);\n }\n\n @NotNull\n @Override\n public java.util.SortedMap<K, V> asSortedMap() {\n return new SortedMapAdapter<K, V>(this);\n }\n}"
},
{
"identifier": "AbstractBuilder",
"path": "src/main/java/sigbla/app/pds/collection/internal/builder/AbstractBuilder.java",
"snippet": "public abstract class AbstractBuilder<E, R> implements Builder<E, R> {\n private boolean built = false;\n\n @NotNull\n @Override\n public Builder<E, R> addAll(@NotNull Traversable<E> elements) {\n elements.forEach(new Function<E, Object>() {\n @Override\n public Object invoke(E element) {\n add(element);\n return null;\n }\n });\n return this;\n }\n\n @NotNull\n @Override\n public Builder<E, R> addAll(@NotNull Iterable<E> elements) {\n for (E element : elements) {\n add(element);\n }\n return this;\n }\n\n @NotNull\n @Override\n public Builder<E, R> addAll(@NotNull Iterator<E> iterator) {\n while (iterator.hasNext()) {\n add(iterator.next());\n }\n return this;\n }\n\n @NotNull\n @Override\n public Builder<E, R> addAll(E e1, E e2, E... es) {\n add(e1);\n add(e2);\n for (E e : es) {\n add(e);\n }\n return this;\n }\n\n @NotNull\n @Override\n final public R build() {\n if (built) throw new IllegalStateException(\"Builders do not support multiple calls to build()\");\n built = true;\n return doBuild();\n }\n\n @NotNull\n public abstract R doBuild();\n}"
}
] | import org.jetbrains.annotations.Nullable;
import java.util.Comparator;
import java.util.Iterator;
import java.util.TreeMap;
import sigbla.app.pds.collection.Builder;
import sigbla.app.pds.collection.BuilderFactory;
import sigbla.app.pds.collection.Map;
import sigbla.app.pds.collection.Pair;
import sigbla.app.pds.collection.SortedMap;
import sigbla.app.pds.collection.internal.base.AbstractSortedMap;
import sigbla.app.pds.collection.internal.builder.AbstractBuilder;
import org.jetbrains.annotations.NotNull; | 2,503 | /*
* Copyright (c) 2014 Andrew O'Malley
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package sigbla.app.pds.collection.mutable;
/**
*
*/
public class MutableTreeMap<K, V> extends AbstractSortedMap<K, V> {
private java.util.SortedMap<K, V> underlying = new TreeMap<K, V>();
@NotNull | /*
* Copyright (c) 2014 Andrew O'Malley
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package sigbla.app.pds.collection.mutable;
/**
*
*/
public class MutableTreeMap<K, V> extends AbstractSortedMap<K, V> {
private java.util.SortedMap<K, V> underlying = new TreeMap<K, V>();
@NotNull | public static <K, V> BuilderFactory<Pair<K, V>, Map<K, V>> factory() { | 2 | 2023-12-10 15:10:13+00:00 | 4k |
AdanJoGoHe/sunandbeach | src/main/java/com/serex/beachandsun/items/VodkaItem.java | [
{
"identifier": "ItemInit",
"path": "src/main/java/com/serex/beachandsun/ItemInit.java",
"snippet": "public class ItemInit {\n public static final Item TROPICAL_CAN = registerItem(\"tropical\", new TropicalCanItem(new FabricItemSettings()));\n public static final Item EMPTY_TROPICAL_CAN = registerItem(\"empty_tropical\", new Item(new FabricItemSettings()));\n public static final Item TIRMA = registerItem(\"tirma\", new TirmaItem(new FabricItemSettings()));\n public static final Item GOFIO_BAG = registerItem(\"gofio_bag\", new GofioBagItem(new FabricItemSettings()));\n public static final Item VODKA = registerItem(\"vodka\", new VodkaItem(new FabricItemSettings()));\n public static final Item MALIBU = registerItem(\"malibu\", new MalibuItem(new FabricItemSettings()));\n public static final Item JUGGERNOG_DRINK = registerItem(\"juggernog_drink\", new JuggernogDrinkItem(new FabricItemSettings()));\n public static final Item REUSABLE_POTION = registerItem(\"reusable_potion\", new ReusablePotionItem(new FabricItemSettings()));\n public static final Item HONEY_RUM = registerItem(\"honey_rum\", new HoneyRumItem(new FabricItemSettings()));\n public static final Item MIRACLE_SWORD = registerItem(\"miracle_sword\", new MiracleSword(MIRACLE_SWORD_MATERIAL, 25, (float) -1.8 , new Item.Settings()));\n public static final Item WOODEN_MACE = registerItem(\"wooden_mace\", new WoodenMace(WOODEN_MACE_MATERIAL, 25, (float) -1.8 , new Item.Settings()));\n public static final Item GREEN_CHURRO = registerItem(\"green_churro\", new GreenChurroSword(GREEN_CHURRO_SWORD_MATERIAL, 3, (float) -1.8 , new Item.Settings()));\n public static final Item BLUE_CHURRO = registerItem(\"blue_churro\", new BlueChurroSword(BLUE_CHURRO_SWORD_MATERIAL, 3, (float) -1.8 , new Item.Settings()));\n\n public static final Item CANDELABRO = registerItem(\"candelabro\", new Candelabro(new FabricItemSettings()));\n\n private static void addItemsToMiscItemGroup(FabricItemGroupEntries entries){\n entries.add(TROPICAL_CAN);\n entries.add(TIRMA);\n entries.add(GOFIO_BAG);\n entries.add(EMPTY_TROPICAL_CAN);\n entries.add(VODKA);\n entries.add(MIRACLE_SWORD);\n entries.add(MALIBU);\n entries.add(WOODEN_MACE);\n entries.add(GREEN_CHURRO);\n entries.add(BLUE_CHURRO);\n entries.add(HONEY_RUM);\n entries.add(REUSABLE_POTION);\n entries.add(CANDELABRO);\n }\n\n private static Item registerItem(String name, Item item) {\n return Registry.register(Registries.ITEM, new Identifier(MODIDEF, name), item);\n }\n\n public static void registerItems(){\n BeachAndSun.LOGGER.info(\"Registering Mod items for {}\", MODIDEF);\n ItemGroupEvents.modifyEntriesEvent(ItemGroups.INGREDIENTS).register(ItemInit::addItemsToMiscItemGroup);\n }\n}"
},
{
"identifier": "ModSounds",
"path": "src/main/java/com/serex/beachandsun/sound/ModSounds.java",
"snippet": "public class ModSounds {\n public static SoundEvent VODKA_FINISH_SOUND = registerSoundEvent(\"vodka_finish_drink\");\n public static SoundEvent LC_SHOP_SONG = registerSoundEvent(\"lc_shop_song\");\n public static SoundEvent QUICK_REVIVE_SOUND = registerSoundEvent(\"quick_revive_sound\");\n\n private static SoundEvent registerSoundEvent(String name){\n Identifier id = new Identifier(Constants.MODIDEF, name);\n return Registry.register(Registries.SOUND_EVENT, id, SoundEvent.of(id));\n }\n\n public static void registerSounds(){\n BeachAndSun.LOGGER.info(\"Registering Mod Sounds for {}\", MODIDEF);\n }\n}"
}
] | import com.serex.beachandsun.ItemInit;
import com.serex.beachandsun.sound.ModSounds;
import java.util.List;
import net.minecraft.advancement.criterion.Criteria;
import net.minecraft.client.item.TooltipContext;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.effect.StatusEffectInstance;
import net.minecraft.entity.effect.StatusEffects;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.item.ItemUsage;
import net.minecraft.potion.PotionUtil;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.stat.Stats;
import net.minecraft.text.Text;
import net.minecraft.util.Hand;
import net.minecraft.util.TypedActionResult;
import net.minecraft.util.UseAction;
import net.minecraft.world.World;
import net.minecraft.world.event.GameEvent;
import org.jetbrains.annotations.Nullable; | 1,648 | package com.serex.beachandsun.items;
public class VodkaItem extends Item {
public VodkaItem(Settings settings) {
super(settings);
}
public TypedActionResult<ItemStack> use(World world, PlayerEntity user, Hand hand) {
return ItemUsage.consumeHeldItem(world, user, hand);
}
@Override
public UseAction getUseAction(ItemStack stack) {
return UseAction.DRINK;
}
@Override
public int getMaxUseTime(ItemStack stack) {
return 32;
}
@Override
public ItemStack finishUsing(ItemStack stack, World world, LivingEntity user) {
PlayerEntity playerEntity;
PlayerEntity playerEntity2 = playerEntity = user instanceof PlayerEntity ? (PlayerEntity)user : null;
if (playerEntity instanceof ServerPlayerEntity) {
Criteria.CONSUME_ITEM.trigger((ServerPlayerEntity)playerEntity, stack);
}
if (!world.isClient) {
List<StatusEffectInstance> list = PotionUtil.getPotionEffects(stack);
for (StatusEffectInstance statusEffectInstance : list) {
if (statusEffectInstance.getEffectType().isInstant()) {
statusEffectInstance.getEffectType().applyInstantEffect(playerEntity, playerEntity, user, statusEffectInstance.getAmplifier(), 1.0);
continue;
}
user.addStatusEffect(new StatusEffectInstance(statusEffectInstance));
}
}
if (playerEntity != null) {
playerEntity.incrementStat(Stats.USED.getOrCreateStat(this));
if (!playerEntity.getAbilities().creativeMode) {
stack.decrement(1);
}
}
if (playerEntity == null || !playerEntity.getAbilities().creativeMode) {
if (stack.isEmpty()) {
user.addStatusEffect(new StatusEffectInstance(StatusEffects.BLINDNESS, 200, 1));
user.addStatusEffect(new StatusEffectInstance(StatusEffects.NAUSEA, 200, 2));
user.addStatusEffect(new StatusEffectInstance(StatusEffects.WEAKNESS, 1000, 1));
user.addStatusEffect(new StatusEffectInstance(StatusEffects.SATURATION, 1000, 1));
user.addStatusEffect(new StatusEffectInstance(StatusEffects.REGENERATION, 3000, 1));
user.addStatusEffect(new StatusEffectInstance(StatusEffects.INSTANT_HEALTH, 1, 1));
user.addStatusEffect(new StatusEffectInstance(StatusEffects.JUMP_BOOST, 3000, 1)); | package com.serex.beachandsun.items;
public class VodkaItem extends Item {
public VodkaItem(Settings settings) {
super(settings);
}
public TypedActionResult<ItemStack> use(World world, PlayerEntity user, Hand hand) {
return ItemUsage.consumeHeldItem(world, user, hand);
}
@Override
public UseAction getUseAction(ItemStack stack) {
return UseAction.DRINK;
}
@Override
public int getMaxUseTime(ItemStack stack) {
return 32;
}
@Override
public ItemStack finishUsing(ItemStack stack, World world, LivingEntity user) {
PlayerEntity playerEntity;
PlayerEntity playerEntity2 = playerEntity = user instanceof PlayerEntity ? (PlayerEntity)user : null;
if (playerEntity instanceof ServerPlayerEntity) {
Criteria.CONSUME_ITEM.trigger((ServerPlayerEntity)playerEntity, stack);
}
if (!world.isClient) {
List<StatusEffectInstance> list = PotionUtil.getPotionEffects(stack);
for (StatusEffectInstance statusEffectInstance : list) {
if (statusEffectInstance.getEffectType().isInstant()) {
statusEffectInstance.getEffectType().applyInstantEffect(playerEntity, playerEntity, user, statusEffectInstance.getAmplifier(), 1.0);
continue;
}
user.addStatusEffect(new StatusEffectInstance(statusEffectInstance));
}
}
if (playerEntity != null) {
playerEntity.incrementStat(Stats.USED.getOrCreateStat(this));
if (!playerEntity.getAbilities().creativeMode) {
stack.decrement(1);
}
}
if (playerEntity == null || !playerEntity.getAbilities().creativeMode) {
if (stack.isEmpty()) {
user.addStatusEffect(new StatusEffectInstance(StatusEffects.BLINDNESS, 200, 1));
user.addStatusEffect(new StatusEffectInstance(StatusEffects.NAUSEA, 200, 2));
user.addStatusEffect(new StatusEffectInstance(StatusEffects.WEAKNESS, 1000, 1));
user.addStatusEffect(new StatusEffectInstance(StatusEffects.SATURATION, 1000, 1));
user.addStatusEffect(new StatusEffectInstance(StatusEffects.REGENERATION, 3000, 1));
user.addStatusEffect(new StatusEffectInstance(StatusEffects.INSTANT_HEALTH, 1, 1));
user.addStatusEffect(new StatusEffectInstance(StatusEffects.JUMP_BOOST, 3000, 1)); | user.playSound(ModSounds.VODKA_FINISH_SOUND,1,1); | 1 | 2023-12-06 10:53:54+00:00 | 4k |
netty/netty-incubator-codec-ohttp | codec-ohttp-hpke-classes-boringssl/src/main/java/io/netty/incubator/codec/hpke/boringssl/BoringSSLOHttpCryptoProvider.java | [
{
"identifier": "AEAD",
"path": "codec-ohttp-hpke/src/main/java/io/netty/incubator/codec/hpke/AEAD.java",
"snippet": "public enum AEAD {\n AES_GCM128((short) 0x0001, 16, 12),\n AES_GCM256((short) 0x0002, 32, 12),\n CHACHA20_POLY1305((short) 0x0003, 32, 12);\n\n public static AEAD forId(short id) {\n for (AEAD val : values()) {\n if (val.id == id) {\n return val;\n }\n }\n throw new IllegalArgumentException(\"unknown AEAD id \" + id);\n }\n\n private final short id;\n private final int nk;\n private final int nn;\n\n AEAD(short id, int nk, int nn) {\n this.id = id;\n this.nk = nk;\n this.nn = nn;\n }\n\n public short id() {\n return id;\n }\n\n public int nk() {\n return nk;\n }\n\n public int nn() {\n return nn;\n }\n}"
},
{
"identifier": "AEADContext",
"path": "codec-ohttp-hpke/src/main/java/io/netty/incubator/codec/hpke/AEADContext.java",
"snippet": "public interface AEADContext extends CryptoDecryptContext, CryptoEncryptContext {\n // TODO: Move some methods in here.\n}"
},
{
"identifier": "AsymmetricCipherKeyPair",
"path": "codec-ohttp-hpke/src/main/java/io/netty/incubator/codec/hpke/AsymmetricCipherKeyPair.java",
"snippet": "public interface AsymmetricCipherKeyPair {\n\n /**\n * Returns the public key parameters.\n *\n * @return the public key parameters.\n */\n AsymmetricKeyParameter publicParameters();\n\n /**\n * Returns the private key parameters.\n *\n * @return the private key parameters.\n */\n AsymmetricKeyParameter privateParameters();\n}"
},
{
"identifier": "AsymmetricKeyParameter",
"path": "codec-ohttp-hpke/src/main/java/io/netty/incubator/codec/hpke/AsymmetricKeyParameter.java",
"snippet": "public interface AsymmetricKeyParameter {\n\n /**\n * Returns the parameter as byte encoded or {@code null}\n * if not supported by the used implementation or parameter type.\n *\n * @return encoded.\n */\n byte[] encoded();\n\n /**\n * Returns {@code true} if this is the private key, {@code false} otherwise.\n *\n * @return {@code true} if this is the private key.\n */\n boolean isPrivate();\n}"
},
{
"identifier": "HPKERecipientContext",
"path": "codec-ohttp-hpke/src/main/java/io/netty/incubator/codec/hpke/HPKERecipientContext.java",
"snippet": "public interface HPKERecipientContext extends HPKEContext, CryptoDecryptContext {\n}"
},
{
"identifier": "HPKESenderContext",
"path": "codec-ohttp-hpke/src/main/java/io/netty/incubator/codec/hpke/HPKESenderContext.java",
"snippet": "public interface HPKESenderContext extends HPKEContext, CryptoEncryptContext {\n /**\n * Return the bytes that are used for encapsulation.\n *\n * @return encapsulation\n */\n byte[] encapsulation();\n}"
},
{
"identifier": "KDF",
"path": "codec-ohttp-hpke/src/main/java/io/netty/incubator/codec/hpke/KDF.java",
"snippet": "public enum KDF {\n HKDF_SHA256((short) 0x0001),\n HKDF_SHA384((short) 0x0002),\n HKDF_SHA512((short) 0x0003);\n\n public static KDF forId(short id) {\n for (KDF val : values()) {\n if (val.id == id) {\n return val;\n }\n }\n throw new IllegalArgumentException(\"unknown KDF id \" + id);\n }\n\n private final short id;\n\n KDF(short id) {\n this.id = id;\n }\n\n public short id() {\n return id;\n }\n}"
},
{
"identifier": "KEM",
"path": "codec-ohttp-hpke/src/main/java/io/netty/incubator/codec/hpke/KEM.java",
"snippet": "public enum KEM {\n P256_SHA256((short) 16, 65, 65),\n P384_SHA348((short) 17, 97, 97),\n P521_SHA512((short) 18, 133, 133),\n X25519_SHA256((short) 32, 32, 32),\n X448_SHA512((short) 33, 56, 56);\n\n public static KEM forId(short id) {\n for (KEM val : values()) {\n if (val.id == id) {\n return val;\n }\n }\n throw new IllegalArgumentException(\"unknown KEM id \" + id);\n }\n\n KEM(short id, int nenc, int npk) {\n this.id = id;\n this.nenc = nenc;\n this.npk = npk;\n }\n\n private final short id;\n private final int nenc;\n private final int npk;\n\n public short id() {\n return id;\n }\n\n public int nenc() {\n return nenc;\n }\n\n public int npk() {\n return npk;\n }\n}"
},
{
"identifier": "OHttpCryptoProvider",
"path": "codec-ohttp-hpke/src/main/java/io/netty/incubator/codec/hpke/OHttpCryptoProvider.java",
"snippet": "public interface OHttpCryptoProvider {\n /**\n * Creates a new {@link AEADContext} instance implementation of\n * <a href=\"https://datatracker.ietf.org/doc/html/rfc5116\">An AEAD encryption algorithm [RFC5116]</a>.\n *\n * @param aead the {@link AEAD} to use.\n * @param key the key to use.\n * @param baseNonce the nounce to use.\n * @return the created {@link AEADContext} based on the given arguments.\n */\n AEADContext setupAEAD(AEAD aead, byte[] key, byte[] baseNonce);\n\n /**\n * Establish a {@link HPKESenderContext} that can be used for encryption.\n *\n * @param kem the {@link KEM} to use.\n * @param kdf the {@link KDF} to use.\n * @param aead the {@link AEAD} to use.\n * @param pkR the public key.\n * @param info info parameter.\n * @param kpE the ephemeral keypair that is used for the seed or {@code null} if none should be used.\n * @return the context.\n */\n HPKESenderContext setupHPKEBaseS(KEM kem, KDF kdf, AEAD aead,\n AsymmetricKeyParameter pkR, byte[] info, AsymmetricCipherKeyPair kpE);\n\n /**\n * Establish a {@link HPKERecipientContext} that can be used for decryption.\n *\n * @param kem the {@link KEM} to use.\n * @param kdf the {@link KDF} to use.\n * @param aead the {@link AEAD} to use.\n * @param enc an encapsulated KEM shared secret.\n * @param skR the private key.\n * @param info info parameter.\n * @return the context.\n */\n HPKERecipientContext setupHPKEBaseR(KEM kem, KDF kdf, AEAD aead, byte[] enc,\n AsymmetricCipherKeyPair skR, byte[] info);\n\n /**\n * Deserialize the input and return the private key.\n *\n * @param kem the {@link KEM} that is used.\n * @param privateKeyBytes the private key\n * @param publicKeyBytes the public key.\n * @return the deserialized {@link AsymmetricCipherKeyPair}.\n */\n AsymmetricCipherKeyPair deserializePrivateKey(KEM kem, byte[] privateKeyBytes, byte[] publicKeyBytes);\n\n /**\n * Deserialize the input and return the public key.\n *\n * @param kem the {@link KEM} that is used.\n * @param publicKeyBytes the public key.\n * @return the deserialized {@link AsymmetricKeyParameter}.\n */\n AsymmetricKeyParameter deserializePublicKey(KEM kem, byte[] publicKeyBytes);\n\n /**\n * Generate a random private key. Please note that this might not be possible for all of the {@link KEM} and so\n * this method might throw an {@link UnsupportedOperationException}.\n *\n * @param kem the {@link KEM} that is used.\n * @return the generated key.\n */\n AsymmetricCipherKeyPair newRandomPrivateKey(KEM kem);\n\n /**\n * Returns {@code true} if the given {@link AEAD} is supported by the implementation, {@code false} otherwise.\n *\n * @param aead the {@link AEAD}.\n * @return if supported.\n */\n boolean isSupported(AEAD aead);\n\n /**\n * Returns {@code true} if the given {@link KEM} is supported by the implementation, {@code false} otherwise.\n *\n * @param kem the {@link KEM}.\n * @return if supported.\n */\n boolean isSupported(KEM kem);\n\n /**\n * Returns {@code true} if the given {@link KDF} is supported by the implementation, {@code false} otherwise.\n *\n * @param kdf the {@link KDF}.\n * @return if supported.\n */\n boolean isSupported(KDF kdf);\n}"
}
] | import io.netty.incubator.codec.hpke.AEAD;
import io.netty.incubator.codec.hpke.AEADContext;
import io.netty.incubator.codec.hpke.AsymmetricCipherKeyPair;
import io.netty.incubator.codec.hpke.AsymmetricKeyParameter;
import io.netty.incubator.codec.hpke.HPKERecipientContext;
import io.netty.incubator.codec.hpke.HPKESenderContext;
import io.netty.incubator.codec.hpke.KDF;
import io.netty.incubator.codec.hpke.KEM;
import io.netty.incubator.codec.hpke.OHttpCryptoProvider;
import java.util.Arrays; | 2,747 | /*
* Copyright 2023 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.netty.incubator.codec.hpke.boringssl;
/**
* BoringSSL based {@link OHttpCryptoProvider}. {@link BoringSSLHPKE#ensureAvailability()} or
* {@link BoringSSLHPKE#isAvailable()} should be used before accessing {@link #INSTANCE} to ensure
* the native library can be loaded on the used platform.
*/
public final class BoringSSLOHttpCryptoProvider implements OHttpCryptoProvider {
/**
* {@link BoringSSLOHttpCryptoProvider} instance.
*/
public static final BoringSSLOHttpCryptoProvider INSTANCE = new BoringSSLOHttpCryptoProvider();
private BoringSSLOHttpCryptoProvider() {
}
@Override | /*
* Copyright 2023 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.netty.incubator.codec.hpke.boringssl;
/**
* BoringSSL based {@link OHttpCryptoProvider}. {@link BoringSSLHPKE#ensureAvailability()} or
* {@link BoringSSLHPKE#isAvailable()} should be used before accessing {@link #INSTANCE} to ensure
* the native library can be loaded on the used platform.
*/
public final class BoringSSLOHttpCryptoProvider implements OHttpCryptoProvider {
/**
* {@link BoringSSLOHttpCryptoProvider} instance.
*/
public static final BoringSSLOHttpCryptoProvider INSTANCE = new BoringSSLOHttpCryptoProvider();
private BoringSSLOHttpCryptoProvider() {
}
@Override | public AEADContext setupAEAD(AEAD aead, byte[] key, byte[] baseNonce) { | 0 | 2023-12-06 09:14:09+00:00 | 4k |
xia0ne/NotificationTools | src/main/java/com/example/notificationtools/controller/TaskController.java | [
{
"identifier": "TaskConfig",
"path": "src/main/java/com/example/notificationtools/config/TaskConfig.java",
"snippet": "@Configuration\n@Log\n@EnableScheduling\npublic class TaskConfig implements SchedulingConfigurer {\n\n\t@Resource\n\tprivate TaskServiceImpl taskService;\n\t@Resource\n\tprivate ScheduleServiceImpl scheduleService;\n\t@Resource\n\tprivate RedisServiceImpl redisService;\n\n\t@Override\n\tpublic void configureTasks(ScheduledTaskRegistrar taskRegistrar) {\n\t\tThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();\n\t\ttaskScheduler.setPoolSize(50);\n\t\ttaskScheduler.setThreadNamePrefix(\"-notificationtools-\");\n\t\ttaskScheduler.initialize();\n\t\ttaskRegistrar.setTaskScheduler(taskScheduler);\n\t\ttaskScheduler.getScheduledThreadPoolExecutor().getQueue().clear();\n\t\tList<TaskEntity> list = taskService.list();\n\t\tfor (TaskEntity task : list) {\n\t\t\ttaskRegistrar.addCronTask(() -> {\n\t\t\t\ttry {\n\t\t\t\t\tscheduleService.addTask(task);\n\t\t\t\t\tredisService.setCount(task.getBelongId());\n\t\t\t\t} catch (Exception e) {\n\t\t\t\t\tthrow new RuntimeException(e);\n\t\t\t\t}\n\t\t\t}, task.getCrontabRule());\n\t\t}\n\t}\n\n\tpublic static List<Integer> getTaskId() {\n\t\treturn List.of(-1, 0, 1);\n\t}\n}"
},
{
"identifier": "TaskEntity",
"path": "src/main/java/com/example/notificationtools/domain/entity/TaskEntity.java",
"snippet": "@Data\n@TableName(\"tasks\")\npublic class TaskEntity {\n\t@TableId(value=\"id\", type = IdType.AUTO)\n\tprivate Integer id;\n\t@TableField(\"task_key\")\n\tprivate String taskKey;\n\t@TableField(\"belong_id\")\n\tprivate Integer belongId;\n\t@TableField(\"crontab_rule\")\n\tprivate String crontabRule;\n\t@TableField(\"message\")\n\tprivate String message;\n\t@TableField(\"start_time\")\n\tprivate Date startTime;\n\t@TableField(\"end_time\")\n\tprivate Date endTime;\n}"
},
{
"identifier": "ScheduleService",
"path": "src/main/java/com/example/notificationtools/service/ScheduleService.java",
"snippet": "public interface ScheduleService {\n\tpublic void setTaskScheduler(TaskEntity task);\n\n\tpublic void addTask(TaskEntity task);\n\n\tpublic int getLength();\n\n\tpublic String getCron(int id);\n\n\tpublic String getMessage(int id);\n\t\n}"
},
{
"identifier": "RedisServiceImpl",
"path": "src/main/java/com/example/notificationtools/service/impl/RedisServiceImpl.java",
"snippet": "@Service\n@Log\npublic class RedisServiceImpl implements RedisService {\n\t@Resource\n\tprivate RedisTemplate<String, Object> redisTemplate;\n\n\t/*\n\t-1 custom\n\t0 drink\n\t1 tig\n\t */\n\t@Override\n\tpublic boolean setCount(int taskId) {\n\t\ttry {\n\t\t\tredisTemplate.opsForValue().increment(\"count:\" + taskId);\n\t\t\treturn true;\n\n\t\t} catch (Exception e) {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t@Override\n\tpublic List<HashMap<Integer, Object>> getCount() {\n\t\ttry {\n\t\t\tList<Integer> taskId = TaskConfig.getTaskId();\n\t\t\tList<String> keys = taskId.stream().map(id -> \"count:\" + id).toList();\n\t\t\tList<Object> counts = redisTemplate.opsForValue().multiGet(keys);\n\t\t\tList<HashMap<Integer, Object>> result = new ArrayList<>();\n\t\t\tfor (int i = 0; i < taskId.size(); i++) {\n\t\t\t\tif (counts.get(i) != null) {\n\t\t\t\t\tresult.add(new HashMap<>(Map.of(taskId.get(i), counts.get(i))));\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn result;\n\t\t} catch (Exception e) {\n\t\t\treturn null;\n\t\t}\n\t}\n\n\n\t@Override\n\tpublic boolean setLog(String logs) {\n\t\tlog.info(\"setLog \" + logs);\n\t\ttry {\n\t\t\tredisTemplate.opsForList().rightPush(\"logs\", logs);\n\t\t\tLong size = redisTemplate.opsForList().size(\"logs\");\n\t\t\tif (size > 10) {\n\t\t\t\tredisTemplate.opsForList().trim(\"log\", size - 10, size);\n\t\t\t}\n\t\t\treturn true;\n\t\t} catch (Exception e) {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t@Override\n\tpublic List<Object> getLogs(int index, int offset) {\n\t\treturn redisTemplate.opsForList().range(\"logs\", index, Math.min(index + offset - 1, index + 9)).stream()\n\t\t\t\t\t\t.map(Object::toString)\n\t\t\t\t\t\t.collect(Collectors.toList());\n\t}\n}"
},
{
"identifier": "TaskServiceImpl",
"path": "src/main/java/com/example/notificationtools/service/impl/TaskServiceImpl.java",
"snippet": "@Service\npublic class TaskServiceImpl extends ServiceImpl<TaskMapper, TaskEntity> implements TaskService {\n\n\t@Override\n\tpublic TaskEntity addToDataBases(int belong_id, String taskKey, String crontab_rule, String message) {\n\t\tQueryWrapper<TaskEntity> queryWrapper = new QueryWrapper<>();\n\t\tqueryWrapper.eq(\"belong_id\", belong_id)\n\t\t\t\t\t\t.eq(\"crontab_rule\", crontab_rule)\n\t\t\t\t\t\t.eq(\"task_key\", taskKey)\n\t\t\t\t\t\t.eq(\"message\", message);\n\t\tList<TaskEntity> tasks = list(queryWrapper);\n\t\tif(!tasks.isEmpty()){\n\t\t\treturn null;\n\t\t}\n\t\tTaskEntity taskEntity = new TaskEntity();\n\t\ttaskEntity.setCrontabRule(crontab_rule);\n\t\ttaskEntity.setTaskKey(taskKey);\n\t\ttaskEntity.setBelongId(belong_id);\n\t\ttaskEntity.setStartTime(new Date());\n\t\ttaskEntity.setEndTime(new Date());\n\t\ttaskEntity.setMessage(message);\n\t\tif(save(taskEntity)){\n\t\t\treturn taskEntity;\n\t\t}else{\n\t\t\treturn null;\n\t\t}\n\t}\n}"
},
{
"identifier": "CheckCrontab",
"path": "src/main/java/com/example/notificationtools/utils/CheckCrontab.java",
"snippet": "public class CheckCrontab {\n\n\tpublic static boolean isValidCronExpression(String crontab) {\n\t\treturn CronExpression.isValidExpression(crontab);\n\t}\n\n\tpublic static boolean isFrequencyGreaterThan10Minutes(String crontab) {\n\t\ttry {\n\t\t\tCronExpression cronExpression = new CronExpression(crontab);\n\t\t\tDate now = DateUtil.date();\n\t\t\tlong nextExecutionTime = cronExpression.getNextValidTimeAfter(now).getTime();\n\t\t\tlong differenceInMinutes = (nextExecutionTime - now.getTime()) / (60 * 1000);\n\t\t\treturn differenceInMinutes > 10;\n\t\t} catch (Exception e) {\n\t\t\treturn false;\n\t\t}\n\t}\n}"
},
{
"identifier": "ResponseResult",
"path": "src/main/java/com/example/notificationtools/utils/ResponseResult.java",
"snippet": "@Data\n@Builder\npublic class ResponseResult<T>{\n\tprivate long timestamp;\n\tprivate String status;\n\tprivate String message;\n\tprivate T data;\n\n\tpublic static <T> ResponseResult<T> success(){\n\t\treturn success(null);\n\t}\n\n\tpublic static <T> ResponseResult<T> success(T data){\n\t\treturn ResponseResult.<T>builder().data(data)\n\t\t\t\t\t\t.message(ResponeseStatus.SUCCESS.getDescription())\n\t\t\t\t\t\t.status(ResponeseStatus.SUCCESS.getResponeseCode())\n\t\t\t\t\t\t.timestamp(System.currentTimeMillis())\n\t\t\t\t\t\t.build();\n\t}\n\n\tpublic static <T> ResponseResult<T> fail(String message){\n\t\treturn fail(null, message);\n\t}\n\n\tpublic static <T> ResponseResult<T> fail(T data, String message){\n\t\treturn ResponseResult.<T>builder().data(data)\n\t\t\t\t\t\t.message(message)\n\t\t\t\t\t\t.status(ResponeseStatus.FAIL.getResponeseCode())\n\t\t\t\t\t\t.timestamp(System.currentTimeMillis())\n\t\t\t\t\t\t.build();\n\t}\n}"
},
{
"identifier": "SendMessage",
"path": "src/main/java/com/example/notificationtools/utils/SendMessage.java",
"snippet": "@Component\n@Log\npublic class SendMessage {\n//\t@Value(\"${pushTools.api}\")\n\tprivate static String api = \"http://api2.pushdeer.com\";\n\n\tpublic static void sendMessage(String key, String message) throws Exception {\n\t\tString encodedMessage = URLEncoder.encode(message, StandardCharsets.UTF_8);\n\t\tString to = String.format(\"%s/message/push?pushkey=%s&text=%s\", api, key, encodedMessage);\n\t\tURL obj = new URL(to);\n\t\tHttpURLConnection con = (HttpURLConnection)obj.openConnection();\n\t\tcon.setRequestProperty(\"Accept\", \"text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7\");\n\t\tcon.setRequestProperty(\"User-Agent\", \"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36\");\n\t\tcon.setConnectTimeout(5000);\n\t\tcon.setReadTimeout(5000);\n\t\tcon.setRequestMethod(\"GET\");\n\t\tlog.info(\"在 \" + DateUtil.now() + \" 发送了一条消息 \" + message + \" 状态\" + con.getResponseCode());\n\t}\n\n}"
}
] | import cn.hutool.core.date.DateUtil;
import com.example.notificationtools.config.TaskConfig;
import com.example.notificationtools.domain.entity.TaskEntity;
import com.example.notificationtools.service.ScheduleService;
import com.example.notificationtools.service.impl.RedisServiceImpl;
import com.example.notificationtools.service.impl.TaskServiceImpl;
import com.example.notificationtools.utils.CheckCrontab;
import com.example.notificationtools.utils.ResponseResult;
import com.example.notificationtools.utils.SendMessage;
import jakarta.annotation.Resource;
import jdk.jshell.execution.Util;
import lombok.extern.java.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*; | 2,237 | package com.example.notificationtools.controller;
@RestController
@RequestMapping("/api")
@Log
public class TaskController {
@Resource
TaskServiceImpl taskService;
@Resource | package com.example.notificationtools.controller;
@RestController
@RequestMapping("/api")
@Log
public class TaskController {
@Resource
TaskServiceImpl taskService;
@Resource | RedisServiceImpl redisService; | 3 | 2023-12-05 06:46:58+00:00 | 4k |
lyswhut/react-native-local-media-metadata | android/src/main/java/org/jaudiotagger/tag/datatype/PairedTextEncodedStringNullTerminated.java | [
{
"identifier": "InvalidDataTypeException",
"path": "android/src/main/java/org/jaudiotagger/tag/InvalidDataTypeException.java",
"snippet": "public class InvalidDataTypeException extends InvalidTagException\n{\n /**\n * Creates a new InvalidDataTypeException datatype.\n */\n public InvalidDataTypeException()\n {\n }\n\n /**\n * Creates a new InvalidDataTypeException datatype.\n *\n * @param ex the cause.\n */\n public InvalidDataTypeException(Throwable ex)\n {\n super(ex);\n }\n\n /**\n * Creates a new InvalidDataTypeException datatype.\n *\n * @param msg the detail message.\n */\n public InvalidDataTypeException(String msg)\n {\n super(msg);\n }\n\n /**\n * Creates a new InvalidDataTypeException datatype.\n *\n * @param msg the detail message.\n * @param ex the cause.\n */\n public InvalidDataTypeException(String msg, Throwable ex)\n {\n super(msg, ex);\n }\n}"
},
{
"identifier": "AbstractTagFrameBody",
"path": "android/src/main/java/org/jaudiotagger/tag/id3/AbstractTagFrameBody.java",
"snippet": "public abstract class AbstractTagFrameBody extends AbstractTagItem\n{\n public void createStructure()\n {\n }\n\n /**\n * Reference to the header associated with this frame body, a framebody can be created without a header\n * but one it is associated with a header this should be set. It is principally useful for the framebody to know\n * its header, because this will specify its tag version and some framebodies behave slighly different\n * between tag versions.\n */\n private AbstractTagFrame header;\n\n /**\n * List of data types that make up this particular frame body.\n */\n protected ArrayList<AbstractDataType> objectList = new ArrayList<AbstractDataType>();\n\n /**\n * Return the Text Encoding\n *\n * @return the text encoding used by this framebody\n */\n public final byte getTextEncoding()\n {\n AbstractDataType o = getObject(DataTypes.OBJ_TEXT_ENCODING);\n\n if (o != null)\n {\n Long encoding = (Long) (o.getValue());\n return encoding.byteValue();\n }\n else\n {\n return TextEncoding.ISO_8859_1;\n }\n }\n\n /**\n * Set the Text Encoding to use for this frame body\n *\n * @param textEncoding to use for this frame body\n */\n public final void setTextEncoding(byte textEncoding)\n {\n //Number HashMap actually converts this byte to a long\n setObjectValue(DataTypes.OBJ_TEXT_ENCODING, textEncoding);\n }\n\n\n /**\n * Creates a new framebody, at this point the bodys\n * ObjectList is setup which defines what datatypes are expected in body\n */\n protected AbstractTagFrameBody()\n {\n setupObjectList();\n }\n\n /**\n * Copy Constructor for fragment body. Copies all objects in the\n * Object Iterator with data.\n * @param copyObject\n */\n protected AbstractTagFrameBody(AbstractTagFrameBody copyObject)\n {\n AbstractDataType newObject;\n for (int i = 0; i < copyObject.objectList.size(); i++)\n {\n newObject = (AbstractDataType) ID3Tags.copyObject(copyObject.objectList.get(i));\n newObject.setBody(this);\n this.objectList.add(newObject);\n }\n }\n\n\n /**\n *\n * @return the text value that the user would expect to see for this framebody type, this should be overridden\n * for all frame-bodies\n */\n public String getUserFriendlyValue()\n {\n return toString();\n }\n\n /**\n * This method calls <code>toString</code> for all it's objects and appends\n * them without any newline characters.\n *\n * @return brief description string\n */\n public String getBriefDescription()\n {\n String str = \"\";\n for (AbstractDataType object : objectList)\n {\n if ((object.toString() != null) && (object.toString().length() > 0))\n {\n str += (object.getIdentifier() + \"=\\\"\" + object.toString() + \"\\\"; \");\n }\n }\n return str;\n }\n\n\n /**\n * This method calls <code>toString</code> for all it's objects and appends\n * them. It contains new line characters and is more suited for display\n * purposes\n *\n * @return formatted description string\n */\n public final String getLongDescription()\n {\n String str = \"\";\n for (AbstractDataType object : objectList)\n {\n if ((object.toString() != null) && (object.toString().length() > 0))\n {\n str += (object.getIdentifier() + \" = \" + object.toString() + \"\\n\");\n }\n }\n return str;\n }\n\n /**\n * Sets all objects of identifier type to value defined by <code>obj</code> argument.\n *\n * @param identifier <code>MP3Object</code> identifier\n * @param value new datatype value\n */\n public final void setObjectValue(String identifier, Object value)\n {\n AbstractDataType object;\n Iterator<AbstractDataType> iterator = objectList.listIterator();\n while (iterator.hasNext())\n {\n object = iterator.next();\n if (object.getIdentifier().equals(identifier))\n {\n object.setValue(value);\n }\n }\n }\n\n /**\n * Returns the value of the datatype with the specified\n * <code>identifier</code>\n *\n * @param identifier\n * @return the value of the dattype with the specified\n * <code>identifier</code>\n */\n public final Object getObjectValue(String identifier)\n {\n return getObject(identifier).getValue();\n }\n\n /**\n * Returns the datatype with the specified\n * <code>identifier</code>\n *\n * @param identifier\n * @return the datatype with the specified\n * <code>identifier</code>\n */\n public final AbstractDataType getObject(String identifier)\n {\n AbstractDataType object;\n Iterator<AbstractDataType> iterator = objectList.listIterator();\n while (iterator.hasNext())\n {\n object = iterator.next();\n if (object.getIdentifier().equals(identifier))\n {\n return object;\n }\n }\n return null;\n }\n\n /**\n * Returns the size in bytes of this fragmentbody\n *\n * @return estimated size in bytes of this datatype\n */\n public int getSize()\n {\n int size = 0;\n AbstractDataType object;\n Iterator<AbstractDataType> iterator = objectList.listIterator();\n while (iterator.hasNext())\n {\n object = iterator.next();\n size += object.getSize();\n }\n return size;\n }\n\n /**\n * Returns true if this instance and its entire DataType\n * array list is a subset of the argument. This class is a subset if it is\n * the same class as the argument.\n *\n * @param obj datatype to determine subset of\n * @return true if this instance and its entire datatype array list is a\n * subset of the argument.\n */\n public boolean isSubsetOf(Object obj)\n {\n if (!(obj instanceof AbstractTagFrameBody))\n {\n return false;\n }\n ArrayList<AbstractDataType> superset = ((AbstractTagFrameBody) obj).objectList;\n for (AbstractDataType anObjectList : objectList)\n {\n if (anObjectList.getValue() != null)\n {\n if (!superset.contains(anObjectList))\n {\n return false;\n }\n }\n }\n return true;\n }\n\n /**\n * Returns true if this datatype and its entire DataType array\n * list equals the argument. This datatype is equal to the argument if they\n * are the same class.\n *\n * @param obj datatype to determine equality of\n * @return true if this datatype and its entire <code>MP3Object</code> array\n * list equals the argument.\n */\n public boolean equals(Object obj)\n {\n if (!(obj instanceof AbstractTagFrameBody))\n {\n return false;\n }\n AbstractTagFrameBody object = (AbstractTagFrameBody) obj;\n boolean check =this.objectList.equals(object.objectList) && super.equals(obj);\n return check;\n }\n\n /**\n * Returns an iterator of the DataType list.\n *\n * @return iterator of the DataType list.\n */\n public Iterator iterator()\n {\n return objectList.iterator();\n }\n\n\n /**\n * Return brief description of FrameBody\n *\n * @return brief description of FrameBody\n */\n public String toString()\n {\n return getBriefDescription();\n }\n\n\n /**\n * Create the list of Datatypes that this body\n * expects in the correct order This method needs to be implemented by concrete subclasses\n */\n protected abstract void setupObjectList();\n\n /**\n * Get Reference to header\n *\n * @return\n */\n public AbstractTagFrame getHeader()\n {\n return header;\n }\n\n /**\n * Set header\n *\n * @param header\n */\n public void setHeader(AbstractTagFrame header)\n {\n this.header = header;\n }\n}"
},
{
"identifier": "EqualsUtil",
"path": "android/src/main/java/org/jaudiotagger/utils/EqualsUtil.java",
"snippet": "public final class EqualsUtil\n{\n\n static public boolean areEqual(boolean aThis, boolean aThat)\n {\n //System.out.println(\"boolean\");\n return aThis == aThat;\n }\n\n static public boolean areEqual(char aThis, char aThat)\n {\n //System.out.println(\"char\");\n return aThis == aThat;\n }\n\n static public boolean areEqual(long aThis, long aThat)\n {\n /*\n * Implementation Note\n * Note that byte, short, and int are handled by this method, through\n * implicit conversion.\n */\n //System.out.println(\"long\");\n return aThis == aThat;\n }\n\n static public boolean areEqual(float aThis, float aThat)\n {\n //System.out.println(\"float\");\n return Float.floatToIntBits(aThis) == Float.floatToIntBits(aThat);\n }\n\n static public boolean areEqual(double aThis, double aThat)\n {\n //System.out.println(\"double\");\n return Double.doubleToLongBits(aThis) == Double.doubleToLongBits(aThat);\n }\n\n /**\n * Possibly-null object field.\n *\n * Includes type-safe enumerations and collections, but does not include\n * arrays. See class comment.\n */\n static public boolean areEqual(Object aThis, Object aThat)\n {\n //System.out.println(\"Object\");\n return aThis == null ? aThat == null : aThis.equals(aThat);\n }\n}"
}
] | import org.jaudiotagger.tag.InvalidDataTypeException;
import org.jaudiotagger.tag.id3.AbstractTagFrameBody;
import org.jaudiotagger.utils.EqualsUtil;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level; | 2,865 | package org.jaudiotagger.tag.datatype;
/**
* Represents a data type that allow multiple Strings but they should be paired as key values, i.e should be 2,4,6..
* But keys are not unique so we don't store as a map, so could have same key pointing to two different values
* such as two ENGINEER keys
*
*/
public class PairedTextEncodedStringNullTerminated extends AbstractDataType
{ | package org.jaudiotagger.tag.datatype;
/**
* Represents a data type that allow multiple Strings but they should be paired as key values, i.e should be 2,4,6..
* But keys are not unique so we don't store as a map, so could have same key pointing to two different values
* such as two ENGINEER keys
*
*/
public class PairedTextEncodedStringNullTerminated extends AbstractDataType
{ | public PairedTextEncodedStringNullTerminated(String identifier, AbstractTagFrameBody frameBody) | 1 | 2023-12-11 05:58:19+00:00 | 4k |
Ender-Cube/Endercube | Parkour/src/main/java/net/endercube/Parkour/commands/LeaderboardCommand.java | [
{
"identifier": "ComponentUtils",
"path": "Common/src/main/java/net/endercube/Common/utils/ComponentUtils.java",
"snippet": "public final class ComponentUtils {\n\n private ComponentUtils() {\n //not called\n }\n\n private final static int CENTER_PX = 154;\n\n /**\n * Changes a number of milliseconds to the HH:mm:ss.SSS format\n *\n * @param milliseconds The number of milliseconds\n * @return HH:mm:ss.SSS formatted String\n */\n public static String toHumanReadableTime(long milliseconds) {\n Date date = new Date(milliseconds);\n\n // formatter\n SimpleDateFormat formatter = new SimpleDateFormat(\"H:m:s.SSS\");\n formatter.setTimeZone(TimeZone.getTimeZone(\"UTC\"));\n\n return yeet0s(formatter.format(date)) + \"s\";\n\n }\n\n private static String yeet0s(String input) {\n String[] outString = input.split(\"\\\\b0:(?=\\\\d)\");\n\n return outString[outString.length - 1];\n }\n\n /**\n * Centers a component\n *\n * @param component The component to be centered\n * @return The component prefixed with spaces\n */\n // Yes, I know it is very scuffed\n public static @NotNull Component centerComponent(final @NotNull Component component) {\n return Component.text(spacePrefix(LegacyComponentSerializer.legacySection().serialize(component)))\n .append(component);\n }\n\n public static @NotNull String spacePrefix(final @NotNull String legacyTextMessage) {\n return spacePrefix(measureLegacyText(legacyTextMessage));\n }\n\n private static int measureLegacyText(final @NotNull String legacyTextMessage) {\n int messagePxSize = 0;\n boolean previousCode = false;\n boolean isBold = false;\n\n for (final char c : legacyTextMessage.toCharArray()) {\n if (c == '§') {\n previousCode = true;\n } else if (previousCode) {\n previousCode = false;\n isBold = c == 'l' || c == 'L';\n } else {\n final DefaultFontInfo info = DefaultFontInfo.forCharacter(c);\n messagePxSize += info.length(isBold);\n messagePxSize++;\n }\n }\n return messagePxSize;\n }\n\n private static @NotNull String spacePrefix(final int messagePxSize) {\n final int halvedMessageSize = messagePxSize / 2;\n final int toCompensate = CENTER_PX - halvedMessageSize;\n final int spaceLength = DefaultFontInfo.SPACE.length() + 1;\n int compensated = 0;\n StringBuilder sb = new StringBuilder();\n while (compensated < toCompensate) {\n sb.append(\" \");\n compensated += spaceLength;\n }\n return sb.toString();\n }\n\n\n public enum DefaultFontInfo {\n A('A', 5),\n a('a', 5),\n B('B', 5),\n b('b', 5),\n C('C', 5),\n c('c', 5),\n D('D', 5),\n d('d', 5),\n E('E', 5),\n e('e', 5),\n F('F', 5),\n f('f', 4),\n G('G', 5),\n g('g', 5),\n H('H', 5),\n h('h', 5),\n I('I', 3),\n i('i', 1),\n J('J', 5),\n j('j', 5),\n K('K', 5),\n k('k', 4),\n L('L', 5),\n l('l', 1),\n M('M', 5),\n m('m', 5),\n N('N', 5),\n n('n', 5),\n O('O', 5),\n o('o', 5),\n P('P', 5),\n p('p', 5),\n Q('Q', 5),\n q('q', 5),\n R('R', 5),\n r('r', 5),\n S('S', 5),\n s('s', 5),\n T('T', 5),\n t('t', 4),\n U('U', 5),\n u('u', 5),\n V('V', 5),\n v('v', 5),\n W('W', 5),\n w('w', 5),\n X('X', 5),\n x('x', 5),\n Y('Y', 5),\n y('y', 5),\n Z('Z', 5),\n z('z', 5),\n NUM_1('1', 5),\n NUM_2('2', 5),\n NUM_3('3', 5),\n NUM_4('4', 5),\n NUM_5('5', 5),\n NUM_6('6', 5),\n NUM_7('7', 5),\n NUM_8('8', 5),\n NUM_9('9', 5),\n NUM_0('0', 5),\n EXCLAMATION_POINT('!', 1),\n AT_SYMBOL('@', 6),\n NUM_SIGN('#', 5),\n DOLLAR_SIGN('$', 5),\n PERCENT('%', 5),\n UP_ARROW('^', 5),\n AMPERSAND('&', 5),\n ASTERISK('*', 5),\n LEFT_PARENTHESIS('(', 4),\n RIGHT_PERENTHESIS(')', 4),\n MINUS('-', 5),\n UNDERSCORE('_', 5),\n PLUS_SIGN('+', 5),\n EQUALS_SIGN('=', 5),\n LEFT_CURL_BRACE('{', 4),\n RIGHT_CURL_BRACE('}', 4),\n LEFT_BRACKET('[', 3),\n RIGHT_BRACKET(']', 3),\n COLON(':', 1),\n SEMI_COLON(';', 1),\n DOUBLE_QUOTE('\"', 3),\n SINGLE_QUOTE('\\'', 1),\n LEFT_ARROW('<', 4),\n RIGHT_ARROW('>', 4),\n QUESTION_MARK('?', 5),\n SLASH('/', 5),\n BACK_SLASH('\\\\', 5),\n LINE('|', 1),\n TILDE('~', 5),\n TICK('`', 2),\n PERIOD('.', 1),\n COMMA(',', 1),\n SPACE(' ', 3),\n DEFAULT('a', 4);\n\n private final char character;\n private final int length;\n\n DefaultFontInfo(char character, int length) {\n this.character = character;\n this.length = length;\n }\n\n public static DefaultFontInfo forCharacter(char c) {\n for (DefaultFontInfo dFI : DefaultFontInfo.values()) {\n if (dFI.character() == c) {\n return dFI;\n }\n }\n return DefaultFontInfo.DEFAULT;\n }\n\n public char character() {\n return this.character;\n }\n\n public int length() {\n return this.length;\n }\n\n public int boldLength() {\n if (this == DefaultFontInfo.SPACE) {\n return this.length();\n }\n return this.length + 1;\n }\n\n public int length(final boolean bold) {\n return bold ? this.boldLength() : this.length();\n }\n }\n}"
},
{
"identifier": "logger",
"path": "Common/src/main/java/net/endercube/Common/EndercubeMinigame.java",
"snippet": "public static final Logger logger;"
},
{
"identifier": "database",
"path": "Parkour/src/main/java/net/endercube/Parkour/ParkourMinigame.java",
"snippet": "public static ParkourDatabase database;"
},
{
"identifier": "parkourMinigame",
"path": "Parkour/src/main/java/net/endercube/Parkour/ParkourMinigame.java",
"snippet": "public static ParkourMinigame parkourMinigame;"
}
] | import net.endercube.Common.utils.ComponentUtils;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.TextComponent;
import net.kyori.adventure.text.format.NamedTextColor;
import net.kyori.adventure.text.format.TextDecoration;
import net.kyori.adventure.text.minimessage.MiniMessage;
import net.minestom.server.command.builder.Command;
import net.minestom.server.command.builder.arguments.ArgumentType;
import net.minestom.server.instance.InstanceContainer;
import net.minestom.server.tag.Tag;
import redis.clients.jedis.resps.Tuple;
import java.util.ArrayList;
import java.util.List;
import static net.endercube.Common.EndercubeMinigame.logger;
import static net.endercube.Parkour.ParkourMinigame.database;
import static net.endercube.Parkour.ParkourMinigame.parkourMinigame; | 3,064 | package net.endercube.Parkour.commands;
public class LeaderboardCommand extends Command {
public LeaderboardCommand() {
super("leaderboard");
var mapArgument = ArgumentType.Word("mapArgument").from(getMaps());
// No map defined
setDefaultExecutor(((sender, context) -> {
sender.sendMessage(Component.text("[ERROR] You must specify a map").color(NamedTextColor.RED));
}));
// Non-existent map defined
mapArgument.setCallback(((sender, exception) -> {
final String input = exception.getInput();
sender.sendMessage(Component.text("[ERROR] The map " + input + " does not exist!").color(NamedTextColor.RED));
}));
// Actually execute command
addSyntax(((sender, context) -> {
final String map = context.get(mapArgument);
sender.sendMessage(createLeaderboard(map));
}), mapArgument);
}
/**
* Generates a leaderboard
* @param mapName The map
* @return A leaderboard or formatted text for an error if there is one
*/
private TextComponent createLeaderboard(String mapName) {
Component placementComponent = Component.text("");
// Get list of times from db
List<Tuple> leaderboardTuple = database.getLeaderboard(mapName, 9);
// Tell the player and the log that something went wrong if the database returns null
if (leaderboardTuple == null) {
logger.warn("The database call for leaderboards in parkour was null for some reason, continuing but something has gone wrong");
return Component.text("")
.append(Component.text("[ERROR] ")
.color(NamedTextColor.RED)
.decorate(TextDecoration.BOLD)
)
.append(Component.text("Something went wrong when reading the database. Please contact admins on the Endercube Discord")
.color(NamedTextColor.RED)
);
}
// Tell the player what happened if there are no times
if (leaderboardTuple.isEmpty()) {
return Component.text("")
.append(Component.text("No times exist for ").color(NamedTextColor.AQUA))
.append(Component.text(mapName).color(NamedTextColor.GOLD).decorate(TextDecoration.BOLD))
.append(Component.text(" yet! Why not set some?").color(NamedTextColor.AQUA));
}
// Add places 1-3
if (leaderboardTuple.size() >= 1) { // This is always true. Leaving it in to make this easier to read
placementComponent = placementComponent.append(leaderboardEntry("#FFD700",
leaderboardTuple.get(0).getElement(),
leaderboardTuple.get(0).getScore(),
1)
);
}
if (leaderboardTuple.size() >= 2) {
placementComponent = placementComponent.append(leaderboardEntry("#808080",
leaderboardTuple.get(1).getElement(),
leaderboardTuple.get(1).getScore(),
2)
);
}
if (leaderboardTuple.size() >= 3) {
placementComponent = placementComponent.append(leaderboardEntry("#CD7F32",
leaderboardTuple.get(2).getElement(),
leaderboardTuple.get(2).getScore(),
3)
).append(Component.newline());
}
// Add places 4-10
if (leaderboardTuple.size() >= 4) {
for (int i = 3; i < leaderboardTuple.size(); i++) {
placementComponent = placementComponent.append(leaderboardEntry("#AAAAAA",
leaderboardTuple.get(i).getElement(),
leaderboardTuple.get(i).getScore(),
i + 1)
);
}
}
return Component.text()
.append(ComponentUtils.centerComponent(MiniMessage.miniMessage().deserialize("<bold><gradient:#FF416C:#FF4B2B>All Time Leaderboard For " + mapName)))
.append(Component.newline())
.append(Component.newline())
.append(placementComponent)
.build();
}
private Component leaderboardEntry(String color, String player, double time, int placement) {
String placementToNameGap;
if (placement >= 10) {
placementToNameGap = " ";
} else {
placementToNameGap = " ";
}
return MiniMessage.miniMessage()
.deserialize("<" + color + ">#<bold>" + placement + placementToNameGap + player + "</bold> " + ComponentUtils.toHumanReadableTime((long) time))
.append(Component.newline());
}
private String[] getMaps() {
ArrayList<String> mapNames = new ArrayList<>();
| package net.endercube.Parkour.commands;
public class LeaderboardCommand extends Command {
public LeaderboardCommand() {
super("leaderboard");
var mapArgument = ArgumentType.Word("mapArgument").from(getMaps());
// No map defined
setDefaultExecutor(((sender, context) -> {
sender.sendMessage(Component.text("[ERROR] You must specify a map").color(NamedTextColor.RED));
}));
// Non-existent map defined
mapArgument.setCallback(((sender, exception) -> {
final String input = exception.getInput();
sender.sendMessage(Component.text("[ERROR] The map " + input + " does not exist!").color(NamedTextColor.RED));
}));
// Actually execute command
addSyntax(((sender, context) -> {
final String map = context.get(mapArgument);
sender.sendMessage(createLeaderboard(map));
}), mapArgument);
}
/**
* Generates a leaderboard
* @param mapName The map
* @return A leaderboard or formatted text for an error if there is one
*/
private TextComponent createLeaderboard(String mapName) {
Component placementComponent = Component.text("");
// Get list of times from db
List<Tuple> leaderboardTuple = database.getLeaderboard(mapName, 9);
// Tell the player and the log that something went wrong if the database returns null
if (leaderboardTuple == null) {
logger.warn("The database call for leaderboards in parkour was null for some reason, continuing but something has gone wrong");
return Component.text("")
.append(Component.text("[ERROR] ")
.color(NamedTextColor.RED)
.decorate(TextDecoration.BOLD)
)
.append(Component.text("Something went wrong when reading the database. Please contact admins on the Endercube Discord")
.color(NamedTextColor.RED)
);
}
// Tell the player what happened if there are no times
if (leaderboardTuple.isEmpty()) {
return Component.text("")
.append(Component.text("No times exist for ").color(NamedTextColor.AQUA))
.append(Component.text(mapName).color(NamedTextColor.GOLD).decorate(TextDecoration.BOLD))
.append(Component.text(" yet! Why not set some?").color(NamedTextColor.AQUA));
}
// Add places 1-3
if (leaderboardTuple.size() >= 1) { // This is always true. Leaving it in to make this easier to read
placementComponent = placementComponent.append(leaderboardEntry("#FFD700",
leaderboardTuple.get(0).getElement(),
leaderboardTuple.get(0).getScore(),
1)
);
}
if (leaderboardTuple.size() >= 2) {
placementComponent = placementComponent.append(leaderboardEntry("#808080",
leaderboardTuple.get(1).getElement(),
leaderboardTuple.get(1).getScore(),
2)
);
}
if (leaderboardTuple.size() >= 3) {
placementComponent = placementComponent.append(leaderboardEntry("#CD7F32",
leaderboardTuple.get(2).getElement(),
leaderboardTuple.get(2).getScore(),
3)
).append(Component.newline());
}
// Add places 4-10
if (leaderboardTuple.size() >= 4) {
for (int i = 3; i < leaderboardTuple.size(); i++) {
placementComponent = placementComponent.append(leaderboardEntry("#AAAAAA",
leaderboardTuple.get(i).getElement(),
leaderboardTuple.get(i).getScore(),
i + 1)
);
}
}
return Component.text()
.append(ComponentUtils.centerComponent(MiniMessage.miniMessage().deserialize("<bold><gradient:#FF416C:#FF4B2B>All Time Leaderboard For " + mapName)))
.append(Component.newline())
.append(Component.newline())
.append(placementComponent)
.build();
}
private Component leaderboardEntry(String color, String player, double time, int placement) {
String placementToNameGap;
if (placement >= 10) {
placementToNameGap = " ";
} else {
placementToNameGap = " ";
}
return MiniMessage.miniMessage()
.deserialize("<" + color + ">#<bold>" + placement + placementToNameGap + player + "</bold> " + ComponentUtils.toHumanReadableTime((long) time))
.append(Component.newline());
}
private String[] getMaps() {
ArrayList<String> mapNames = new ArrayList<>();
| for (InstanceContainer instance : parkourMinigame.getInstances()) { | 3 | 2023-12-10 12:08:18+00:00 | 4k |
lukebemishprojects/Tempest | common/src/main/java/dev/lukebemish/tempest/impl/mixin/LivingEntityMixin.java | [
{
"identifier": "Constants",
"path": "common/src/main/java/dev/lukebemish/tempest/impl/Constants.java",
"snippet": "public final class Constants {\n public static final String MOD_ID = \"tempest\";\n\n private static final ResourceLocation BASE = new ResourceLocation(MOD_ID, MOD_ID);\n public static final Gson GSON = new GsonBuilder().setLenient().create();\n public static final Logger LOGGER = LogManager.getLogger(MOD_ID);\n public static final TagKey<Block> FREEZES_UP = TagKey.create(Registries.BLOCK, id(\"freezes_up\"));\n public static final TagKey<Block> BREAKS_WITH_HAIL = TagKey.create(Registries.BLOCK, id(\"breaks_with_hail\"));\n public static final TagKey<Block> SAFE_WITH_HAIL = TagKey.create(Registries.BLOCK, id(\"safe_with_hail\"));\n public static final TagKey<Block> SNOW_PASSTHROUGH = TagKey.create(Registries.BLOCK, id(\"snow_passthrough\"));\n public static final TagKey<EntityType<?>> DAMAGED_BY_HAIL = TagKey.create(Registries.ENTITY_TYPE, id(\"damaged_by_hail\"));\n public static final TagKey<EntityType<?>> IMMUNE_TO_HAIL = TagKey.create(Registries.ENTITY_TYPE, id(\"damaged_by_hail\"));\n\n public static final ResourceKey<DamageType> HAIL_DAMAGE_TYPE = ResourceKey.create(Registries.DAMAGE_TYPE, id(\"hail\"));\n\n public static final ResourceLocation TEMPEST_WEATHER_CHECK = id(\"tempest_weather_check\");\n\n public static ResourceLocation id(String path) {\n return BASE.withPath(path);\n }\n\n private Constants() {}\n\n public static void bootstrap() {\n NoisyWeatherMap.register();\n\n Services.PLATFORM.register(() -> TempestWeatherCheck.TYPE, TEMPEST_WEATHER_CHECK, BuiltInRegistries.LOOT_CONDITION_TYPE);\n }\n}"
},
{
"identifier": "Services",
"path": "common/src/main/java/dev/lukebemish/tempest/impl/Services.java",
"snippet": "public final class Services {\n private Services() {}\n\n public static final Platform PLATFORM = load(Platform.class);\n\n private static final List<Snower> SNOWERS;\n private static final List<Melter> MELTERS;\n\n public static boolean snow(ServerLevel level, BlockPos pos, BlockState original) {\n for (var snower : SNOWERS) {\n if (snower.snow(level, pos, original)) {\n return true;\n }\n }\n return false;\n }\n\n public static boolean melt(ServerLevel level, BlockPos pos, BlockState original) {\n for (var melter : MELTERS) {\n if (melter.melt(level, pos, original)) {\n return true;\n }\n }\n return false;\n }\n\n public static <T> T load(Class<T> clazz) {\n return ServiceLoader.load(clazz)\n .findFirst()\n .orElseThrow(() -> new NullPointerException(\"Failed to load service for \" + clazz.getName()));\n }\n\n static {\n var melters = new ArrayList<Melter>();\n var snowers = new ArrayList<Snower>();\n for (var provider : ServiceLoader.load(CompatProvider.class)) {\n if (provider.shouldLoad()) {\n var compat = provider.compat();\n melters.add(new Melter() {\n boolean valid = true;\n\n @Override\n public boolean melt(ServerLevel level, BlockPos pos, BlockState original) {\n if (valid) {\n try {\n return compat.melt(level, pos, original);\n } catch (Throwable t) {\n valid = false;\n Constants.LOGGER.error(\"Failed to melt block at {} with provider {}\", pos, provider.getClass().getName(), t);\n }\n }\n return false;\n }\n });\n snowers.add(new Snower() {\n boolean valid = true;\n\n @Override\n public boolean snow(ServerLevel level, BlockPos pos, BlockState original) {\n if (valid) {\n try {\n return compat.snow(level, pos, original);\n } catch (Throwable t) {\n valid = false;\n Constants.LOGGER.error(\"Failed to snow block at {} with provider {}\", pos, provider.getClass().getName(), t);\n }\n }\n return false;\n }\n });\n }\n }\n MELTERS = List.copyOf(melters);\n SNOWERS = List.copyOf(snowers);\n }\n\n public interface Platform {\n WeatherChunkData getChunkData(LevelChunk chunk);\n <S, T extends S> Supplier<T> register(Supplier<T> supplier, ResourceLocation location, Registry<S> registry);\n\n boolean modLoaded(String modId);\n }\n\n @FunctionalInterface\n private interface Melter {\n boolean melt(ServerLevel level, BlockPos pos, BlockState original);\n }\n\n @FunctionalInterface\n private interface Snower {\n boolean snow(ServerLevel level, BlockPos pos, BlockState original);\n }\n\n public interface Compat {\n boolean melt(ServerLevel level, BlockPos pos, BlockState original);\n boolean snow(ServerLevel level, BlockPos pos, BlockState original);\n }\n\n public interface CompatProvider {\n Compat compat();\n\n boolean shouldLoad();\n }\n}"
},
{
"identifier": "WeatherCategory",
"path": "common/src/main/java/dev/lukebemish/tempest/impl/data/WeatherCategory.java",
"snippet": "public enum WeatherCategory {\n SNOW(new ResourceLocation(\"textures/environment/snow.png\"), false, 1.0f),\n RAIN(new ResourceLocation(\"textures/environment/rain.png\"), true, 0.2f),\n SLEET(Constants.id(\"textures/environment/sleet.png\"), true, 0.5f),\n HAIL(Constants.id(\"textures/environment/hail.png\"), true, 0.5f);\n\n public final ResourceLocation location;\n public final boolean fastFalling;\n private final float swirlMult;\n\n WeatherCategory(ResourceLocation location, boolean fastFalling, float swirlMult) {\n this.location = location;\n this.fastFalling = fastFalling;\n this.swirlMult = swirlMult;\n }\n\n public static class WeatherStatus {\n public final WeatherCategory category;\n public final float intensity;\n public final float swirl;\n public final float windX;\n public final float windZ;\n public final float speed;\n public final float thunder;\n\n public WeatherStatus(WeatherCategory category, float intensity, float windX, float windZ, float thunder) {\n this.category = category;\n float i = Mth.sqrt(intensity);\n this.intensity = 1 - (0.7f * (1 - i));\n this.speed = Mth.sqrt(windX * windX + windZ * windZ);\n this.swirl = (1 - speed * speed) * this.category.swirlMult;\n this.windX = windX / this.speed;\n this.windZ = windZ / this.speed;\n this.thunder = thunder;\n }\n }\n}"
}
] | import com.llamalad7.mixinextras.injector.wrapoperation.Operation;
import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation;
import dev.lukebemish.tempest.impl.Constants;
import dev.lukebemish.tempest.impl.Services;
import dev.lukebemish.tempest.impl.data.WeatherCategory;
import net.minecraft.core.BlockPos;
import net.minecraft.core.registries.Registries;
import net.minecraft.world.damagesource.DamageSource;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.levelgen.Heightmap;
import net.minecraft.world.phys.Vec3;
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.Slice;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; | 2,491 | package dev.lukebemish.tempest.impl.mixin;
@Mixin(LivingEntity.class)
public abstract class LivingEntityMixin extends Entity {
LivingEntityMixin(EntityType<? extends Entity> entityType, Level level) {
super(entityType, level);
}
@WrapOperation(
method = "travel(Lnet/minecraft/world/phys/Vec3;)V",
at = @At(
value = "INVOKE",
target = "Lnet/minecraft/world/entity/LivingEntity;setDeltaMovement(DDD)V"
),
slice = @Slice(
from = @At(
value = "INVOKE",
target = "Lnet/minecraft/world/entity/LivingEntity;handleRelativeFrictionAndCalculateMovement(Lnet/minecraft/world/phys/Vec3;F)Lnet/minecraft/world/phys/Vec3;"
)
)
)
private void tempest$wrapDeltaMovement(LivingEntity livingEntity, double dx, double dy, double dz, Operation<Void> operation) {
//noinspection DataFlowIssue
if (!((LivingEntity) (Object) this).shouldDiscardFriction()) {
if (this.onGround()) {
var pos = this.getBlockPosBelowThatAffectsMyMovement();
//noinspection resource
var weatherData = Services.PLATFORM.getChunkData(this.level().getChunkAt(pos)).query(pos);
int blackIce = weatherData.blackIce();
if (blackIce != 0) {
var unscaledDx = dx / 0.91f;
var unscaledDz = dz / 0.91f;
var degree = 1 - (blackIce / 15f);
degree = degree * degree;
var newDx = degree * dx + (1 - degree) * unscaledDx;
var newDz = degree * dz + (1 - degree) * unscaledDz;
operation.call(livingEntity, newDx, dy, newDz);
return;
}
}
}
operation.call(livingEntity, dx, dy, dz);
}
@SuppressWarnings("resource")
@Inject(
method = "baseTick()V",
at = @At("HEAD")
)
private void tempest$baseTick(CallbackInfo ci) {
if (this.isAlive()) {
var pos = BlockPos.containing(this.getX(), this.getEyeY(), this.getZ());
if (level().canSeeSky(pos) && level().getHeightmapPos(Heightmap.Types.MOTION_BLOCKING, pos).getY() <= pos.getY()){
var weatherData = Services.PLATFORM.getChunkData(this.level().getChunkAt(pos));
var status = weatherData.getWeatherStatusWindAware(pos);
if (!this.level().isClientSide()) {
if ((this.tickCount & 8) == 0 && status != null && status.category == WeatherCategory.HAIL) { | package dev.lukebemish.tempest.impl.mixin;
@Mixin(LivingEntity.class)
public abstract class LivingEntityMixin extends Entity {
LivingEntityMixin(EntityType<? extends Entity> entityType, Level level) {
super(entityType, level);
}
@WrapOperation(
method = "travel(Lnet/minecraft/world/phys/Vec3;)V",
at = @At(
value = "INVOKE",
target = "Lnet/minecraft/world/entity/LivingEntity;setDeltaMovement(DDD)V"
),
slice = @Slice(
from = @At(
value = "INVOKE",
target = "Lnet/minecraft/world/entity/LivingEntity;handleRelativeFrictionAndCalculateMovement(Lnet/minecraft/world/phys/Vec3;F)Lnet/minecraft/world/phys/Vec3;"
)
)
)
private void tempest$wrapDeltaMovement(LivingEntity livingEntity, double dx, double dy, double dz, Operation<Void> operation) {
//noinspection DataFlowIssue
if (!((LivingEntity) (Object) this).shouldDiscardFriction()) {
if (this.onGround()) {
var pos = this.getBlockPosBelowThatAffectsMyMovement();
//noinspection resource
var weatherData = Services.PLATFORM.getChunkData(this.level().getChunkAt(pos)).query(pos);
int blackIce = weatherData.blackIce();
if (blackIce != 0) {
var unscaledDx = dx / 0.91f;
var unscaledDz = dz / 0.91f;
var degree = 1 - (blackIce / 15f);
degree = degree * degree;
var newDx = degree * dx + (1 - degree) * unscaledDx;
var newDz = degree * dz + (1 - degree) * unscaledDz;
operation.call(livingEntity, newDx, dy, newDz);
return;
}
}
}
operation.call(livingEntity, dx, dy, dz);
}
@SuppressWarnings("resource")
@Inject(
method = "baseTick()V",
at = @At("HEAD")
)
private void tempest$baseTick(CallbackInfo ci) {
if (this.isAlive()) {
var pos = BlockPos.containing(this.getX(), this.getEyeY(), this.getZ());
if (level().canSeeSky(pos) && level().getHeightmapPos(Heightmap.Types.MOTION_BLOCKING, pos).getY() <= pos.getY()){
var weatherData = Services.PLATFORM.getChunkData(this.level().getChunkAt(pos));
var status = weatherData.getWeatherStatusWindAware(pos);
if (!this.level().isClientSide()) {
if ((this.tickCount & 8) == 0 && status != null && status.category == WeatherCategory.HAIL) { | var source = new DamageSource(this.level().registryAccess().registryOrThrow(Registries.DAMAGE_TYPE).getHolderOrThrow(Constants.HAIL_DAMAGE_TYPE)); | 0 | 2023-12-06 23:23:31+00:00 | 4k |
RennanMendes/healthnove-backend | src/main/java/com/healthnove/schedulingHealthNove/domain/service/AppointmentService.java | [
{
"identifier": "Status",
"path": "src/main/java/com/healthnove/schedulingHealthNove/domain/enumerated/Status.java",
"snippet": "public enum Status {\n SCHEDULED, CARRIED_OUT, CANCELED\n}"
},
{
"identifier": "UnscheduledAppointmentException",
"path": "src/main/java/com/healthnove/schedulingHealthNove/domain/exception/UnscheduledAppointmentException.java",
"snippet": "public class UnscheduledAppointmentException extends RuntimeException {\n\n public UnscheduledAppointmentException() {\n super(\"Consulta não agendada!\");\n }\n}"
},
{
"identifier": "Appointment",
"path": "src/main/java/com/healthnove/schedulingHealthNove/domain/model/Appointment.java",
"snippet": "@Entity\n@Table(name = \"tb_appointment\")\n@AllArgsConstructor\n@NoArgsConstructor\n@Getter\n@EqualsAndHashCode(of = \"id\")\npublic class Appointment {\n\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private Long id;\n\n @Column(name = \"appointment_date\")\n private LocalDateTime date;\n\n @Enumerated(EnumType.STRING)\n private Status status;\n\n @ManyToOne\n @JoinColumn(name = \"id_doctor\")\n private Doctor doctor;\n\n @ManyToOne\n @JoinColumn(name = \"id_user\")\n private User user;\n\n public Appointment(LocalDateTime date, User user, Doctor doctor) {\n this.date = date;\n this.doctor = doctor;\n this.user = user;\n this.status = Status.SCHEDULED;\n }\n\n public void setStatus(Status status) {\n this.status = status;\n }\n}"
},
{
"identifier": "Doctor",
"path": "src/main/java/com/healthnove/schedulingHealthNove/domain/model/Doctor.java",
"snippet": "@Entity\n@Table(name = \"tb_doctor\")\n@AllArgsConstructor\n@NoArgsConstructor\n@Getter\n@EqualsAndHashCode(of = \"id\")\npublic class Doctor {\n\n @Id\n private Long id;\n\n @Column(unique = true)\n private String crm;\n\n @Enumerated(EnumType.STRING)\n private Speciality speciality;\n private boolean active;\n\n @OneToOne\n @JoinColumn(name = \"id_user\")\n private User user;\n\n public Doctor(User user, DoctorRequestDto requestDto) {\n this.id = user.getId();\n this.crm = requestDto.crm();\n this.speciality = requestDto.speciality();\n this.active = true;\n this.user = user;\n }\n\n public void setSpeciality(Speciality speciality) {\n this.speciality = speciality;\n }\n\n public void setActive(boolean active) {\n this.active = active;\n }\n\n}"
},
{
"identifier": "User",
"path": "src/main/java/com/healthnove/schedulingHealthNove/domain/model/User.java",
"snippet": "@Entity\n@Table(name = \"tb_user\")\n@Getter\n@NoArgsConstructor\n@AllArgsConstructor\n@EqualsAndHashCode(of = \"id\")\npublic class User implements UserDetails {\n\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private Long id;\n private String firstName;\n private String lastName;\n\n @Column(unique = true)\n private String cpf;\n private String phone;\n private Date birthDate;\n\n @Enumerated(EnumType.STRING)\n private Gender gender;\n\n @Column(unique = true)\n private String email;\n private String password;\n\n @Enumerated(EnumType.STRING)\n private UserType userType;\n private boolean active;\n\n public User(UserRequestDto userData) {\n this.firstName = userData.name();\n this.lastName = userData.lastName();\n this.cpf = userData.cpf();\n this.phone = userData.phone();\n this.birthDate = userData.birthDate();\n this.gender = userData.gender();\n this.email = userData.email();\n this.password = userData.password();\n\n this.userType = UserType.PATIENT;\n this.active = true;\n }\n\n public void update(UserUpdateDto userData) {\n this.firstName = userData.firstName();\n this.lastName = userData.lastName();\n this.phone = userData.phone();\n this.email = userData.email();\n }\n\n public void setUserType(UserType userType) {\n this.userType = userType;\n }\n\n public void delete() {\n this.active = false;\n }\n\n @Override\n public Collection<? extends GrantedAuthority> getAuthorities() {\n return List.of(new SimpleGrantedAuthority(\"ROLE_USER\"));\n }\n\n @Override\n public String getUsername() {\n return email;\n }\n\n @Override\n public boolean isAccountNonExpired() {\n return true;\n }\n\n @Override\n public boolean isAccountNonLocked() {\n return true;\n }\n\n @Override\n public boolean isCredentialsNonExpired() {\n return true;\n }\n\n @Override\n public boolean isEnabled() {\n return true;\n }\n\n public void setPassword(String password) {\n this.password = password;\n }\n}"
},
{
"identifier": "AppointmentRepository",
"path": "src/main/java/com/healthnove/schedulingHealthNove/domain/repository/AppointmentRepository.java",
"snippet": "public interface AppointmentRepository extends JpaRepository<Appointment, Long> {\n\n Optional<Appointment> findByIdAndStatus(Long id, Status status);\n\n List<Appointment> findByUserIdAndStatus(Long id, Status status);\n\n List<Appointment> findByDoctorIdAndStatus(Long id, Status status);\n\n @Query(\"SELECT EXISTS (SELECT 1 FROM Appointment a WHERE a.doctor.id = :id AND a.date = :date AND a.status = 'SCHEDULED')\")\n boolean existsByDoctorIdAndDate(@Param(\"id\") Long id, @Param(\"date\") LocalDateTime date);\n\n @Query(\"SELECT EXISTS (SELECT 1 FROM Appointment a WHERE a.user.id = :userId AND a.status = SCHEDULED AND a.date BETWEEN :firstHour AND :lastHour)\")\n boolean existsByUserIdAndDateBetween(@Param(\"userId\") Long userId, @Param(\"firstHour\") LocalDateTime firstHour, @Param(\"lastHour\") LocalDateTime lastHour);\n\n}"
}
] | import com.healthnove.schedulingHealthNove.domain.dto.appointment.AppointmentRequestDto;
import com.healthnove.schedulingHealthNove.domain.dto.appointment.AppointmentResponseDto;
import com.healthnove.schedulingHealthNove.domain.enumerated.Status;
import com.healthnove.schedulingHealthNove.domain.exception.UnscheduledAppointmentException;
import com.healthnove.schedulingHealthNove.domain.model.Appointment;
import com.healthnove.schedulingHealthNove.domain.model.Doctor;
import com.healthnove.schedulingHealthNove.domain.model.User;
import com.healthnove.schedulingHealthNove.domain.repository.AppointmentRepository;
import com.healthnove.schedulingHealthNove.domain.validations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.stream.Stream; | 1,954 | package com.healthnove.schedulingHealthNove.domain.service;
@Service
public class AppointmentService {
private final UserService userService;
private final DoctorService doctorService;
private final AppointmentRepository repository;
private final List<AppointmentSchedulingValidator> validators;
@Autowired
public AppointmentService(UserService userService, DoctorService doctorService, AppointmentRepository repository, List<AppointmentSchedulingValidator> validators) {
this.userService = userService;
this.doctorService = doctorService;
this.repository = repository;
this.validators = validators;
}
public AppointmentResponseDto findAppointmentById(Long id) {
return new AppointmentResponseDto(this.findById(id));
}
public Stream<AppointmentResponseDto> findByUserId(Long id) {
List<Appointment> appointments = repository.findByUserIdAndStatus(id, Status.SCHEDULED);
return appointments.stream().map(AppointmentResponseDto::new);
}
public Stream<AppointmentResponseDto> findByDoctorId(Long id) {
List<Appointment> appointments = repository.findByDoctorIdAndStatus(id, Status.SCHEDULED);
return appointments.stream().map(AppointmentResponseDto::new);
}
public AppointmentResponseDto scheduleAppointment(AppointmentRequestDto requestDto) {
validators.forEach(v -> v.validate(requestDto));
User user = userService.findByIdAndActiveTrue(requestDto.userId());
Doctor doctor = doctorService.findDoctorById(requestDto.doctorId());
Appointment appointment = new Appointment(requestDto.appointmentDate(), user, doctor);
return new AppointmentResponseDto(repository.save(appointment));
}
@Transactional
public void cancelAppointment(Long id) {
Appointment appointment = this.findById(id);
appointment.setStatus(Status.CANCELED);
}
private Appointment findById(Long id) { | package com.healthnove.schedulingHealthNove.domain.service;
@Service
public class AppointmentService {
private final UserService userService;
private final DoctorService doctorService;
private final AppointmentRepository repository;
private final List<AppointmentSchedulingValidator> validators;
@Autowired
public AppointmentService(UserService userService, DoctorService doctorService, AppointmentRepository repository, List<AppointmentSchedulingValidator> validators) {
this.userService = userService;
this.doctorService = doctorService;
this.repository = repository;
this.validators = validators;
}
public AppointmentResponseDto findAppointmentById(Long id) {
return new AppointmentResponseDto(this.findById(id));
}
public Stream<AppointmentResponseDto> findByUserId(Long id) {
List<Appointment> appointments = repository.findByUserIdAndStatus(id, Status.SCHEDULED);
return appointments.stream().map(AppointmentResponseDto::new);
}
public Stream<AppointmentResponseDto> findByDoctorId(Long id) {
List<Appointment> appointments = repository.findByDoctorIdAndStatus(id, Status.SCHEDULED);
return appointments.stream().map(AppointmentResponseDto::new);
}
public AppointmentResponseDto scheduleAppointment(AppointmentRequestDto requestDto) {
validators.forEach(v -> v.validate(requestDto));
User user = userService.findByIdAndActiveTrue(requestDto.userId());
Doctor doctor = doctorService.findDoctorById(requestDto.doctorId());
Appointment appointment = new Appointment(requestDto.appointmentDate(), user, doctor);
return new AppointmentResponseDto(repository.save(appointment));
}
@Transactional
public void cancelAppointment(Long id) {
Appointment appointment = this.findById(id);
appointment.setStatus(Status.CANCELED);
}
private Appointment findById(Long id) { | return repository.findByIdAndStatus(id, Status.SCHEDULED).orElseThrow(UnscheduledAppointmentException::new); | 1 | 2023-12-14 21:54:29+00:00 | 4k |
xhtcode/xht-cloud-parent | xht-cloud-system/xht-cloud-system-service/src/main/java/com/xht/cloud/system/module/dict/controller/SysDictController.java | [
{
"identifier": "R",
"path": "xht-cloud-framework/xht-cloud-framework-core/src/main/java/com/xht/cloud/framework/core/api/R.java",
"snippet": "@Getter\n@Schema(description = \"返回值Body体\")\n@JsonPropertyOrder(value = {\"code\", \"msg\", \"data\"})\npublic class R<T> implements Serializable {\n\n @Serial\n private static final long serialVersionUID = 1L;\n\n /**\n * 状态码\n */\n @JsonProperty(\"code\")\n @Schema(description = \"状态码\")\n private Integer code;\n\n /**\n * 响应描述\n */\n @JsonProperty(\"msg\")\n @Schema(description = \"响应描述\")\n private String msg;\n\n /**\n * 响应数据\n */\n @JsonProperty(\"data\")\n @Schema(description = \"响应数据\")\n private T data;\n\n public static <T> R<T> ok() {\n return restResult(ApiConstants.SUCCESS, ApiConstants.SUCCESS_MSG, null);\n }\n\n public static <T> R<T> ok(T data) {\n return restResult(ApiConstants.SUCCESS, ApiConstants.SUCCESS_MSG, data);\n }\n\n public static <T> R<T> ok(String msg, T data) {\n return restResult(ApiConstants.SUCCESS, msg, data);\n }\n\n public static <T> R<T> failed() {\n return failed(GlobalErrorStatusCode.INTERNAL_SERVER_ERROR);\n }\n\n public static <T> R<T> failed(String msg) {\n return restResult(ApiConstants.FAIL, msg, null);\n }\n\n public static <T> R<T> failed(Integer code, String msg) {\n return restResult(code, msg, null);\n }\n\n public static <T> R<T> failed(IErrorStatusCode status) {\n return restResult(status.code(), status.desc(), null);\n }\n\n public static <T> R<T> failed(IErrorStatusCode status, T data) {\n return restResult(status.code(), status.desc(), data);\n }\n\n\n public static <T> R<T> restResult(Integer code, String msg, T data) {\n R<T> apiResult = new R<>();\n apiResult.setCode(code);\n apiResult.setData(data);\n apiResult.setMsg(msg);\n return apiResult;\n }\n\n public R<T> setCode(Integer code) {\n this.code = code;\n return this;\n }\n\n public R<T> setMsg(String msg) {\n this.msg = msg;\n return this;\n }\n\n public R<T> setData(T data) {\n this.data = data;\n return this;\n }\n}"
},
{
"identifier": "PageResponse",
"path": "xht-cloud-framework/xht-cloud-framework-core/src/main/java/com/xht/cloud/framework/core/api/response/PageResponse.java",
"snippet": "@Data\n@Schema(description = \"分页信息响应实体\")\npublic class PageResponse<T> extends Response {\n\n /**\n * 当前页\n */\n @Schema(description = \"当前页\")\n private long current;\n\n /**\n * 每页显示条数\n */\n @Schema(description = \"每页显示条数\")\n private long size;\n\n /**\n * 总页数\n */\n @Schema(description = \"总页数\")\n private long pages;\n\n /**\n * 总条目数\n */\n @Schema(description = \"总条目数\")\n private long total;\n\n /**\n * 结果集\n */\n @Schema(description = \"结果集\")\n private List<T> list;\n\n}"
},
{
"identifier": "Create",
"path": "xht-cloud-framework/xht-cloud-spring-boot-start-web/src/main/java/com/xht/cloud/framework/web/validation/group/Create.java",
"snippet": "public interface Create {\n}"
},
{
"identifier": "Update",
"path": "xht-cloud-framework/xht-cloud-spring-boot-start-web/src/main/java/com/xht/cloud/framework/web/validation/group/Update.java",
"snippet": "public interface Update {\n}"
},
{
"identifier": "SysDictAddRequest",
"path": "xht-cloud-system/xht-cloud-system-service/src/main/java/com/xht/cloud/system/module/dict/controller/request/SysDictAddRequest.java",
"snippet": "@Data\n@Schema(name = \"SysDictRequest(字典-增加请求信息)\", description = \"字典-增加请求信息\")\npublic class SysDictAddRequest extends SysDictRequest {\n\n}"
},
{
"identifier": "SysDictQueryRequest",
"path": "xht-cloud-system/xht-cloud-system-service/src/main/java/com/xht/cloud/system/module/dict/controller/request/SysDictQueryRequest.java",
"snippet": "@Data\n@Schema(name = \"SysDictRequest(字典-查询请求信息)\", description = \"字典-查询请求信息\")\npublic class SysDictQueryRequest extends SysDictRequest {\n\n}"
},
{
"identifier": "SysDictUpdateRequest",
"path": "xht-cloud-system/xht-cloud-system-service/src/main/java/com/xht/cloud/system/module/dict/controller/request/SysDictUpdateRequest.java",
"snippet": "@Data\n@Schema(name = \"SysDictRequest(字典-修改请求信息)\", description = \"字典-修改请求信息\")\npublic class SysDictUpdateRequest extends SysDictRequest {\n\n /**\n * Id\n */\n @Schema(description = \"Id\")\n @NotBlank(message = \"Id `id` 不能为空\", groups = {Create.class, Update.class})\n private String id;\n\n}"
},
{
"identifier": "SysDictResponse",
"path": "xht-cloud-system/xht-cloud-system-service/src/main/java/com/xht/cloud/system/module/dict/controller/response/SysDictResponse.java",
"snippet": "@Data\n@Schema(name = \"SysDictResponse(字典-响应信息)\", description = \"字典\")\npublic class SysDictResponse extends Response {\n\n /**\n * Id\n */\n @Schema(description = \"Id\")\n private String id;\n\n /**\n * 字典编码\n */\n @Schema(description = \"字典编码\")\n private String dictCode;\n\n /**\n * 字典值\n */\n @Schema(description = \"字典值\")\n private String dictValue;\n\n /**\n * 状态(0未启用1已经启用)\n */\n @Schema(description = \"状态(0未启用1已经启用)\")\n private String dictStatus;\n\n /**\n * 备注\n */\n @Schema(description = \"备注\")\n private String description;\n\n /**\n * 排序\n */\n @Schema(description = \"排序\")\n private Integer sortOrder;\n\n}"
},
{
"identifier": "SysDictVo",
"path": "xht-cloud-system/xht-cloud-system-service/src/main/java/com/xht/cloud/system/module/dict/controller/response/SysDictVo.java",
"snippet": "@Data\npublic class SysDictVo extends SysDictResponse {\n\n private List<SysDictItemResponse> children;\n\n}"
},
{
"identifier": "ISysDictService",
"path": "xht-cloud-system/xht-cloud-system-service/src/main/java/com/xht/cloud/system/module/dict/service/ISysDictService.java",
"snippet": "public interface ISysDictService {\n\n /**\n * 创建\n *\n * @param addRequest {@link SysDictAddRequest}\n * @return {@link String} 主键\n */\n String create(SysDictAddRequest addRequest);\n\n /**\n * 根据id修改\n *\n * @param updateRequest {@link SysDictUpdateRequest}\n */\n void update(SysDictUpdateRequest updateRequest);\n\n /**\n * 删除\n *\n * @param ids {@link List<String>} id集合\n */\n void remove(List<String> ids);\n\n /**\n * 根据id查询详细\n *\n * @param id {@link String} 数据库主键\n * @return {@link SysDictResponse}\n */\n SysDictResponse findById(String id);\n\n /**\n * 根据字典id 和字典状态查询详细\n * @param id 字典id\n * @return 状态正常的\n */\n default SysDictResponse findByIdStatus(String id) {\n SysDictResponse dictResponse = findById(id);\n if (Objects.nonNull(dictResponse) && Objects.equals(CommonStatus.DICT_STATUS_SUCCESS, dictResponse.getDictStatus())) {\n return dictResponse;\n }\n return null;\n }\n\n /**\n * 分页查询\n *\n * @param queryRequest {@link SysDictQueryRequest}\n * @return {@link PageResponse<SysDictResponse>} 分页详情\n */\n PageResponse<SysDictResponse> findPage(SysDictQueryRequest queryRequest);\n\n /**\n * 根据字典编码 dictCode 判断是否存在\n * 当有id的时候是不包括自己\n * @param dictCode {@link String} 字典编码\n * @param id {@link String} 字典id\n * @return {@link Boolean} true 存在 false不存在\n */\n boolean existByCode(String dictCode, String id);\n\n /**\n * 根据dictCode 字典编码查询详细\n *\n * @param dictCode {@link String} 字典编码\n * @return {@link SysDictVo}\n */\n SysDictVo findByCode(String dictCode);\n\n\n /**\n * 根据 字典编码 dictCode查询详细\n *\n * @param dictCode {@link String} 字典编码\n * @return {@link List<SysDictItemResponse>}\n */\n default List<SysDictItemResponse> findItemByCode(String dictCode) {\n SysDictVo byCode = findByCode(dictCode);\n if (Objects.nonNull(byCode)) {\n return byCode.getChildren();\n }\n return Collections.emptyList();\n }\n\n}"
},
{
"identifier": "ok",
"path": "xht-cloud-framework/xht-cloud-framework-core/src/main/java/com/xht/cloud/framework/core/api/R.java",
"snippet": "public static <T> R<T> ok() {\n return restResult(ApiConstants.SUCCESS, ApiConstants.SUCCESS_MSG, null);\n}"
}
] | import com.xht.cloud.framework.core.api.R;
import com.xht.cloud.framework.core.api.response.PageResponse;
import com.xht.cloud.framework.safety.repeat.annotation.RepeatSubmitLimit;
import com.xht.cloud.framework.web.validation.group.Create;
import com.xht.cloud.framework.web.validation.group.Update;
import com.xht.cloud.system.module.dict.controller.request.SysDictAddRequest;
import com.xht.cloud.system.module.dict.controller.request.SysDictQueryRequest;
import com.xht.cloud.system.module.dict.controller.request.SysDictUpdateRequest;
import com.xht.cloud.system.module.dict.controller.response.SysDictResponse;
import com.xht.cloud.system.module.dict.controller.response.SysDictVo;
import com.xht.cloud.system.module.dict.service.ISysDictService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import static com.xht.cloud.framework.core.api.R.ok; | 2,950 | package com.xht.cloud.system.module.dict.controller;
/**
* 描述 :字典
*
* @author : xht
**/
@Slf4j
@RestController
@RequestMapping("/sys/dict")
@RequiredArgsConstructor
@Tag(name = "字典")
public class SysDictController {
private final ISysDictService sysDictService;
/**
* 创建
*
* @param addRequest {@link SysDictAddRequest}
* @return {@link Boolean} true成功 false失败
*/
@Operation(summary = "创建-字典")
@PostMapping
@RepeatSubmitLimit
@PreAuthorize("@oauth2.hasAnyAuthority('sys:dict:add')")
public R<Boolean> create(@Validated(Create.class) @RequestBody SysDictAddRequest addRequest) {
sysDictService.create(addRequest);
return ok(true);
}
/**
* 根据id修改
*
* @param updateRequest {@link SysDictUpdateRequest}
* @return {@link Boolean} true成功 false失败
*/
@Operation(summary = "根据id修改-字典")
@PutMapping
@RepeatSubmitLimit
@PreAuthorize("@oauth2.hasAnyAuthority('sys:dict:edit')") | package com.xht.cloud.system.module.dict.controller;
/**
* 描述 :字典
*
* @author : xht
**/
@Slf4j
@RestController
@RequestMapping("/sys/dict")
@RequiredArgsConstructor
@Tag(name = "字典")
public class SysDictController {
private final ISysDictService sysDictService;
/**
* 创建
*
* @param addRequest {@link SysDictAddRequest}
* @return {@link Boolean} true成功 false失败
*/
@Operation(summary = "创建-字典")
@PostMapping
@RepeatSubmitLimit
@PreAuthorize("@oauth2.hasAnyAuthority('sys:dict:add')")
public R<Boolean> create(@Validated(Create.class) @RequestBody SysDictAddRequest addRequest) {
sysDictService.create(addRequest);
return ok(true);
}
/**
* 根据id修改
*
* @param updateRequest {@link SysDictUpdateRequest}
* @return {@link Boolean} true成功 false失败
*/
@Operation(summary = "根据id修改-字典")
@PutMapping
@RepeatSubmitLimit
@PreAuthorize("@oauth2.hasAnyAuthority('sys:dict:edit')") | public R<Boolean> update(@Validated(Update.class) @RequestBody SysDictUpdateRequest updateRequest) { | 6 | 2023-12-12 08:16:30+00:00 | 4k |
Utils4J/JavaUtils | src/main/java/de/mineking/javautils/database/TypeMapper.java | [
{
"identifier": "ID",
"path": "src/main/java/de/mineking/javautils/ID.java",
"snippet": "public class ID {\n\tprivate final static Base62 base62 = Base62.createInstance();\n\tpublic final static int size = Long.BYTES + Byte.BYTES; //Timestamp + Serial\n\n\tprivate static long lastTime = 0;\n\tprivate static byte serial;\n\n\t@NotNull\n\tprivate static String toString(@NotNull byte[] bytes) {\n\t\treturn new String(base62.encode(bytes), StandardCharsets.UTF_8);\n\t}\n\n\t@NotNull\n\tprivate static byte[] fromString(@NotNull String str) {\n\t\treturn base62.decode(str.getBytes(StandardCharsets.UTF_8));\n\t}\n\n\t@NotNull\n\tpublic synchronized static ID generate() {\n\t\tvar time = System.currentTimeMillis();\n\t\tvar buffer = ByteBuffer.allocate(size);\n\n\t\tif(time > lastTime) serial = Byte.MIN_VALUE;\n\t\telse if(serial == Byte.MAX_VALUE) {\n\t\t\tserial = Byte.MIN_VALUE;\n\t\t\ttime++;\n\t\t}\n\n\t\tbuffer.putLong(time);\n\t\tbuffer.put(serial++);\n\n\t\tlastTime = time;\n\n\t\treturn new ID(buffer.array());\n\t}\n\n\t@NotNull\n\tpublic static ID decode(@NotNull String id) {\n\t\treturn new ID(fromString(id));\n\t}\n\n\t@NotNull\n\tpublic static ID decode(@NotNull BigInteger id) {\n\t\treturn new ID(id.toByteArray());\n\t}\n\n\t@NotNull\n\tpublic static ID decode(@NotNull byte[] data) {\n\t\treturn new ID(data);\n\t}\n\n\tprivate final byte[] data;\n\n\tID(byte[] data) {\n\t\tthis.data = data;\n\t}\n\n\t@NotNull\n\tpublic String asString() {\n\t\treturn toString(data);\n\t}\n\n\t@NotNull\n\tpublic BigInteger asNumber() {\n\t\treturn new BigInteger(data);\n\t}\n\n\t@NotNull\n\tpublic ByteBuffer bytes() {\n\t\treturn ByteBuffer.wrap(data);\n\t}\n\n\tpublic Instant getTimeCreated() {\n\t\treturn Instant.ofEpochMilli(bytes().getLong());\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn asString();\n\t}\n}"
},
{
"identifier": "DataType",
"path": "src/main/java/de/mineking/javautils/database/type/DataType.java",
"snippet": "public interface DataType {\n\t@NotNull\n\tstatic DataType ofName(@NotNull String name) {\n\t\treturn new DataType() {\n\t\t\t@NotNull\n\t\t\t@Override\n\t\t\tpublic String getName() {\n\t\t\t\treturn name;\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic String toString() {\n\t\t\t\treturn name;\n\t\t\t}\n\t\t};\n\t}\n\n\t@NotNull\n\tString getName();\n}"
},
{
"identifier": "PostgresType",
"path": "src/main/java/de/mineking/javautils/database/type/PostgresType.java",
"snippet": "public enum PostgresType implements DataType {\n\n\t/**\n\t * signed eight-byte integer\n\t */\n\tBIG_INT(\"bigint\"),\n\t/**\n\t * autoincrementing eight-byte integer\n\t */\n\tBIG_SERIAL(\"bigserial\"),\n\t/**\n\t * fixed-length bit string\n\t */\n\tBIT(\"bit\"),\n\t/**\n\t * variable-length bit string\n\t */\n\tVAR_BIT(\"varbit\"),\n\t/**\n\t * logical Boolean (true/false)\n\t */\n\tBOOLEAN(\"boolean\"),\n\t/**\n\t * rectangular box on a plane\n\t */\n\tBOX(\"box\"),\n\t/**\n\t * binary data (“byte array”)\n\t */\n\tBYTE_ARRAY(\"bytea\"),\n\t/**\n\t * fixed-length character string\n\t */\n\tCHARACTER(\"character\"),\n\t/**\n\t * variable-length character string\n\t */\n\tVAR_CHAR(\"varchar\"),\n\t/**\n\t * IPv4 or IPv6 network address\n\t */\n\tCIDR(\"cidr\"),\n\t/**\n\t * circle on a plane\n\t */\n\tCIRCLE(\"circle\"),\n\t/**\n\t * calendar date (year, month, day)\n\t */\n\tDATE(\"date\"),\n\t/**\n\t * double precision floating-point number (8 bytes)\n\t */\n\tDOUBLE_PRECISION(\"float8\"),\n\t/**\n\t * IPv4 or IPv6 host address\n\t */\n\tINET(\"inet\"),\n\t/**\n\t * signed four-byte integer\n\t */\n\tINTEGER(\"integer\"),\n\t/**\n\t * time span\n\t */\n\tINTERVAL(\"interval\"),\n\t/**\n\t * textual JSON data\n\t */\n\tJSON(\"json\"),\n\t/**\n\t * binary JSON data, decomposed\n\t */\n\tJSONB(\"jsonb\"),\n\t/**\n\t * infinite line on a plane\n\t */\n\tLINE(\"line\"),\n\t/**\n\t * line segment on a plane\n\t */\n\tLSEG(\"lseg\"),\n\t/**\n\t * MAC (Media Access Control) address\n\t */\n\tMAC_ADDR(\"macaddr\"),\n\t/**\n\t * MAC (Media Access Control) address (EUI-64 format)\n\t */\n\tMAC_ADDR_8(\"macaddr8\"),\n\t/**\n\t * currency amount\n\t */\n\tMONEY(\"money\"),\n\t/**\n\t * exact numeric of selectable precision\n\t */\n\tNUMERIC(\"numeric\"),\n\t/**\n\t * geometric path on a plane\n\t */\n\tPATH(\"path\"),\n\t/**\n\t * PostgreSQL Log Sequence Number\n\t */\n\tPG_LSN(\"pg_lsn\"),\n\t/**\n\t * user-level transaction ID snapshot\n\t */\n\tPG_SNAPSHOT(\"pg_snapshot\"),\n\t/**\n\t * geometric point on a plane\n\t */\n\tPOINT(\"point\"),\n\t/**\n\t * closed geometric path on a plane\n\t */\n\tPOLYGON(\"polygon\"),\n\t/**\n\t * single precision floating-point number (4 bytes)\n\t */\n\tREAL(\"real\"),\n\t/**\n\t * signed two-byte integer\n\t */\n\tSMALL_INT(\"smallint\"),\n\t/**\n\t * autoincrementing two-byte integer\n\t */\n\tSMALL_SERIAL(\"smallserial\"),\n\t/**\n\t * autoincrementing four-byte integer\n\t */\n\tSERIAL(\"serial\"),\n\t/**\n\t * variable-length character string\n\t */\n\tTEXT(\"text\"),\n\t/**\n\t * time of day (no time zone)\n\t */\n\tTIME(\"time\"),\n\t/**\n\t * time of day, including time zone\n\t */\n\tTIMETZ(\"timetz\"),\n\t/**\n\t * date and time (no time zone)\n\t */\n\tTIMESTAMP(\"timestamp\"),\n\t/**\n\t * date and time, including time zone\n\t */\n\tTIMESTAMPTZ(\"timestamptz\"),\n\t/**\n\t * text search query\n\t */\n\tTSQUERY(\"tsquery\"),\n\t/**\n\t * text search document\n\t */\n\tTSVECTOR(\"tsvector\"),\n\t/**\n\t * user-level transaction ID snapshot (deprecated; see pg_snapshot)\n\t */\n\tTXID_SNAPSHOT(\"txid_snapshot\"),\n\t/**\n\t * universally unique identifier\n\t */\n\tUUID(\"uuid\"),\n\t/**\n\t * XML data\n\t */\n\tXML(\"xml\");\n\n\n\tprivate final String name;\n\n\tPostgresType(String name) {\n\t\tthis.name = name;\n\t}\n\n\t@NotNull\n\t@Override\n\tpublic String getName() {\n\t\treturn name;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn name;\n\t}\n}"
},
{
"identifier": "ReflectionUtils",
"path": "src/main/java/de/mineking/javautils/reflection/ReflectionUtils.java",
"snippet": "public class ReflectionUtils {\n\t@NotNull\n\tpublic static Class<?> getClass(@NotNull Type type) {\n\t\tif(type instanceof Class<?> c) return c;\n\t\telse if(type instanceof ParameterizedType pt) return getClass(pt.getRawType());\n\t\telse if(type instanceof GenericArrayType) return ReflectionUtils.class;\n\n\t\tthrow new IllegalArgumentException(\"Cannot get class for type '\" + type + \"'\");\n\t}\n\n\tpublic static boolean isArray(@NotNull Type type, boolean includeCollection) {\n\t\tvar clazz = getClass(type);\n\t\treturn type instanceof GenericArrayType || clazz.isArray() || (includeCollection && Collection.class.isAssignableFrom(clazz));\n\t}\n\n\t@NotNull\n\tpublic static Optional<Enum<?>> getEnumConstant(@NotNull Type type, @NotNull String name) {\n\t\treturn Arrays.stream((Enum<?>[]) getClass(type).getEnumConstants())\n\t\t\t\t.filter(c -> c.name().equals(name))\n\t\t\t\t.findFirst();\n\t}\n\n\t@NotNull\n\tpublic static Type getComponentType(@NotNull Type type) {\n\t\tif(type instanceof Class<?> c && c.isArray()) return c.getComponentType();\n\t\telse if(type instanceof ParameterizedType pt) return pt.getActualTypeArguments()[0];\n\t\telse if(type instanceof GenericArrayType at) return at.getGenericComponentType();\n\n\t\tthrow new IllegalArgumentException(\"Cannot get component for '\" + type + \"'\");\n\t}\n\n\t@NotNull\n\tpublic static Type getActualArrayComponent(@NotNull Type type) {\n\t\tif(type instanceof Class<?> c) {\n\t\t\tif(c.isArray()) return c.getComponentType();\n\t\t\telse return c;\n\t\t} else if(type instanceof GenericArrayType at) return getActualArrayComponent(at.getGenericComponentType());\n\t\telse if(type instanceof ParameterizedType pt && Collection.class.isAssignableFrom(getClass(type))) return getActualArrayComponent(pt.getActualTypeArguments()[0]);\n\n\t\tthrow new IllegalArgumentException();\n\t}\n\n\t@NotNull\n\tpublic static Object[] createArray(@NotNull Type component, int... dimensions) {\n\t\treturn (Object[]) Array.newInstance(getClass(component), dimensions);\n\t}\n\n\t@NotNull\n\tpublic static Stream<?> stream(@NotNull Object o) {\n\t\treturn o instanceof Collection<?> c ? c.stream() : Arrays.stream((Object[]) o);\n\t}\n}"
}
] | import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.ToNumberStrategy;
import de.mineking.javautils.ID;
import de.mineking.javautils.database.type.DataType;
import de.mineking.javautils.database.type.PostgresType;
import de.mineking.javautils.reflection.ReflectionUtils;
import org.jdbi.v3.core.argument.Argument;
import org.jdbi.v3.core.statement.StatementContext;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.time.Instant;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger; | 2,909 | package de.mineking.javautils.database;
public interface TypeMapper<T, R> {
boolean accepts(@NotNull DatabaseManager manager, @NotNull Type type, @NotNull Field f);
@NotNull
DataType getType(@NotNull DatabaseManager manager, @NotNull Type type, @NotNull Field f);
@NotNull
default Argument createArgument(@NotNull DatabaseManager manager, @NotNull Type type, @NotNull Field f, @Nullable T value) {
return new Argument() {
@Override
public void apply(int position, PreparedStatement statement, StatementContext ctx) throws SQLException {
statement.setObject(position, value);
}
@Override
public String toString() {
return Objects.toString(value);
}
};
}
@Nullable
@SuppressWarnings("unchecked")
default T format(@NotNull DatabaseManager manager, @NotNull Type type, @NotNull Field f, @Nullable R value) {
return (T) value;
}
@Nullable
T extract(@NotNull ResultSet set, @NotNull String name, @NotNull Type target) throws SQLException;
@SuppressWarnings("unchecked")
@Nullable
default R parse(@NotNull DatabaseManager manager, @NotNull Type type, @NotNull Field field, @Nullable T value) {
return (R) value;
}
TypeMapper<Integer, Integer> SERIAL = new TypeMapper<>() {
@Override
public boolean accepts(@NotNull DatabaseManager manager, @NotNull Type type, @NotNull Field f) {
return f.getAnnotation(Column.class).autoincrement() && (type.equals(int.class) || type.equals(long.class));
}
@NotNull
@Override
public DataType getType(@NotNull DatabaseManager manager, @NotNull Type type, @NotNull Field f) { | package de.mineking.javautils.database;
public interface TypeMapper<T, R> {
boolean accepts(@NotNull DatabaseManager manager, @NotNull Type type, @NotNull Field f);
@NotNull
DataType getType(@NotNull DatabaseManager manager, @NotNull Type type, @NotNull Field f);
@NotNull
default Argument createArgument(@NotNull DatabaseManager manager, @NotNull Type type, @NotNull Field f, @Nullable T value) {
return new Argument() {
@Override
public void apply(int position, PreparedStatement statement, StatementContext ctx) throws SQLException {
statement.setObject(position, value);
}
@Override
public String toString() {
return Objects.toString(value);
}
};
}
@Nullable
@SuppressWarnings("unchecked")
default T format(@NotNull DatabaseManager manager, @NotNull Type type, @NotNull Field f, @Nullable R value) {
return (T) value;
}
@Nullable
T extract(@NotNull ResultSet set, @NotNull String name, @NotNull Type target) throws SQLException;
@SuppressWarnings("unchecked")
@Nullable
default R parse(@NotNull DatabaseManager manager, @NotNull Type type, @NotNull Field field, @Nullable T value) {
return (R) value;
}
TypeMapper<Integer, Integer> SERIAL = new TypeMapper<>() {
@Override
public boolean accepts(@NotNull DatabaseManager manager, @NotNull Type type, @NotNull Field f) {
return f.getAnnotation(Column.class).autoincrement() && (type.equals(int.class) || type.equals(long.class));
}
@NotNull
@Override
public DataType getType(@NotNull DatabaseManager manager, @NotNull Type type, @NotNull Field f) { | return type.equals(int.class) ? PostgresType.SERIAL : PostgresType.BIG_SERIAL; | 2 | 2023-12-13 14:05:17+00:00 | 4k |
serendipitk/LunarCore | src/main/java/emu/lunarcore/data/excel/AvatarSkillTreeExcel.java | [
{
"identifier": "GameData",
"path": "src/main/java/emu/lunarcore/data/GameData.java",
"snippet": "@SuppressWarnings(\"unused\")\npublic class GameData {\n // Excels\n @Getter private static Int2ObjectMap<AvatarExcel> avatarExcelMap = new Int2ObjectOpenHashMap<>();\n @Getter private static Int2ObjectMap<ItemExcel> itemExcelMap = new Int2ObjectOpenHashMap<>();\n @Getter private static Int2ObjectMap<ItemUseExcel> itemUseExcelMap = new Int2ObjectOpenHashMap<>();\n @Getter private static Int2ObjectMap<EquipmentExcel> equipExcelMap = new Int2ObjectOpenHashMap<>();\n @Getter private static Int2ObjectMap<RelicExcel> relicExcelMap = new Int2ObjectOpenHashMap<>();\n @Getter private static Int2ObjectMap<PropExcel> propExcelMap = new Int2ObjectOpenHashMap<>();\n @Getter private static Int2ObjectMap<NpcExcel> npcExcelMap = new Int2ObjectOpenHashMap<>();\n @Getter private static Int2ObjectMap<SummonUnitExcel> summonUnitExcelMap = new Int2ObjectOpenHashMap<>();\n @Getter private static Int2ObjectMap<MonsterExcel> monsterExcelMap = new Int2ObjectOpenHashMap<>();\n @Getter private static Int2ObjectMap<NpcMonsterExcel> npcMonsterExcelMap = new Int2ObjectOpenHashMap<>();\n @Getter private static Int2ObjectMap<StageExcel> stageExcelMap = new Int2ObjectOpenHashMap<>();\n @Getter private static Int2ObjectMap<MazePlaneExcel> mazePlaneExcelMap = new Int2ObjectOpenHashMap<>();\n @Getter private static Int2ObjectMap<MapEntranceExcel> mapEntranceExcelMap = new Int2ObjectOpenHashMap<>();\n @Getter private static Int2ObjectMap<HeroExcel> heroExcelMap = new Int2ObjectOpenHashMap<>();\n @Getter private static Int2ObjectMap<ShopExcel> shopExcelMap = new Int2ObjectOpenHashMap<>();\n @Getter private static Int2ObjectMap<RewardExcel> rewardExcelMap = new Int2ObjectOpenHashMap<>();\n @Getter private static Int2ObjectMap<InteractExcel> interactExcelMap = new Int2ObjectOpenHashMap<>();\n @Getter private static Int2ObjectMap<PlayerIconExcel> playerIconExcelMap = new Int2ObjectOpenHashMap<>();\n @Getter private static Int2ObjectMap<ItemComposeExcel> itemComposeExcelMap = new Int2ObjectOpenHashMap<>();\n @Getter private static Int2ObjectMap<ActivityPanelExcel> activityPanelExcelMap = new Int2ObjectOpenHashMap<>();\n @Getter private static Int2ObjectMap<BackGroundMusicExcel> backGroundMusicExcelMap = new Int2ObjectOpenHashMap<>();\n @Getter private static Int2ObjectMap<QuestExcel> questExcelMap = new Int2ObjectLinkedOpenHashMap<>();\n @Getter private static Int2ObjectMap<TextJoinExcel> textJoinExcelMap = new Int2ObjectLinkedOpenHashMap<>();\n @Getter private static Int2ObjectMap<ChatBubbleExcel> chatBubbleExcelMap = new Int2ObjectOpenHashMap<>();\n @Getter private static Int2ObjectMap<PhoneThemeExcel> phoneThemeExcelMap = new Int2ObjectOpenHashMap<>();\n\n @Getter private static Int2ObjectMap<ChallengeGroupExcel> challengeGroupExcelMap = new Int2ObjectOpenHashMap<>();\n @Getter private static Int2ObjectMap<ChallengeExcel> challengeExcelMap = new Int2ObjectOpenHashMap<>();\n @Getter private static Int2ObjectMap<ChallengeTargetExcel> challengeTargetExcelMap = new Int2ObjectOpenHashMap<>();\n private static Int2ObjectMap<ChallengeRewardExcel> challengeRewardExcelMap = new Int2ObjectOpenHashMap<>();\n \n @Getter private static Int2ObjectMap<RogueManagerExcel> rogueManagerExcelMap = new Int2ObjectOpenHashMap<>();\n @Getter private static Int2ObjectMap<RogueTalentExcel> rogueTalentExcelMap = new Int2ObjectOpenHashMap<>();\n @Getter private static Int2ObjectMap<RogueAeonExcel> rogueAeonExcelMap = new Int2ObjectLinkedOpenHashMap<>();\n @Getter private static Int2ObjectMap<RogueAreaExcel> rogueAreaExcelMap = new Int2ObjectOpenHashMap<>();\n @Getter private static Int2ObjectMap<RogueRoomExcel> rogueRoomExcelMap = new Int2ObjectOpenHashMap<>();\n @Getter private static Int2ObjectMap<RogueMapExcel> rogueMapExcelMap = new Int2ObjectOpenHashMap<>();\n @Getter private static Int2ObjectMap<RogueMonsterExcel> rogueMonsterExcelMap = new Int2ObjectOpenHashMap<>();\n private static Int2ObjectMap<RogueBuffExcel> rogueBuffExcelMap = new Int2ObjectOpenHashMap<>();\n \n private static Int2ObjectMap<AvatarPromotionExcel> avatarPromotionExcelMap = new Int2ObjectOpenHashMap<>();\n private static Int2ObjectMap<AvatarSkillTreeExcel> avatarSkillTreeExcelMap = new Int2ObjectOpenHashMap<>();\n private static Int2ObjectMap<AvatarRankExcel> avatarRankExcelMap = new Int2ObjectOpenHashMap<>();\n private static Int2ObjectMap<EquipmentPromotionExcel> equipmentPromotionExcelMap = new Int2ObjectOpenHashMap<>();\n private static Int2ObjectMap<MazeBuffExcel> mazeBuffExcelMap = new Int2ObjectOpenHashMap<>();\n private static Int2ObjectMap<CocoonExcel> cocoonExcelMap = new Int2ObjectOpenHashMap<>();\n private static Int2ObjectMap<MappingInfoExcel> mappingInfoExcelMap = new Int2ObjectOpenHashMap<>();\n private static Int2ObjectMap<MonsterDropExcel> monsterDropExcelMap = new Int2ObjectOpenHashMap<>();\n \n private static Int2ObjectMap<PlayerLevelExcel> playerLevelExcelMap = new Int2ObjectOpenHashMap<>();\n private static Int2ObjectMap<ExpTypeExcel> expTypeExcelMap = new Int2ObjectOpenHashMap<>();\n private static Int2ObjectMap<EquipmentExpTypeExcel> equipmentExpTypeExcelMap = new Int2ObjectOpenHashMap<>();\n private static Int2ObjectMap<RelicExpTypeExcel> relicExpTypeExcelMap = new Int2ObjectOpenHashMap<>();\n \n private static Int2ObjectMap<RelicMainAffixExcel> relicMainAffixExcelMap = new Int2ObjectOpenHashMap<>();\n private static Int2ObjectMap<RelicSubAffixExcel> relicSubAffixExcelMap = new Int2ObjectOpenHashMap<>();\n private static Int2ObjectMap<RelicSetExcel> relicSetExcelMap = new Int2ObjectOpenHashMap<>();\n \n // Configs (Bin)\n @Getter private static Object2ObjectMap<String, FloorInfo> floorInfos = new Object2ObjectOpenHashMap<>();\n\n public static Int2ObjectMap<?> getMapForExcel(Class<?> resourceDefinition) {\n Int2ObjectMap<?> map = null;\n\n try {\n Field field = GameData.class.getDeclaredField(Utils.lowerCaseFirstChar(resourceDefinition.getSimpleName()) + \"Map\");\n field.setAccessible(true);\n\n map = (Int2ObjectMap<?>) field.get(null);\n\n field.setAccessible(false);\n } catch (Exception e) {\n\n }\n\n return map;\n }\n\n public static List<Integer> getAllRelicIds() {\n List<Integer> allIds = new ArrayList<>();\n\n for (Int2ObjectMap.Entry<RelicExcel> entry : relicExcelMap.int2ObjectEntrySet()) {\n RelicExcel relicExcel = entry.getValue();\n allIds.add(relicExcel.getId());\n }\n\n return allIds;\n }\n\n public static int getRelicSetFromId(int relicId) {\n RelicExcel relicExcel = GameData.getRelicExcelMap().get(relicId);\n\n if (relicExcel == null) {\n return 0;\n }\n return relicExcel.getSetId();\n }\n\n public static List<Integer> getAllMusicIds() {\n List<Integer> allIds = new ArrayList<>();\n\n for (Int2ObjectMap.Entry<BackGroundMusicExcel> entry : backGroundMusicExcelMap.int2ObjectEntrySet()) {\n BackGroundMusicExcel backGroundMusicExcel = entry.getValue();\n allIds.add(backGroundMusicExcel.getId());\n }\n\n return allIds;\n }\n\n public static int TextJoinItemFromId(int id) {\n for (Int2ObjectMap.Entry<TextJoinExcel> entry : textJoinExcelMap.int2ObjectEntrySet()) {\n TextJoinExcel textJoinExcel = entry.getValue();\n if (textJoinExcel.getId() == id) {\n IntArrayList textJoinItemList = textJoinExcel.getTextJoinItemList();\n if (textJoinItemList.size() > 0) {\n return textJoinItemList.getInt(textJoinItemList.size() - 1);\n }\n }\n }\n return id * 10; // or return a default value if needed\n }\n \n public static List<Integer> getAllMonsterIds() {\n List<Integer> allIds = new ArrayList<>();\n\n for (Int2ObjectMap.Entry<MonsterExcel> entry : monsterExcelMap.int2ObjectEntrySet()) {\n MonsterExcel monsterExcel = entry.getValue();\n allIds.add(monsterExcel.getId());\n }\n\n return allIds;\n }\n\n public static int getMusicGroupId(int musicId) {\n var excel = backGroundMusicExcelMap.get(musicId);\n return excel != null ? excel.getGroupId() : 0;\n }\n \n public static AvatarPromotionExcel getAvatarPromotionExcel(int id, int promotion) {\n return avatarPromotionExcelMap.get((id << 8) + promotion);\n }\n\n public static AvatarSkillTreeExcel getAvatarSkillTreeExcel(int skill, int level) {\n return avatarSkillTreeExcelMap.get((skill << 4) + level);\n }\n\n public static AvatarRankExcel getAvatarRankExcel(int rankId) {\n return avatarRankExcelMap.get(rankId);\n }\n\n public static EquipmentPromotionExcel getEquipmentPromotionExcel(int id, int promotion) {\n return equipmentPromotionExcelMap.get((id << 8) + promotion);\n }\n\n public static int getPlayerExpRequired(int level) {\n var excel = playerLevelExcelMap.get(level);\n return excel != null ? excel.getPlayerExp() : 0;\n }\n\n public static int getAvatarExpRequired(int expGroup, int level) {\n var excel = expTypeExcelMap.get((expGroup << 16) + level);\n return excel != null ? excel.getExp() : 0;\n }\n\n public static int getEquipmentExpRequired(int expGroup, int level) {\n var excel = equipmentExpTypeExcelMap.get((expGroup << 16) + level);\n return excel != null ? excel.getExp() : 0;\n }\n\n public static int getRelicExpRequired(int expGroup, int level) {\n var excel = relicExpTypeExcelMap.get((expGroup << 16) + level);\n return excel != null ? excel.getExp() : 0;\n }\n \n public static RelicMainAffixExcel getRelicMainAffixExcel(int groupId, int affixId) {\n return relicMainAffixExcelMap.get((groupId << 16) + affixId);\n }\n\n public static RelicSubAffixExcel getRelicSubAffixExcel(int groupId, int affixId) {\n return relicSubAffixExcelMap.get((groupId << 16) + affixId);\n }\n \n public static FloorInfo getFloorInfo(int planeId, int floorId) {\n return floorInfos.get(\"P\" + planeId + \"_F\" + floorId);\n }\n\n public static MazeBuffExcel getMazeBuffExcel(int buffId, int level) {\n return mazeBuffExcelMap.get((buffId << 4) + level);\n }\n \n public static CocoonExcel getCocoonExcel(int cocoonId, int worldLevel) {\n return cocoonExcelMap.get((cocoonId << 8) + worldLevel);\n }\n \n public static MappingInfoExcel getMappingInfoExcel(int mappingInfoId, int worldLevel) {\n return mappingInfoExcelMap.get((mappingInfoId << 8) + worldLevel);\n }\n \n public static MonsterDropExcel getMonsterDropExcel(int monsterNpcId, int worldLevel) {\n return monsterDropExcelMap.get((monsterNpcId << 4) + worldLevel);\n }\n \n public static ChallengeRewardExcel getChallengeRewardExcel(int groupId, int starCount) {\n return challengeRewardExcelMap.get((groupId << 16) + starCount);\n }\n \n public static RogueMapExcel getRogueMapExcel(int rogueMapId, int siteId) {\n return rogueMapExcelMap.get((rogueMapId << 8) + siteId);\n }\n \n public static RogueBuffExcel getRogueBuffExcel(int rogueBuffId, int level) {\n return rogueBuffExcelMap.get((rogueBuffId << 4) + level);\n }\n}"
},
{
"identifier": "GameResource",
"path": "src/main/java/emu/lunarcore/data/GameResource.java",
"snippet": "public abstract class GameResource implements Comparable<GameResource> {\n\n public abstract int getId();\n\n public void onLoad() {\n\n }\n\n @Override\n public int compareTo(GameResource o) {\n return this.getId() - o.getId();\n }\n}"
},
{
"identifier": "ItemParam",
"path": "src/main/java/emu/lunarcore/data/common/ItemParam.java",
"snippet": "@Getter\npublic class ItemParam {\n @SerializedName(value = \"id\", alternate = {\"ItemId\", \"ItemID\"})\n private int id;\n\n @SerializedName(value = \"count\", alternate = {\"ItemCount\", \"ItemNum\"})\n private int count;\n\n private transient ItemParamType type = ItemParamType.PILE;\n\n public ItemParam() {\n // Gson\n }\n \n public ItemParam(int id, int count) {\n this.id = id;\n this.count = count;\n }\n\n public ItemParam(ItemParamType type, int id, int count) {\n this.type = type;\n this.id = id;\n this.count = count;\n }\n\n public ItemParam(ItemCost itemCost) {\n if (itemCost.hasPileItem()) {\n this.id = itemCost.getPileItem().getItemId();\n this.count = itemCost.getPileItem().getItemNum();\n } else if (itemCost.hasEquipmentUniqueId()) {\n this.type = ItemParamType.UNIQUE;\n this.id = itemCost.getEquipmentUniqueId();\n this.count = 1;\n } else if (itemCost.hasRelicUniqueId()) {\n this.type = ItemParamType.UNIQUE;\n this.id = itemCost.getRelicUniqueId();\n this.count = 1;\n }\n }\n\n public static enum ItemParamType {\n UNKNOWN, PILE, UNIQUE;\n }\n}"
}
] | import java.util.List;
import emu.lunarcore.data.GameData;
import emu.lunarcore.data.GameResource;
import emu.lunarcore.data.ResourceType;
import emu.lunarcore.data.ResourceType.LoadPriority;
import emu.lunarcore.data.common.ItemParam;
import it.unimi.dsi.fastutil.ints.IntArrayList;
import lombok.Getter; | 3,568 | package emu.lunarcore.data.excel;
@Getter
@ResourceType(name = {"AvatarSkillTreeConfig.json"}, loadPriority = LoadPriority.LOW)
public class AvatarSkillTreeExcel extends GameResource {
private int PointID;
private int Level;
private int MaxLevel;
private boolean DefaultUnlock;
private int AvatarID;
private int AvatarPromotionLimit;
private int AvatarLevelLimit;
| package emu.lunarcore.data.excel;
@Getter
@ResourceType(name = {"AvatarSkillTreeConfig.json"}, loadPriority = LoadPriority.LOW)
public class AvatarSkillTreeExcel extends GameResource {
private int PointID;
private int Level;
private int MaxLevel;
private boolean DefaultUnlock;
private int AvatarID;
private int AvatarPromotionLimit;
private int AvatarLevelLimit;
| private List<ItemParam> MaterialList; | 2 | 2023-12-08 14:13:04+00:00 | 4k |
adabox-aio/dextreme-sdk | src/test/java/io/adabox/dextreme/dex/api/VyFinanceApiTest.java | [
{
"identifier": "DexFactory",
"path": "src/main/java/io/adabox/dextreme/DexFactory.java",
"snippet": "public class DexFactory {\n\n private DexFactory() {\n throw new IllegalStateException(\"Utility class\");\n }\n\n /**\n * Get Dex Object\n *\n * @return {@link Dex}\n */\n public static Dex getDex(DexType dexType, BaseProvider baseProvider) {\n TokenRegistry.getInstance().updateTokens();\n switch (dexType) {\n case Minswap -> {\n return new Minswap(baseProvider);\n }\n case Muesliswap -> {\n return new Muesliswap(baseProvider);\n }\n case Sundaeswap -> {\n return new Sundaeswap(baseProvider);\n }\n case WingRiders -> {\n return new WingRiders(baseProvider);\n }\n case VyFinance -> {\n return new VyFinance(new ApiProvider());\n }\n// case Spectrum -> {\n// return new Spectrum(baseProvider);\n// }\n case null, default ->\n throw new IllegalArgumentException(dexType + \" is not yet Supported!\");\n }\n }\n}"
},
{
"identifier": "Dex",
"path": "src/main/java/io/adabox/dextreme/dex/base/Dex.java",
"snippet": "@Slf4j\n@Getter\n@Setter\npublic abstract class Dex {\n\n private final DexType dexType;\n private final BaseProvider provider;\n private final Api api;\n private Map<String, LiquidityPool> liquidityPoolMap = new HashMap<>();\n\n public Dex(DexType dexType, BaseProvider provider, Api api) {\n this.dexType = dexType;\n this.provider = provider;\n this.api = api;\n updateLiquidityPools();\n log.info(\"{} - Loaded: {} Liquidity Pools.\", dexType.name(), getLiquidityPoolMap().size());\n }\n\n public void updateLiquidityPools() {\n if (getProvider().getProviderType() == ProviderType.API) {\n setLiquidityPoolMap(getApi().liquidityPools().stream()\n .collect(Collectors.toMap(LiquidityPool::getIdentifier, Function.identity(), ((liquidityPool, liquidityPool2) -> liquidityPool))));\n } else {\n List<UTxO> assetUtxos = ((ClientProvider) getProvider()).assetUtxos(getFactoryToken());\n setLiquidityPoolMap(assetUtxos.stream()\n .map(this::toLiquidityPool)\n .filter(Objects::nonNull)\n .collect(Collectors.toMap(LiquidityPool::getIdentifier, Function.identity(), ((liquidityPool, liquidityPool2) -> liquidityPool))));\n }\n\n }\n\n public Map<String, Token> getTokens(boolean verifiedOnly) {\n Map<String, Token> tokenDtos = new HashMap<>();\n getLiquidityPoolMap().values().forEach(liquidityPool -> {\n if (!tokenDtos.containsKey(liquidityPool.getAssetA().getIdentifier(\"\"))) {\n TokenUtils.insertTokenToMap(tokenDtos, getLiquidityPoolMap().values(), liquidityPool.getAssetA(), verifiedOnly);\n }\n if (!tokenDtos.containsKey(liquidityPool.getAssetB().getIdentifier(\"\"))) {\n TokenUtils.insertTokenToMap(tokenDtos, getLiquidityPoolMap().values(), liquidityPool.getAssetB(), verifiedOnly);\n }\n });\n return tokenDtos;\n }\n\n public List<LiquidityPool> getLiquidityPools(Asset assetA, Asset assetB) {\n if (getProvider().getProviderType() != ProviderType.API || assetA.isLovelace()) {\n return getLiquidityPoolMap().values().stream().filter(liquidityPool -> {\n if (assetA != null && assetB == null) {\n return liquidityPool.getAssetA().getAssetName().equals(assetA.getAssetName());\n } else if (assetA != null) {\n return (liquidityPool.getAssetA().getAssetName().equals(assetA.getAssetName()) && liquidityPool.getAssetB().getAssetName().equals(assetB.getAssetName())) ||\n (liquidityPool.getAssetA().getAssetName().equals(assetB.getAssetName()) && liquidityPool.getAssetB().getAssetName().equals(assetA.getAssetName()));\n } else {\n return false;\n }\n }).toList();\n }\n return getApi().liquidityPools(assetA, assetB);\n }\n\n public LiquidityPool toLiquidityPool(UTxO utxo) {\n if (StringUtils.isBlank(utxo.getDatumHash())) {\n return null;\n }\n if (!utxo.containsAsset(getFactoryToken())) {\n return null;\n }\n if (!utxo.containsAssetPolicyId(getPoolNFTPolicyIds())) {\n return null;\n }\n List<String> policyList = new ArrayList<>(getPoolNFTPolicyIds());\n policyList.add(getLPTokenPolicyId());\n List<Balance> balanceList = utxo.filterByUnitAndPolicies(getFactoryToken(), policyList.toArray(new String[0]));\n if (balanceList.size() < 2 || balanceList.size() > 3) {\n return null;\n }\n int assetAIndex = 0;\n int assetBIndex = 1;\n\n if (balanceList.size() == 3) {\n assetAIndex = 1;\n assetBIndex = 2;\n }\n LiquidityPool liquidityPool = new LiquidityPool(\n getDexType().name(),\n balanceList.get(assetAIndex).getAsset(),\n balanceList.get(assetBIndex).getAsset(),\n balanceList.get(assetAIndex).getQuantity(),\n balanceList.get(assetBIndex).getQuantity(),\n utxo.getAddress(),\n getMarketOrderAddress(),\n getLimitOrderAddress());\n\n Asset poolNft = utxo.getAssetWithPolicyIds(getPoolNFTPolicyIds());\n\n if (poolNft == null) {\n return null;\n }\n\n liquidityPool.setLpToken(new Asset(getLPTokenPolicyId(), poolNft.getNameHex(), 0));\n liquidityPool.setIdentifier(liquidityPool.getLpToken().getIdentifier(\"\"));\n liquidityPool.setPoolFeePercent(getPoolFeePercent(utxo));\n liquidityPool.setUTxO(utxo);\n return liquidityPool;\n }\n\n public abstract String getFactoryToken();\n\n public abstract List<String> getPoolNFTPolicyIds();\n\n public abstract String getLPTokenPolicyId();\n\n public abstract String getMarketOrderAddress();\n\n public abstract String getLimitOrderAddress();\n\n public abstract double getPoolFeePercent(UTxO utxo);\n\n public abstract BigInteger getSwapFee(); // the (batcher) fee applicable for this DEX\n\n public abstract BigInteger getLovelaceOutput(); // the amount of lovelace which will be returned on swaps\n\n public abstract PlutusData swapDatum(SwapDatumRequest swapDatumRequest);\n}"
},
{
"identifier": "DexType",
"path": "src/main/java/io/adabox/dextreme/dex/base/DexType.java",
"snippet": "public enum DexType {\n Minswap,\n Muesliswap,\n Sundaeswap,\n VyFinance,\n Spectrum,\n WingRiders;\n\n public DexType resolveDexType(String dexTypeString) {\n return Arrays.stream(values()).filter(dexType -> dexType.name().equalsIgnoreCase(dexTypeString)).findFirst().orElse(null);\n }\n}"
},
{
"identifier": "Asset",
"path": "src/main/java/io/adabox/dextreme/model/Asset.java",
"snippet": "@Data\n@Slf4j\n@EqualsAndHashCode\n@NoArgsConstructor\n@AllArgsConstructor\npublic class Asset {\n\n private String policyId;\n private String nameHex;\n private int decimals;\n\n public static Asset fromId(String id, int decimals) {\n id = id.replace(\".\", \"\");\n if (id.equals(LOVELACE)) {\n return AssetType.ADA.getAsset();\n } else {\n return new Asset(id.substring(0, 56), id.substring(56), decimals);\n }\n }\n\n public String getIdentifier(String delimiter) {\n return policyId + delimiter + nameHex;\n }\n\n public String getNameHex() {\n return isLovelace() ? \"\" : nameHex;\n }\n\n @JsonIgnore\n public boolean isLovelace() {\n return nameHex.equalsIgnoreCase(LOVELACE);\n }\n\n public String getAssetName() {\n return isLovelace() ? \"ADA\" : new String(HexUtil.decodeHexString(getNameHex()), StandardCharsets.UTF_8);\n }\n\n @Override\n public String toString() {\n return getAssetName();\n }\n}"
},
{
"identifier": "LiquidityPool",
"path": "src/main/java/io/adabox/dextreme/model/LiquidityPool.java",
"snippet": "@Setter\n@Getter\n@ToString\n@NoArgsConstructor\npublic class LiquidityPool {\n\n private String dex;\n private Asset assetA;\n private Asset assetB;\n private BigInteger reserveA;\n private BigInteger reserveB;\n private String address;\n private String marketOrderAddress;\n private String limitOrderAddress;\n\n @JsonIgnore\n private Asset lpToken;\n private String identifier = \"\";\n private double poolFeePercent = 0.0;\n\n @JsonIgnore\n private UTxO uTxO;\n\n public LiquidityPool(String dex, Asset assetA, Asset assetB, BigInteger reserveA, BigInteger reserveB,\n String address, String marketOrderAddress, String limitOrderAddress) {\n this.dex = dex;\n this.assetA = assetA;\n this.assetB = assetB;\n this.reserveA = reserveA;\n this.reserveB = reserveB;\n this.address = address;\n this.marketOrderAddress = marketOrderAddress;\n this.limitOrderAddress = limitOrderAddress;\n }\n\n @JsonProperty(\"uuid\")\n public String getUuid() {\n return dex + \".\" + getPair() + \".\" + identifier;\n }\n\n public String getPair() {\n return assetA.getAssetName() + \"/\" + assetB.getAssetName();\n }\n\n public double getPrice() {\n double adjustedReserveA = reserveA.doubleValue() / Math.pow(10, assetA.getDecimals());\n double adjustedReserveB = reserveB.doubleValue() / Math.pow(10, assetB.getDecimals());\n\n return adjustedReserveA / adjustedReserveB;\n }\n\n @JsonProperty(\"TVL\")\n public double getTotalValueLocked() {\n double assetADividedByDecimals = reserveA.doubleValue() / Math.pow(10, assetA.getDecimals());\n double assetBDividedByDecimals = reserveB.doubleValue() / Math.pow(10, assetB.getDecimals());\n if (assetA.isLovelace()) {\n return assetADividedByDecimals + assetBDividedByDecimals * getPrice();\n }\n return (assetADividedByDecimals) * getPrice() * assetBDividedByDecimals * (1.0 / getPrice());\n }\n}"
},
{
"identifier": "Token",
"path": "src/main/java/io/adabox/dextreme/model/Token.java",
"snippet": "@Getter\n@Setter\n@ToString\n@NoArgsConstructor\n@AllArgsConstructor\npublic class Token extends Asset {\n\n private String name;\n private String ticker;\n private String image;\n private boolean verified;\n private String description;\n private Set<String> canSwapTo = new HashSet<>();\n\n public Token(String policyId, String nameHex, String name, String ticker, String image, boolean verified, int decimals, String description) {\n super(policyId, nameHex, decimals);\n this.name = name;\n this.ticker = ticker;\n this.image = image;\n this.verified = verified;\n this.description = description;\n }\n\n public Token(Asset asset, AssetTokenRegistry assetTokenRegistry, boolean isVerified) {\n if (asset.isLovelace()) {\n setNameHex(LOVELACE);\n setPolicyId(asset.getPolicyId());\n setName(\"Cardano\");\n setTicker(\"ADA\");\n setDecimals(6);\n setVerified(true);\n } else {\n setNameHex(asset.getNameHex());\n setPolicyId(asset.getPolicyId());\n if (assetTokenRegistry != null) {\n setName(assetTokenRegistry.getAssetNameAscii());\n setTicker(assetTokenRegistry.getTicker());\n setImage(assetTokenRegistry.getLogo());\n setDecimals(assetTokenRegistry.getDecimals());\n setDescription(assetTokenRegistry.getDescription());\n } else {\n setName(asset.getAssetName());\n setTicker(asset.getAssetName());\n }\n setVerified(isVerified);\n }\n }\n\n public String getId() {\n return getPolicyId() + getNameHex();\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 Token token = (Token) o;\n return Objects.equals(getNameHex(), token.getNameHex()) && Objects.equals(getPolicyId(), token.getPolicyId());\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(getNameHex(), getPolicyId());\n }\n}"
},
{
"identifier": "ApiProvider",
"path": "src/main/java/io/adabox/dextreme/provider/ApiProvider.java",
"snippet": "public class ApiProvider extends BaseProvider {\n\n @Override\n public ProviderType getProviderType() {\n return ProviderType.API;\n }\n}"
}
] | import io.adabox.dextreme.DexFactory;
import io.adabox.dextreme.dex.base.Dex;
import io.adabox.dextreme.dex.base.DexType;
import io.adabox.dextreme.model.Asset;
import io.adabox.dextreme.model.LiquidityPool;
import io.adabox.dextreme.model.Token;
import io.adabox.dextreme.provider.ApiProvider;
import org.junit.jupiter.api.Test;
import java.util.List;
import static io.adabox.dextreme.model.AssetType.ADA;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull; | 3,367 | package io.adabox.dextreme.dex.api;
public class VyFinanceApiTest {
private final Dex vyFinance = DexFactory.getDex(DexType.VyFinance, new ApiProvider());
@Test
public void vyFinanceGetLP() { | package io.adabox.dextreme.dex.api;
public class VyFinanceApiTest {
private final Dex vyFinance = DexFactory.getDex(DexType.VyFinance, new ApiProvider());
@Test
public void vyFinanceGetLP() { | Asset assetA = ADA.getAsset(); | 3 | 2023-12-10 12:14:48+00:00 | 4k |
zhaw-iwi/promise | src/main/java/ch/zhaw/statefulconversation/model/commons/actions/DynamicRemoveTopicAction.java | [
{
"identifier": "Action",
"path": "src/main/java/ch/zhaw/statefulconversation/model/Action.java",
"snippet": "@Entity\npublic abstract class Action extends Prompt {\n\n protected Action() {\n\n }\n\n private String storageKeyTo;\n\n public Action(String actionPromp) {\n super(actionPromp);\n this.storageKeyTo = null;\n }\n\n public Action(String actionPrompt, Storage storage, String storageKeyTo) {\n super(actionPrompt, storage, List.of());\n this.storageKeyTo = storageKeyTo;\n }\n\n public Action(String actionPrompt, Storage storage, String storageKeyFrom, String storageKeyTo) {\n super(actionPrompt, storage, List.of(storageKeyFrom));\n this.storageKeyTo = storageKeyTo;\n }\n\n protected String getStorageKeyTo() {\n if (this.storageKeyTo == null) {\n throw new RuntimeException(\n \"this is not a dynamic action - storageKeyTo is supposed to be null\");\n }\n return this.storageKeyTo;\n }\n\n public abstract void execute(Utterances utterances);\n\n @Override\n public String toString() {\n return \"Action IS-A \" + super.toString();\n }\n}"
},
{
"identifier": "Storage",
"path": "src/main/java/ch/zhaw/statefulconversation/model/Storage.java",
"snippet": "@Entity\npublic class Storage {\n\n @Id\n @GeneratedValue\n private UUID id;\n\n public UUID getID() {\n return this.id;\n }\n\n @OneToMany(cascade = { CascadeType.ALL }, fetch = FetchType.EAGER, orphanRemoval = true)\n private List<StorageEntry> entries;\n\n public Storage() {\n this.entries = new ArrayList<StorageEntry>();\n }\n\n public void put(String key, JsonElement value) {\n for (StorageEntry current : this.entries) {\n if (current.getKey().equals(key)) {\n current.setValue(value);\n return;\n }\n }\n\n StorageEntry entry = new StorageEntry(key, value);\n this.entries.add(entry);\n }\n\n public boolean containsKey(String key) {\n for (StorageEntry current : this.entries) {\n if (current.getKey().equals(key)) {\n return true;\n }\n }\n return false;\n }\n\n public JsonElement get(String key) {\n for (StorageEntry candiate : this.entries) {\n if (candiate.getKey().equals(key)) {\n return candiate.getValue();\n }\n }\n throw new RuntimeException(\"this storage does not contain an entry with key = \" + key);\n }\n\n public StorageEntry remove(String key) {\n for (StorageEntry current : this.entries) {\n if (current.getKey().equals(key)) {\n this.entries.remove(current);\n return current;\n }\n }\n throw new RuntimeException(\"this storage does not contain an entry with key = \" + key);\n }\n\n public Map<String, JsonElement> toMap() {\n Map<String, JsonElement> result = new HashMap<>();\n for (StorageEntry current : this.entries) {\n result.put(current.getKey(), current.getValue());\n }\n return result;\n }\n\n @Override\n public String toString() {\n return \"Storage containing \" + this.entries;\n }\n\n // @TODO utility serialisation/deserialisation methods\n public static List<String> toListOfString(JsonElement jsonListOfStrings) {\n List<JsonElement> listOfJsonElements = jsonListOfStrings.getAsJsonArray().asList();\n List<String> result = new ArrayList<String>();\n for (JsonElement current : listOfJsonElements) {\n result.add(current.getAsString());\n }\n return result;\n }\n\n private static Gson GSON = new Gson();\n\n public static JsonElement toJsonElement(Object javaObject) {\n return Storage.GSON.toJsonTree(javaObject);\n }\n\n}"
},
{
"identifier": "Utterances",
"path": "src/main/java/ch/zhaw/statefulconversation/model/Utterances.java",
"snippet": "@Entity\npublic class Utterances {\n\n private static final String ASSISTANT = \"assistant\";\n private static final String USER = \"user\";\n\n @Id\n @GeneratedValue\n private UUID id;\n\n public UUID getID() {\n return this.id;\n }\n\n @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, orphanRemoval = true)\n @OrderColumn(name = \"utterance_index\")\n private List<Utterance> utteranceList;\n\n public Utterances() {\n this.utteranceList = new ArrayList<Utterance>();\n }\n\n public void appendAssistantSays(String assistantSays) {\n this.utteranceList.add(new Utterance(Utterances.ASSISTANT, assistantSays));\n }\n\n public void appendUserSays(String userSays) {\n this.utteranceList.add(new Utterance(Utterances.USER, userSays));\n }\n\n /*\n * This one is assuming the last utterance is from the user\n * (used in RemoveLastUtteranceAction)\n */\n public void removeLastUtterance() {\n if (!this.utteranceList.getLast().getRole().equals(Utterances.USER)) {\n throw new RuntimeException(\"assumption that last utterance has role == user failed\");\n }\n this.utteranceList.removeLast();\n }\n\n public String removeLastTwoUtterances() {\n if (!this.utteranceList.getLast().getRole().equals(Utterances.ASSISTANT)) {\n throw new RuntimeException(\"assumption that last utterance has role == assistant failed\");\n }\n this.utteranceList.removeLast();\n\n // the following loop is to accomodate the possibility that the assistant had\n // multiple responses in a row (cf. HTML reponses)\n while (this.utteranceList.getLast().getRole().equals(Utterances.ASSISTANT)) {\n this.utteranceList.removeLast();\n }\n\n if (!this.utteranceList.getLast().getRole().equals(Utterances.USER)) {\n throw new RuntimeException(\n \"assumption that when removing all assistant utterances only user utterance remains failed\");\n }\n\n Utterance lastUserUtterance = this.utteranceList.getLast();\n return lastUserUtterance.getContent();\n }\n\n public boolean isEmpty() {\n return this.utteranceList.isEmpty();\n }\n\n public void reset() {\n this.utteranceList.clear();\n }\n\n public List<Utterance> toList() {\n List<Utterance> result = List.copyOf(this.utteranceList);\n return result;\n }\n\n @Override\n public String toString() {\n StringBuffer result = new StringBuffer(\"\");\n for (Utterance current : this.utteranceList) {\n result.append(current.getRole() + \": \" + current.getContent() + \"\\n\");\n }\n return result.toString();\n }\n}"
}
] | import java.util.List;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
import ch.zhaw.statefulconversation.model.Action;
import ch.zhaw.statefulconversation.model.Storage;
import ch.zhaw.statefulconversation.model.Utterances;
import jakarta.persistence.Entity; | 1,794 | package ch.zhaw.statefulconversation.model.commons.actions;
@Entity
public class DynamicRemoveTopicAction extends Action {
protected DynamicRemoveTopicAction() {
}
| package ch.zhaw.statefulconversation.model.commons.actions;
@Entity
public class DynamicRemoveTopicAction extends Action {
protected DynamicRemoveTopicAction() {
}
| public DynamicRemoveTopicAction(String actionPromptTemplate, Storage storage, String storageKeyFrom, | 1 | 2023-12-06 09:36:58+00:00 | 4k |
SkyDynamic/QuickBackupM-Fabric | src/main/java/dev/skydynamic/quickbackupmulti/QuickBackupMulti.java | [
{
"identifier": "Translate",
"path": "src/main/java/dev/skydynamic/quickbackupmulti/i18n/Translate.java",
"snippet": "public class Translate {\n\n private static Map<String, String> translateMap = new HashMap<>();\n public static final Collection<String> supportLanguage = List.of(\"zh_cn\", \"en_us\");\n\n public static Map<String, String> getTranslationFromResourcePath(String lang) {\n InputStream langFile = Translate.class.getClassLoader().getResourceAsStream(\"assets/quickbackupmulti/lang/%s.yml\".formatted(lang));\n if (langFile == null) {\n return Collections.emptyMap();\n }\n String yamlData;\n try {\n yamlData = IOUtils.toString(langFile, StandardCharsets.UTF_8);\n } catch (IOException e) {\n return Collections.emptyMap();\n }\n Yaml yaml = new Yaml();\n Map<String, Object> obj = yaml.load(yamlData);\n return addMapToResult(\"\", obj);\n }\n\n public static void handleResourceReload(String lang) {\n translateMap = getTranslationFromResourcePath(lang);\n }\n\n public static String translate(String key, Object... args) {\n String fmt = translateMap.getOrDefault(key, key);\n if (!translateMap.containsKey(key)) return key;\n return String.format(fmt, args);\n }\n\n public static String tr(String k, Object... o) {\n return translate(k, o);\n }\n\n @SuppressWarnings(\"unchecked\")\n private static Map<String, String> addMapToResult(String prefix, Map<String, Object> map) {\n Map<String, String> resultMap = new HashMap<>();\n for (Map.Entry<String, Object> entry : map.entrySet()) {\n String key = entry.getKey();\n Object value = entry.getValue();\n String newPrefix = prefix.isEmpty() ? key : prefix + \".\" + key;\n if (value instanceof Map) {\n resultMap.putAll(addMapToResult(newPrefix, (Map<String, Object>) value));\n } else {\n resultMap.put(newPrefix, value.toString());\n }\n }\n return resultMap;\n }\n\n}"
},
{
"identifier": "Config",
"path": "src/main/java/dev/skydynamic/quickbackupmulti/utils/config/Config.java",
"snippet": "public class Config {\n public static QuickBackupMultiConfig INSTANCE = new QuickBackupMultiConfig();\n public static QbmTempConfig TEMP_CONFIG = new QbmTempConfig();\n}"
},
{
"identifier": "restore",
"path": "src/main/java/dev/skydynamic/quickbackupmulti/utils/QbmManager.java",
"snippet": " public static void restore(int slot) {\n File targetBackupSlot = getBackupDir().resolve(\"Slot\" + slot).toFile();\n try {\n// var it = Files.walk(savePath,5).sorted(Comparator.reverseOrder()).iterator();\n// while (it.hasNext()){\n// Files.delete(it.next());\n// }\n for (File file : Objects.requireNonNull(savePath.toFile().listFiles((FilenameFilter) fileFilter))) {\n FileUtils.forceDelete(file);\n }\n FileUtils.copyDirectory(targetBackupSlot, savePath.toFile());\n } catch (IOException e) {\n restore(slot);\n }\n }"
},
{
"identifier": "RegisterCommand",
"path": "src/main/java/dev/skydynamic/quickbackupmulti/command/QuickBackupMultiCommand.java",
"snippet": "public static void RegisterCommand(CommandDispatcher<ServerCommandSource> dispatcher) {\n LiteralCommandNode<ServerCommandSource> QuickBackupMultiShortCommand = dispatcher.register(literal(\"qb\")\n .then(literal(\"list\").executes(it -> listSaveBackups(it.getSource())))\n\n .then(literal(\"make\").requires(me -> me.hasPermissionLevel(2))\n .executes(it -> makeSaveBackup(it.getSource(), -1, \"\"))\n .then(CommandManager.argument(\"slot\", IntegerArgumentType.integer(1))\n .executes(it -> makeSaveBackup(it.getSource(), IntegerArgumentType.getInteger(it, \"slot\"), \"\"))\n .then(CommandManager.argument(\"desc\", StringArgumentType.string())\n .executes(it -> makeSaveBackup(it.getSource(), IntegerArgumentType.getInteger(it, \"slot\"), StringArgumentType.getString(it, \"desc\"))))\n )\n .then(CommandManager.argument(\"desc\", StringArgumentType.string())\n .executes(it -> makeSaveBackup(it.getSource(), -1, StringArgumentType.getString(it, \"desc\"))))\n )\n\n .then(literal(\"back\").requires(me -> me.hasPermissionLevel(2))\n .executes(it -> restoreSaveBackup(it.getSource(), 1))\n .then(CommandManager.argument(\"slot\", IntegerArgumentType.integer(1))\n .executes(it -> restoreSaveBackup(it.getSource(), IntegerArgumentType.getInteger(it, \"slot\")))))\n\n .then(literal(\"confirm\").requires(me -> me.hasPermissionLevel(2))\n .executes(it -> {\n try {\n executeRestore(it.getSource());\n } catch (Exception e) {\n e.printStackTrace();\n }\n return 0;\n }))\n\n .then(literal(\"cancel\").requires(me -> me.hasPermissionLevel(2))\n .executes(it -> cancelRestore(it.getSource())))\n\n .then(literal(\"delete\").requires(me -> me.hasPermissionLevel(2))\n .then(CommandManager.argument(\"slot\", IntegerArgumentType.integer(1))\n .executes(it -> deleteSaveBackup(it.getSource(), IntegerArgumentType.getInteger(it, \"slot\")))))\n\n .then(literal(\"setting\").requires(me -> me.hasPermissionLevel(2))\n .then(literal(\"lang\")\n .then(literal(\"get\").executes(it -> getLang(it.getSource())))\n .then(literal(\"set\").requires(me -> me.hasPermissionLevel(2))\n .then(CommandManager.argument(\"lang\", StringArgumentType.string())\n .suggests(new LangSuggestionProvider())\n .executes(it -> setLang(it.getSource(), StringArgumentType.getString(it, \"lang\"))))))\n .then(literal(\"schedule\")\n .then(literal(\"enable\").executes(it -> enableScheduleBackup(it.getSource())))\n .then(literal(\"disable\").executes(it -> disableScheduleBackup(it.getSource())))\n .then(literal(\"set\")\n .then(literal(\"interval\")\n .then(literal(\"second\")\n .then(CommandManager.argument(\"second\", IntegerArgumentType.integer(1))\n .executes(it -> setScheduleInterval(it.getSource(), IntegerArgumentType.getInteger(it, \"second\"), \"s\"))\n )\n ).then(literal(\"minute\")\n .then(CommandManager.argument(\"minute\", IntegerArgumentType.integer(1))\n .executes(it -> setScheduleInterval(it.getSource(), IntegerArgumentType.getInteger(it, \"minute\"), \"m\"))\n )\n ).then(literal(\"hour\")\n .then(CommandManager.argument(\"hour\", IntegerArgumentType.integer(1))\n .executes(it -> setScheduleInterval(it.getSource(), IntegerArgumentType.getInteger(it, \"hour\"), \"h\"))\n )\n ).then(literal(\"day\")\n .then(CommandManager.argument(\"day\", IntegerArgumentType.integer(1))\n .executes(it -> setScheduleInterval(it.getSource(), IntegerArgumentType.getInteger(it, \"day\"), \"d\"))\n )\n )\n )\n .then(literal(\"cron\")\n .then(CommandManager.argument(\"cron\", StringArgumentType.string())\n .executes(it -> setScheduleCron(it.getSource(), StringArgumentType.getString(it, \"cron\")))))\n .then(literal(\"mode\")\n .then(literal(\"switch\")\n .then(literal(\"interval\")\n .executes(it -> switchMode(it.getSource(), \"interval\")))\n .then(literal(\"cron\")\n .executes(it -> switchMode(it.getSource(), \"cron\"))))\n .then(literal(\"get\").executes(it -> getScheduleMode(it.getSource()))))\n )\n .then(literal(\"get\")\n .executes(it -> getNextBackupTime(it.getSource())))\n )\n )\n );\n\n dispatcher.register(literal(\"quickbackupm\").redirect(QuickBackupMultiShortCommand));\n}"
}
] | import dev.skydynamic.quickbackupmulti.i18n.Translate;
import dev.skydynamic.quickbackupmulti.utils.config.Config;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.ModInitializer;
import net.fabricmc.loader.api.FabricLoader;
import net.fabricmc.fabric.api.command.v2.CommandRegistrationCallback;
import net.fabricmc.fabric.api.event.lifecycle.v1.ServerLifecycleEvents;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static dev.skydynamic.quickbackupmulti.utils.QbmManager.restore;
import static dev.skydynamic.quickbackupmulti.command.QuickBackupMultiCommand.RegisterCommand; | 2,158 | package dev.skydynamic.quickbackupmulti;
//#if MC>=11900
//#else
//$$ import net.fabricmc.fabric.api.command.v1.CommandRegistrationCallback;
//#endif
public final class QuickBackupMulti implements ModInitializer {
public static final Logger LOGGER = LoggerFactory.getLogger("QuickBackupMulti");
EnvType env = FabricLoader.getInstance().getEnvironmentType();
@Override
public void onInitialize() {
Config.INSTANCE.load();
Translate.handleResourceReload(Config.INSTANCE.getLang());
//#if MC>=11900
CommandRegistrationCallback.EVENT.register((dispatcher, registryAccess, environment) -> RegisterCommand(dispatcher));
//#else
//$$ CommandRegistrationCallback.EVENT.register((dispatcher, registryAccess) -> RegisterCommand(dispatcher));
//#endif
ServerLifecycleEvents.SERVER_STARTED.register(server -> {
Config.TEMP_CONFIG.setServerValue(server);
Config.TEMP_CONFIG.setEnv(env);
});
ServerLifecycleEvents.SERVER_STOPPED.register(server -> {
if (Config.TEMP_CONFIG.isBackup) {
if (env == EnvType.SERVER) { | package dev.skydynamic.quickbackupmulti;
//#if MC>=11900
//#else
//$$ import net.fabricmc.fabric.api.command.v1.CommandRegistrationCallback;
//#endif
public final class QuickBackupMulti implements ModInitializer {
public static final Logger LOGGER = LoggerFactory.getLogger("QuickBackupMulti");
EnvType env = FabricLoader.getInstance().getEnvironmentType();
@Override
public void onInitialize() {
Config.INSTANCE.load();
Translate.handleResourceReload(Config.INSTANCE.getLang());
//#if MC>=11900
CommandRegistrationCallback.EVENT.register((dispatcher, registryAccess, environment) -> RegisterCommand(dispatcher));
//#else
//$$ CommandRegistrationCallback.EVENT.register((dispatcher, registryAccess) -> RegisterCommand(dispatcher));
//#endif
ServerLifecycleEvents.SERVER_STARTED.register(server -> {
Config.TEMP_CONFIG.setServerValue(server);
Config.TEMP_CONFIG.setEnv(env);
});
ServerLifecycleEvents.SERVER_STOPPED.register(server -> {
if (Config.TEMP_CONFIG.isBackup) {
if (env == EnvType.SERVER) { | restore(Config.TEMP_CONFIG.backupSlot); | 2 | 2023-12-09 13:51:17+00:00 | 4k |
parmenashp/minecraft-narrator | forge/src/main/java/com/mitsuaky/stanleyparable/screen/ConfigScreen.java | [
{
"identifier": "APICommunicator",
"path": "forge/src/main/java/com/mitsuaky/stanleyparable/APICommunicator.java",
"snippet": "public class APICommunicator {\n private static final String API_URL = \"http://127.0.0.1:5000/\";\n private static final Logger LOGGER = LogManager.getLogger(APICommunicator.class);\n\n public static CompletableFuture<JsonObject> sendRequestAsync(String method, String path, JsonObject event) throws RuntimeException {\n LOGGER.info(\"Making async API call to server: \" + event);\n CompletableFuture<JsonObject> future = CompletableFuture.supplyAsync(() -> sendRequest(method, path, event));\n future.orTimeout(20, TimeUnit.SECONDS);\n return future;\n }\n\n public static JsonObject sendRequest(String method, String path, JsonObject event) throws RuntimeException {\n HttpURLConnection connection = null;\n try {\n connection = initializeConnection(method, path);\n LOGGER.info(\"Sending event to server: \" + event);\n if (event != null) {\n try (OutputStream os = connection.getOutputStream()) {\n byte[] input = event.toString().getBytes(StandardCharsets.UTF_8);\n os.write(input, 0, input.length);\n } catch (Exception ex) {\n throw new RuntimeException(\"Could not send event to server: \" + ex.getMessage(), ex);\n }\n }\n\n try (BufferedReader br = new BufferedReader(\n new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {\n StringBuilder response = new StringBuilder();\n String responseLine;\n while ((responseLine = br.readLine()) != null) {\n response.append(responseLine.trim());\n }\n return JsonParser.parseString(response.toString()).getAsJsonObject();\n } catch (Exception ex) {\n throw new RuntimeException(\"Could not read response from server: \" + ex.getMessage(), ex);\n }\n } catch (Exception ex) {\n throw new RuntimeException(\"Could not send request to server: \" + ex.getMessage(), ex);\n } finally {\n if (connection != null) {\n connection.disconnect();\n }\n }\n }\n\n private static HttpURLConnection initializeConnection(String method, String path) throws Exception {\n URL url = new URL(API_URL + path);\n HttpURLConnection connection = (HttpURLConnection) url.openConnection();\n connection.setRequestMethod(method);\n connection.setRequestProperty(\"Content-Type\", \"application/json; utf-8\");\n connection.setDoOutput(true);\n return connection;\n }\n}"
},
{
"identifier": "ClientConfig",
"path": "forge/src/main/java/com/mitsuaky/stanleyparable/ClientConfig.java",
"snippet": "public class ClientConfig {\n private static final Logger LOGGER = LogManager.getLogger(ClientConfig.class);\n public static final ForgeConfigSpec.Builder BUILDER = new ForgeConfigSpec.Builder();\n public static final ForgeConfigSpec SPEC;\n\n public static final ForgeConfigSpec.ConfigValue<Integer> COOLDOWN_INDIVIDUAL;\n public static final ForgeConfigSpec.ConfigValue<Integer> COOLDOWN_GLOBAL;\n public static final ForgeConfigSpec.ConfigValue<Integer> NARRATOR_VOLUME;\n public static final ForgeConfigSpec.ConfigValue<Boolean> SEND_TO_CHAT;\n public static final ForgeConfigSpec.ConfigValue<Boolean> TTS;\n\n public static final ForgeConfigSpec.ConfigValue<String> OPENAI_API_KEY;\n public static final ForgeConfigSpec.ConfigValue<String> OPENAI_BASE_URL;\n public static final ForgeConfigSpec.ConfigValue<String> OPENAI_MODEL;\n public static final ForgeConfigSpec.ConfigValue<String> ELEVENLABS_API_KEY;\n public static final ForgeConfigSpec.ConfigValue<String> ELEVENLABS_VOICE_ID;\n\n static {\n BUILDER.push(\"Configs for Minecraft Narrator\");\n COOLDOWN_INDIVIDUAL = BUILDER.comment(\"Cooldown for individual events in minutes\").defineInRange(\"cooldown_individual\", 5, 1, 20);\n COOLDOWN_GLOBAL = BUILDER.comment(\"Cooldown for global events in seconds\").defineInRange(\"cooldown_global\", 30, 30, 60);\n NARRATOR_VOLUME = BUILDER.comment(\"Narrator Volume\").defineInRange(\"narrator_volume\", 100, 1, 130);\n SEND_TO_CHAT = BUILDER.comment(\"Send events to chat\").define(\"send_to_chat\", true);\n TTS = BUILDER.comment(\"Enable text to speech\").define(\"tts\", true);\n\n OPENAI_API_KEY = BUILDER.comment(\"OpenAI API Key\").define(\"openai_api_key\", \"\");\n OPENAI_BASE_URL = BUILDER.comment(\"OpenAI Base URL\").define(\"openai_base_url\", \"https://api.openai.com/v1\");\n OPENAI_MODEL = BUILDER.comment(\"OpenAI Model\").define(\"openai_model\", \"gpt-4-1106-preview\");\n ELEVENLABS_API_KEY = BUILDER.comment(\"ElevenLabs API Key\").define(\"elevenlabs_api_key\", \"\");\n ELEVENLABS_VOICE_ID = BUILDER.comment(\"ElevenLabs Voice ID/Name\").define(\"elevenlabs_voice_id\", \"\");\n\n BUILDER.pop();\n SPEC = BUILDER.build();\n }\n\n public static void applyServerConfig() {\n JsonObject request = new JsonObject();\n try {\n request.addProperty(\"cooldown_individual\", COOLDOWN_INDIVIDUAL.get());\n request.addProperty(\"cooldown_global\", COOLDOWN_GLOBAL.get());\n request.addProperty(\"narrator_volume\", NARRATOR_VOLUME.get());\n request.addProperty(\"tts\", TTS.get());\n request.addProperty(\"openai_api_key\", OPENAI_API_KEY.get());\n request.addProperty(\"openai_base_url\", OPENAI_BASE_URL.get());\n request.addProperty(\"openai_model\", OPENAI_MODEL.get());\n request.addProperty(\"elevenlabs_api_key\", ELEVENLABS_API_KEY.get());\n request.addProperty(\"elevenlabs_voice_id\", ELEVENLABS_VOICE_ID.get());\n APICommunicator.sendRequestAsync(\"POST\", \"config\", request);\n } catch (Exception ex) {\n LOGGER.error(\"Could not send config to server: \" + ex.getMessage(), ex);\n }\n }\n}"
},
{
"identifier": "PingWidget",
"path": "forge/src/main/java/com/mitsuaky/stanleyparable/screen/widget/PingWidget.java",
"snippet": "@OnlyIn(Dist.CLIENT)\npublic class PingWidget extends AbstractButton {\n protected static final WidgetSprites BUTTON_SPRITES = new WidgetSprites(new ResourceLocation(\"widget/button\"), new ResourceLocation(\"widget/button_disabled\"), new ResourceLocation(\"widget/button_highlighted\"));\n protected static final ResourceLocation RESTART_ICON = new ResourceLocation(\"stanleyparable\",\"widget/restart_icon\");\n\n public PingWidget(int pX, int pY, int pWidth, int pHeight, Component pMessage) {\n super(pX, pY, pWidth, pHeight, pMessage);\n }\n\n public void onClick(double pMouseX, double pMouseY) {\n this.onPress();\n }\n\n public void renderWidget(GuiGraphics pGuiGraphics, int pMouseX, int pMouseY, float pPartialTick) {\n Minecraft minecraft = Minecraft.getInstance();\n RenderSystem.enableBlend();\n RenderSystem.enableDepthTest();\n pGuiGraphics.setColor(1.0F, 1.0F, 1.0F, this.alpha);\n pGuiGraphics.blitSprite(BUTTON_SPRITES.get(this.active, this.isHoveredOrFocused()), this.getX(), this.getY(), 20, this.getHeight());\n pGuiGraphics.blitSprite(RESTART_ICON, this.getX() + 2, this.getY() + 2, 16, 16);\n pGuiGraphics.setColor(1.0F, 1.0F, 1.0F, 1.0F);\n pGuiGraphics.drawString(minecraft.font, this.getMessage(), this.getX() + 24, this.getY() + (this.height - 8) / 2, 14737632 | Mth.ceil(this.alpha * 255.0F) << 24);\n }\n\n public boolean keyPressed(int pKeyCode, int pScanCode, int pModifiers) {\n if (this.active && this.visible) {\n if (CommonInputs.selected(pKeyCode)) {\n this.playDownSound(Minecraft.getInstance().getSoundManager());\n this.onPress();\n return true;\n } else {\n return false;\n }\n } else {\n return false;\n }\n }\n\n public void updateWidgetNarration(@NotNull NarrationElementOutput pNarrationElementOutput) {\n this.defaultButtonNarrationText(pNarrationElementOutput);\n }\n\n public void onPress() {}\n}"
}
] | import com.google.gson.JsonObject;
import com.mitsuaky.stanleyparable.APICommunicator;
import com.mitsuaky.stanleyparable.ClientConfig;
import com.mitsuaky.stanleyparable.screen.widget.PingWidget;
import net.minecraft.client.gui.GuiGraphics;
import net.minecraft.client.gui.components.AbstractSliderButton;
import net.minecraft.client.gui.components.Button;
import net.minecraft.client.gui.components.Checkbox;
import net.minecraft.client.gui.screens.Screen;
import net.minecraft.network.chat.Component;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jetbrains.annotations.NotNull;
import java.awt.*; | 2,291 | package com.mitsuaky.stanleyparable.screen;
@OnlyIn(Dist.CLIENT)
public class ConfigScreen extends Screen {
private static final Logger LOGGER = LogManager.getLogger(ConfigScreen.class);
private final Screen parent;
private final int commonWidth = 200;
private final int commonHeight = 20;
private int coolDownIndividual = ClientConfig.COOLDOWN_INDIVIDUAL.get();
private int coolDownGlobal = ClientConfig.COOLDOWN_GLOBAL.get();
private int narratorVolume = ClientConfig.NARRATOR_VOLUME.get();
private boolean sendToChat = ClientConfig.SEND_TO_CHAT.get();
private boolean tts = ClientConfig.TTS.get();
private String ping = "Offline";
private PingWidget pingWidget;
public ConfigScreen(Screen parent) {
super(Component.translatable("gui.stanleyparable.config.title"));
this.parent = parent;
}
@Override
protected void init() {
super.init();
long time = System.currentTimeMillis(); | package com.mitsuaky.stanleyparable.screen;
@OnlyIn(Dist.CLIENT)
public class ConfigScreen extends Screen {
private static final Logger LOGGER = LogManager.getLogger(ConfigScreen.class);
private final Screen parent;
private final int commonWidth = 200;
private final int commonHeight = 20;
private int coolDownIndividual = ClientConfig.COOLDOWN_INDIVIDUAL.get();
private int coolDownGlobal = ClientConfig.COOLDOWN_GLOBAL.get();
private int narratorVolume = ClientConfig.NARRATOR_VOLUME.get();
private boolean sendToChat = ClientConfig.SEND_TO_CHAT.get();
private boolean tts = ClientConfig.TTS.get();
private String ping = "Offline";
private PingWidget pingWidget;
public ConfigScreen(Screen parent) {
super(Component.translatable("gui.stanleyparable.config.title"));
this.parent = parent;
}
@Override
protected void init() {
super.init();
long time = System.currentTimeMillis(); | APICommunicator.sendRequestAsync("GET", "ping", null).whenComplete((response, throwable) -> { | 0 | 2023-12-13 18:51:41+00:00 | 4k |
quentin452/Garden-Stuff-Continuation | src/main/resources/com/jaquadro/minecraft/gardentrees/integration/TwilightForestIntegration.java | [
{
"identifier": "SaplingRegistry",
"path": "src/main/java/com/jaquadro/minecraft/gardencore/api/SaplingRegistry.java",
"snippet": "public final class SaplingRegistry {\n\n private final UniqueMetaRegistry registry = new UniqueMetaRegistry();\n private static final SaplingRegistry instance = new SaplingRegistry();\n\n public static SaplingRegistry instance() {\n return instance;\n }\n\n private SaplingRegistry() {\n Item sapling = Item.getItemFromBlock(Blocks.sapling);\n this.registerSapling(sapling, 0, Blocks.log, 0, Blocks.leaves, 0);\n this.registerSapling(sapling, 1, Blocks.log, 1, Blocks.leaves, 1);\n this.registerSapling(sapling, 2, Blocks.log, 2, Blocks.leaves, 2);\n this.registerSapling(sapling, 3, Blocks.log, 3, Blocks.leaves, 3);\n this.registerSapling(sapling, 4, Blocks.log2, 0, Blocks.leaves2, 0);\n this.registerSapling(sapling, 5, Blocks.log2, 1, Blocks.leaves2, 1);\n }\n\n public void registerSapling(Item sapling, int saplingMeta, Block wood, int woodMeta, Block leaf, int leafMeta) {\n if (sapling != null && wood != null && leaf != null) {\n this.registerSapling(\n ModItems.getUniqueMetaID(sapling, saplingMeta),\n ModBlocks.getUniqueMetaID(wood, woodMeta),\n ModBlocks.getUniqueMetaID(leaf, leafMeta));\n }\n }\n\n public void registerSapling(UniqueMetaIdentifier sapling, UniqueMetaIdentifier wood, UniqueMetaIdentifier leaf) {\n SaplingRegistry.SaplingRecord record = new SaplingRegistry.SaplingRecord();\n record.saplingType = sapling;\n record.woodType = wood;\n record.leafType = leaf;\n this.registry.register(sapling, record);\n }\n\n public UniqueMetaIdentifier getLeavesForSapling(Item sapling) {\n return this.getLeavesForSapling(sapling, 32767);\n }\n\n public UniqueMetaIdentifier getLeavesForSapling(Item sapling, int saplingMeta) {\n return this.getLeavesForSapling(ModItems.getUniqueMetaID(sapling, saplingMeta));\n }\n\n public UniqueMetaIdentifier getLeavesForSapling(UniqueMetaIdentifier sapling) {\n SaplingRegistry.SaplingRecord record = (SaplingRegistry.SaplingRecord) this.registry.getEntry(sapling);\n return record == null ? null : record.leafType;\n }\n\n public UniqueMetaIdentifier getWoodForSapling(Item sapling) {\n return this.getWoodForSapling(sapling, 32767);\n }\n\n public UniqueMetaIdentifier getWoodForSapling(Item sapling, int saplingMeta) {\n return this.getWoodForSapling(ModItems.getUniqueMetaID(sapling, saplingMeta));\n }\n\n public UniqueMetaIdentifier getWoodForSapling(UniqueMetaIdentifier sapling) {\n SaplingRegistry.SaplingRecord record = (SaplingRegistry.SaplingRecord) this.registry.getEntry(sapling);\n return record == null ? null : record.woodType;\n }\n\n public Object getExtendedData(Item sapling, String key) {\n return this.getExtendedData(sapling, 32767, key);\n }\n\n public Object getExtendedData(Item sapling, int saplingMeta, String key) {\n return this.getExtendedData(ModItems.getUniqueMetaID(sapling, saplingMeta), key);\n }\n\n public Object getExtendedData(UniqueMetaIdentifier sapling, String key) {\n SaplingRegistry.SaplingRecord record = (SaplingRegistry.SaplingRecord) this.registry.getEntry(sapling);\n return record == null ? null : record.extraData.get(key);\n }\n\n public void putExtendedData(Item sapling, String key, Object data) {\n this.putExtendedData(sapling, 32767, key, data);\n }\n\n public void putExtendedData(Item sapling, int saplingMeta, String key, Object data) {\n this.putExtendedData(ModItems.getUniqueMetaID(sapling, saplingMeta), key, data);\n }\n\n public void putExtendedData(UniqueMetaIdentifier sapling, String key, Object data) {\n SaplingRegistry.SaplingRecord record = (SaplingRegistry.SaplingRecord) this.registry.getEntry(sapling);\n if (record == null) {\n this.registerSapling(sapling, (UniqueMetaIdentifier) null, (UniqueMetaIdentifier) null);\n record = (SaplingRegistry.SaplingRecord) this.registry.getEntry(sapling);\n }\n\n record.extraData.put(key, data);\n }\n\n private static class SaplingRecord {\n\n public UniqueMetaIdentifier saplingType;\n public UniqueMetaIdentifier woodType;\n public UniqueMetaIdentifier leafType;\n public HashMap extraData;\n\n private SaplingRecord() {\n this.extraData = new HashMap();\n }\n\n // $FF: synthetic method\n SaplingRecord(Object x0) {\n this();\n }\n }\n}"
},
{
"identifier": "UniqueMetaIdentifier",
"path": "src/main/java/com/jaquadro/minecraft/gardencore/util/UniqueMetaIdentifier.java",
"snippet": "public final class UniqueMetaIdentifier {\n\n public final String modId;\n public final String name;\n public final int meta;\n private UniqueIdentifier cachedUID;\n\n public UniqueMetaIdentifier(String modId, String name) {\n this.modId = modId;\n this.name = name;\n this.meta = 32767;\n }\n\n public UniqueMetaIdentifier(String modId, String name, int meta) {\n this.modId = modId;\n this.name = name;\n this.meta = meta;\n }\n\n public UniqueMetaIdentifier(String qualifiedName, int meta) {\n String[] parts = qualifiedName.split(\":\");\n this.modId = parts[0];\n this.name = parts[1];\n this.meta = meta;\n }\n\n public UniqueMetaIdentifier(String compoundName) {\n String[] parts1 = compoundName.split(\";\");\n String[] parts2 = parts1[0].split(\":\");\n this.modId = parts2[0];\n if (parts2.length >= 2) {\n this.name = parts2[1];\n } else {\n this.name = \"\";\n }\n\n if (parts1.length >= 2) {\n this.meta = Integer.parseInt(parts1[1]);\n } else if (parts2.length > 2) {\n this.meta = Integer.parseInt(parts2[parts2.length - 1]);\n } else {\n this.meta = 32767;\n }\n\n }\n\n public UniqueMetaIdentifier(String compoundName, char separator) {\n String[] parts1 = compoundName.split(\"[ ]*\" + separator + \"[ ]*\");\n String[] parts2 = parts1[0].split(\":\");\n this.modId = parts2[0];\n if (parts2.length >= 2) {\n this.name = parts2[1];\n } else {\n this.name = \"\";\n }\n\n if (parts1.length >= 2) {\n this.meta = Integer.parseInt(parts1[1]);\n } else {\n this.meta = 32767;\n }\n\n }\n\n public UniqueIdentifier getUniqueIdentifier() {\n if (this.cachedUID == null) {\n this.cachedUID = new UniqueIdentifier(this.modId + \":\" + this.name);\n }\n\n return this.cachedUID;\n }\n\n public Block getBlock() {\n return GameRegistry.findBlock(this.modId, this.name);\n }\n\n public Item getItem() {\n return GameRegistry.findItem(this.modId, this.name);\n }\n\n public boolean equals(Object obj) {\n if (obj == null) {\n return false;\n } else if (obj.getClass() != this.getClass()) {\n return false;\n } else {\n UniqueMetaIdentifier other = (UniqueMetaIdentifier) obj;\n return Objects.equal(this.modId, other.modId) && Objects.equal(this.name, other.name)\n && this.meta == other.meta;\n }\n }\n\n public int hashCode() {\n return Objects.hashCode(new Object[] { this.modId, this.name }) ^ this.meta * 37;\n }\n\n public String toString() {\n return String.format(\"%s:%s;%d\", this.modId, this.name, this.meta);\n }\n\n public static UniqueMetaIdentifier createFor(ItemStack itemStack) {\n if (itemStack.getItem() == null) {\n return null;\n } else {\n String name = GameData.getItemRegistry()\n .getNameForObject(itemStack.getItem());\n return new UniqueMetaIdentifier(name, itemStack.getItemDamage());\n }\n }\n\n public static UniqueMetaIdentifier createFor(Block block, int meta) {\n if (block == null) {\n return null;\n } else {\n String name = GameData.getBlockRegistry()\n .getNameForObject(block);\n return new UniqueMetaIdentifier(name, meta);\n }\n }\n\n public static UniqueMetaIdentifier createFor(Block block) {\n if (block == null) {\n return null;\n } else {\n String name = GameData.getBlockRegistry()\n .getNameForObject(block);\n return new UniqueMetaIdentifier(name);\n }\n }\n}"
},
{
"identifier": "OrnamentalTreeFactory",
"path": "src/main/java/com/jaquadro/minecraft/gardentrees/world/gen/OrnamentalTreeFactory.java",
"snippet": "public interface OrnamentalTreeFactory {\n\n WorldGenOrnamentalTree create(Block var1, int var2, Block var3, int var4);\n}"
},
{
"identifier": "OrnamentalTreeRegistry",
"path": "src/main/java/com/jaquadro/minecraft/gardentrees/world/gen/OrnamentalTreeRegistry.java",
"snippet": "public class OrnamentalTreeRegistry {\n\n private static Map registry = new HashMap();\n\n public static void registerTree(String name, OrnamentalTreeFactory treeFactory) {\n registry.put(name, treeFactory);\n }\n\n public static OrnamentalTreeFactory getTree(String name) {\n return (OrnamentalTreeFactory) registry.get(name);\n }\n\n static {\n registerTree(\"small_oak\", WorldGenStandardOrnTree.SmallOakTree.FACTORY);\n registerTree(\"small_spruce\", WorldGenStandardOrnTree.SmallSpruceTree.FACTORY);\n registerTree(\"small_jungle\", WorldGenStandardOrnTree.SmallJungleTree.FACTORY);\n registerTree(\"small_acacia\", WorldGenStandardOrnTree.SmallAcaciaTree.FACTORY);\n registerTree(\"small_palm\", WorldGenStandardOrnTree.SmallPalmTree.FACTORY);\n registerTree(\"small_willow\", WorldGenStandardOrnTree.SmallWillowTree.FACTORY);\n registerTree(\"small_pine\", WorldGenStandardOrnTree.SmallPineTree.FACTORY);\n registerTree(\"small_mahogany\", WorldGenStandardOrnTree.SmallMahoganyTree.FACTORY);\n registerTree(\"small_shrub\", WorldGenStandardOrnTree.SmallShrubTree.FACTORY);\n registerTree(\"small_canopy\", WorldGenStandardOrnTree.SmallCanopyTree.FACTORY);\n registerTree(\"small_cyprus\", WorldGenStandardOrnTree.SmallCyprusTree.FACTORY);\n registerTree(\"tall_small_oak\", WorldGenStandardOrnTree.TallSmallOakTree.FACTORY);\n registerTree(\"large_oak\", WorldGenStandardOrnTree.LargeOakTree.FACTORY);\n registerTree(\"large_spruce\", WorldGenStandardOrnTree.LargeSpruceTree.FACTORY);\n }\n}"
}
] | import com.jaquadro.minecraft.gardencore.api.SaplingRegistry;
import com.jaquadro.minecraft.gardencore.util.UniqueMetaIdentifier;
import com.jaquadro.minecraft.gardentrees.world.gen.OrnamentalTreeFactory;
import com.jaquadro.minecraft.gardentrees.world.gen.OrnamentalTreeRegistry;
import cpw.mods.fml.common.Loader;
import cpw.mods.fml.common.registry.GameRegistry;
import net.minecraft.item.Item;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry; | 3,307 | package com.jaquadro.minecraft.gardentrees.integration;
public class TwilightForestIntegration {
public static final String MOD_ID = "TwilightForest";
public static void init() {
if (Loader.isModLoaded("TwilightForest")) {
Map saplingBank1 = new HashMap();
saplingBank1.put("small_oak", new int[]{0, 7, 8, 9});
saplingBank1.put("large_oak", new int[]{4, 5});
saplingBank1.put("small_canopy", new int[]{1, 2, 3, 6});
Map banks = new HashMap();
banks.put(Item.getItemFromBlock(GameRegistry.findBlock("TwilightForest", "tile.TFSapling")), saplingBank1);
SaplingRegistry saplingReg = SaplingRegistry.instance();
Iterator var3 = banks.entrySet().iterator();
label43:
while(var3.hasNext()) {
Entry entry = (Entry)var3.next();
Item sapling = (Item)entry.getKey();
Iterator var6 = ((Map)entry.getValue()).entrySet().iterator();
while(true) {
Entry bankEntry;
OrnamentalTreeFactory factory;
do {
if (!var6.hasNext()) {
continue label43;
}
bankEntry = (Entry)var6.next();
factory = OrnamentalTreeRegistry.getTree((String)bankEntry.getKey());
} while(factory == null);
int[] var9 = (int[])bankEntry.getValue();
int var10 = var9.length;
for(int var11 = 0; var11 < var10; ++var11) {
int i = var9[var11]; | package com.jaquadro.minecraft.gardentrees.integration;
public class TwilightForestIntegration {
public static final String MOD_ID = "TwilightForest";
public static void init() {
if (Loader.isModLoaded("TwilightForest")) {
Map saplingBank1 = new HashMap();
saplingBank1.put("small_oak", new int[]{0, 7, 8, 9});
saplingBank1.put("large_oak", new int[]{4, 5});
saplingBank1.put("small_canopy", new int[]{1, 2, 3, 6});
Map banks = new HashMap();
banks.put(Item.getItemFromBlock(GameRegistry.findBlock("TwilightForest", "tile.TFSapling")), saplingBank1);
SaplingRegistry saplingReg = SaplingRegistry.instance();
Iterator var3 = banks.entrySet().iterator();
label43:
while(var3.hasNext()) {
Entry entry = (Entry)var3.next();
Item sapling = (Item)entry.getKey();
Iterator var6 = ((Map)entry.getValue()).entrySet().iterator();
while(true) {
Entry bankEntry;
OrnamentalTreeFactory factory;
do {
if (!var6.hasNext()) {
continue label43;
}
bankEntry = (Entry)var6.next();
factory = OrnamentalTreeRegistry.getTree((String)bankEntry.getKey());
} while(factory == null);
int[] var9 = (int[])bankEntry.getValue();
int var10 = var9.length;
for(int var11 = 0; var11 < var10; ++var11) {
int i = var9[var11]; | UniqueMetaIdentifier woodBlock = saplingReg.getWoodForSapling(sapling, i); | 1 | 2023-12-12 08:13:16+00:00 | 4k |
joyheros/realworld | app-main/src/test/java/io/zhifou/realworld/auth/application/service/impl/ProfileServiceImplTest.java | [
{
"identifier": "FollowRelation",
"path": "app-permission/src/main/java/io/zhifou/realworld/auth/domain/FollowRelation.java",
"snippet": "public class FollowRelation {\n\tprivate Long userId;\n\tprivate Long targetId;\n\n\tpublic FollowRelation() {\n\t}\n\n\tpublic FollowRelation(Long userId, Long targetId) {\n\t\tthis.userId = userId;\n\t\tthis.targetId = targetId;\n\t}\n\n\t/**\n\t * @return the userId\n\t */\n\tpublic Long getUserId() {\n\t\treturn userId;\n\t}\n\n\t/**\n\t * @param userId the userId to set\n\t */\n\tpublic void setUserId(Long userId) {\n\t\tthis.userId = userId;\n\t}\n\n\t/**\n\t * @return the targetId\n\t */\n\tpublic Long getTargetId() {\n\t\treturn targetId;\n\t}\n\n\t/**\n\t * @param targetId the targetId to set\n\t */\n\tpublic void setTargetId(Long targetId) {\n\t\tthis.targetId = targetId;\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\treturn obj instanceof FollowRelation other && Objects.equals(this.userId, other.userId)\n\t\t\t\t&& Objects.equals(this.targetId, other.targetId);\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\treturn Objects.hash(this.userId, this.targetId);\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"FollowRelation {\" + \"userId=\" + userId + \", targetId=\" + targetId + \"}\";\n\t}\n}"
},
{
"identifier": "User",
"path": "app-permission/src/main/java/io/zhifou/realworld/auth/domain/User.java",
"snippet": "public class User {\n\tprivate Long id;\n\tprivate String email;\n\tprivate String username;\n\tprivate String password;\n\tprivate String bio;\n\tprivate String image;\n\n\tpublic User() {\n\t}\n\n\tpublic User(String email, String username, String password) {\n\t\tthis.email = email;\n\t\tthis.username = username;\n\t\tthis.password = password;\n\t\tthis.bio = \"\";\n\t\tthis.image = \"\";\n\t}\n\n\tpublic User(String email, String username, String password, String bio, String image) {\n\t\tthis.email = email;\n\t\tthis.username = username;\n\t\tthis.password = password;\n\t\tthis.bio = bio;\n\t\tthis.image = image;\n\t}\n\n\tpublic void update(String email, String username, String password, String bio, String image) {\n\t\tif (!email.isBlank()) {\n\t\t\tthis.email = email;\n\t\t}\n\t\tif (!username.isBlank()) {\n\t\t\tthis.username = username;\n\t\t}\n\t\tif (!password.isBlank()) {\n\t\t\tthis.password = password;\n\t\t}\n\t\tif (!bio.isBlank()) {\n\t\t\tthis.bio = bio;\n\t\t}\n\t\tif (!image.isBlank()) {\n\t\t\tthis.image = image;\n\t\t}\n\t}\n\n\t/**\n\t * @return the id\n\t */\n\tpublic Long getId() {\n\t\treturn id;\n\t}\n\n\t/**\n\t * @param id the id to set\n\t */\n\tpublic void setId(Long id) {\n\t\tthis.id = id;\n\t}\n\n\t/**\n\t * @return the email\n\t */\n\tpublic String getEmail() {\n\t\treturn email;\n\t}\n\n\t/**\n\t * @param email the email to set\n\t */\n\tpublic void setEmail(String email) {\n\t\tthis.email = email;\n\t}\n\n\t/**\n\t * @return the username\n\t */\n\tpublic String getUsername() {\n\t\treturn username;\n\t}\n\n\t/**\n\t * @param username the username to set\n\t */\n\tpublic void setUsername(String username) {\n\t\tthis.username = username;\n\t}\n\n\t/**\n\t * @return the password\n\t */\n\tpublic String getPassword() {\n\t\treturn password;\n\t}\n\n\t/**\n\t * @param password the password to set\n\t */\n\tpublic void setPassword(String password) {\n\t\tthis.password = password;\n\t}\n\n\t/**\n\t * @return the bio\n\t */\n\tpublic String getBio() {\n\t\treturn bio;\n\t}\n\n\t/**\n\t * @param bio the bio to set\n\t */\n\tpublic void setBio(String bio) {\n\t\tthis.bio = bio;\n\t}\n\n\t/**\n\t * @return the image\n\t */\n\tpublic String getImage() {\n\t\tif (image == null || \"\".equals(image)) {\n\t\t\timage = \"https://static.productionready.io/images/smiley-cyrus.jpg\";\n\t\t}\n\t\treturn image;\n\t}\n\n\t/**\n\t * @param image the image to set\n\t */\n\tpublic void setImage(String image) {\n\t\tthis.image = image;\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\treturn obj instanceof User other && Objects.equals(this.id, other.id)\n\t\t\t\t&& Objects.equals(this.username, other.username) && Objects.equals(this.email, other.email);\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\treturn Objects.hash(this.id, this.username, this.email);\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"User {\" + \"id=\" + id + \", username='\" + username + \"', email='\" + email + \"'}\";\n\t}\n}"
},
{
"identifier": "UserProvider",
"path": "app-permission/src/main/java/io/zhifou/realworld/auth/domain/support/UserProvider.java",
"snippet": "@Repository\npublic interface UserProvider {\n\tOptional<User> save(User user);\n\n\tOptional<User> findById(Long id);\n\n\tOptional<User> findByUsername(String username);\n\n\tOptional<User> findByEmail(String email);\n\n\tvoid saveRelation(FollowRelation followRelation);\n\n\tOptional<FollowRelation> findRelation(Long userId, Long targetId);\n\n\tvoid removeRelation(FollowRelation followRelation);\n}"
}
] | import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.when;
import java.util.Optional;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import io.zhifou.realworld.auth.application.data.ProfileData;
import io.zhifou.realworld.auth.domain.FollowRelation;
import io.zhifou.realworld.auth.domain.User;
import io.zhifou.realworld.auth.domain.support.UserProvider;
| 1,991 | package io.zhifou.realworld.auth.application.service.impl;
@ExtendWith(MockitoExtension.class)
class ProfileServiceImplTest {
private ProfileServiceImpl profileService;
@Mock
private UserProvider userProvider;
@BeforeEach
void setUp() throws Exception {
this.profileService = new ProfileServiceImpl(userProvider);
}
@AfterEach
void tearDown() throws Exception {
}
@Test
void testGetProfileUserLong() {
when(userProvider.findById(anyLong())).thenReturn(Optional.of(userEntity()));
when(userProvider.findRelation(any(), any())).thenReturn(Optional.of(follow()));
ProfileData actual = profileService.getProfile(userEntity(), anyLong());
assertEquals(userEntity().getUsername(), actual.username());
assertEquals(userEntity().getBio(), actual.bio());
assertTrue(actual.following());
}
@Test
void testGetProfileUserString() {
when(userProvider.findByUsername(anyString())).thenReturn(Optional.of(userEntity()));
when(userProvider.findRelation(any(), any())).thenReturn(Optional.of(follow()));
ProfileData actual = profileService.getProfile(userEntity(), anyString());
assertEquals(userEntity().getUsername(), actual.username());
assertEquals(userEntity().getBio(), actual.bio());
assertTrue(actual.following());
}
@Test
void testFollow() {
when(userProvider.findByUsername(anyString())).thenReturn(Optional.of(userEntity()));
when(userProvider.findRelation(any(), any())).thenReturn(Optional.empty());
ProfileData actual = profileService.follow(userEntity(), anyString());
assertTrue(actual.following());
}
@Test
void testUnfollow() {
when(userProvider.findByUsername(anyString())).thenReturn(Optional.of(userEntity()));
when(userProvider.findRelation(any(), any())).thenReturn(Optional.of(follow()));
ProfileData actual = profileService.unfollow(userEntity(), anyString());
assertFalse(actual.following());
}
| package io.zhifou.realworld.auth.application.service.impl;
@ExtendWith(MockitoExtension.class)
class ProfileServiceImplTest {
private ProfileServiceImpl profileService;
@Mock
private UserProvider userProvider;
@BeforeEach
void setUp() throws Exception {
this.profileService = new ProfileServiceImpl(userProvider);
}
@AfterEach
void tearDown() throws Exception {
}
@Test
void testGetProfileUserLong() {
when(userProvider.findById(anyLong())).thenReturn(Optional.of(userEntity()));
when(userProvider.findRelation(any(), any())).thenReturn(Optional.of(follow()));
ProfileData actual = profileService.getProfile(userEntity(), anyLong());
assertEquals(userEntity().getUsername(), actual.username());
assertEquals(userEntity().getBio(), actual.bio());
assertTrue(actual.following());
}
@Test
void testGetProfileUserString() {
when(userProvider.findByUsername(anyString())).thenReturn(Optional.of(userEntity()));
when(userProvider.findRelation(any(), any())).thenReturn(Optional.of(follow()));
ProfileData actual = profileService.getProfile(userEntity(), anyString());
assertEquals(userEntity().getUsername(), actual.username());
assertEquals(userEntity().getBio(), actual.bio());
assertTrue(actual.following());
}
@Test
void testFollow() {
when(userProvider.findByUsername(anyString())).thenReturn(Optional.of(userEntity()));
when(userProvider.findRelation(any(), any())).thenReturn(Optional.empty());
ProfileData actual = profileService.follow(userEntity(), anyString());
assertTrue(actual.following());
}
@Test
void testUnfollow() {
when(userProvider.findByUsername(anyString())).thenReturn(Optional.of(userEntity()));
when(userProvider.findRelation(any(), any())).thenReturn(Optional.of(follow()));
ProfileData actual = profileService.unfollow(userEntity(), anyString());
assertFalse(actual.following());
}
| private User userEntity() {
| 1 | 2023-12-14 07:28:49+00:00 | 4k |
swallez/elasticsearch-genai-demo | src/main/java/co/elastic/examples/Components.java | [
{
"identifier": "OllamaEmbeddingModel",
"path": "src/main/java-lc4j/dev/langchain4j/model/ollama/OllamaEmbeddingModel.java",
"snippet": "public class OllamaEmbeddingModel implements EmbeddingModel {\n\n private final OllamaClient client;\n private final String modelName;\n private final Integer maxRetries;\n\n @Builder\n public OllamaEmbeddingModel(String baseUrl, Duration timeout,\n String modelName, Integer maxRetries) {\n this.client = OllamaClient.builder().baseUrl(baseUrl).timeout(timeout).build();\n this.modelName = modelName;\n this.maxRetries = getOrDefault(maxRetries, 3);\n }\n\n @Override\n public Response<List<Embedding>> embedAll(List<TextSegment> textSegments) {\n List<Embedding> embeddings = new ArrayList<>();\n textSegments.forEach(textSegment -> {\n EmbeddingRequest request = EmbeddingRequest.builder()\n .model(modelName)\n .prompt(textSegment.text())\n .build();\n\n EmbeddingResponse response = withRetry(() -> client.embed(request), maxRetries);\n embeddings.add(new Embedding(response.getEmbedding()));\n });\n\n return Response.from(embeddings);\n }\n}"
},
{
"identifier": "OllamaStreamingLanguageModel",
"path": "src/main/java-lc4j/dev/langchain4j/model/ollama/OllamaStreamingLanguageModel.java",
"snippet": "public class OllamaStreamingLanguageModel implements StreamingLanguageModel {\n\n private final OllamaClient client;\n private final String modelName;\n private final Double temperature;\n\n @Builder\n public OllamaStreamingLanguageModel(String baseUrl, Duration timeout,\n String modelName, Double temperature) {\n this.client = OllamaClient.builder().baseUrl(baseUrl).timeout(timeout).build();\n this.modelName = modelName;\n this.temperature = getOrDefault(temperature, 0.7);\n }\n\n @Override\n public void generate(String prompt, StreamingResponseHandler<String> handler) {\n CompletionRequest request = CompletionRequest.builder()\n .model(modelName)\n .prompt(prompt)\n .options(Options.builder()\n .temperature(temperature)\n .build())\n .stream(true)\n .build();\n\n client.streamingCompletion(request, handler);\n }\n}"
},
{
"identifier": "ElasticsearchEmbeddingStore",
"path": "src/main/java-lc4j/dev/langchain4j/store/embedding/elasticsearch/ElasticsearchEmbeddingStore.java",
"snippet": "public class ElasticsearchEmbeddingStore implements EmbeddingStore<TextSegment> {\n\n private static final Logger log = LoggerFactory.getLogger(ElasticsearchEmbeddingStore.class);\n\n private final ElasticsearchClient client;\n private final String indexName;\n private final ObjectMapper objectMapper;\n\n /**\n * Creates an instance of ElasticsearchEmbeddingStore.\n *\n * @param serverUrl Elasticsearch Server URL (mandatory)\n * @param apiKey Elasticsearch API key (optional)\n * @param userName Elasticsearch userName (optional)\n * @param password Elasticsearch password (optional)\n * @param indexName Elasticsearch index name (optional). Default value: \"default\".\n * Index will be created automatically if not exists.\n * @param dimension Embedding vector dimension (mandatory when index does not exist yet).\n */\n public ElasticsearchEmbeddingStore(String serverUrl,\n String apiKey,\n String userName,\n String password,\n String indexName,\n Integer dimension) {\n\n RestClientBuilder restClientBuilder = RestClient\n .builder(HttpHost.create(ensureNotNull(serverUrl, \"serverUrl\")));\n\n if (!isNullOrBlank(userName)) {\n CredentialsProvider provider = new BasicCredentialsProvider();\n provider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(userName, password));\n restClientBuilder.setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setDefaultCredentialsProvider(provider));\n }\n\n if (!isNullOrBlank(apiKey)) {\n restClientBuilder.setDefaultHeaders(new Header[]{\n new BasicHeader(\"Authorization\", \"Apikey \" + apiKey)\n });\n }\n\n ElasticsearchTransport transport = new RestClientTransport(restClientBuilder.build(), new JacksonJsonpMapper());\n\n this.client = new ElasticsearchClient(transport);\n this.indexName = ensureNotNull(indexName, \"indexName\");\n this.objectMapper = new ObjectMapper();\n\n createIndexIfNotExist(indexName, dimension);\n }\n\n public ElasticsearchEmbeddingStore(ElasticsearchClient client, String indexName, Integer dimension) {\n this.client = client;\n this.indexName = ensureNotNull(indexName, \"indexName\");\n this.objectMapper = new ObjectMapper();\n\n createIndexIfNotExist(indexName, dimension);\n }\n\n public ElasticsearchEmbeddingStore(RestClient restClient, String indexName, Integer dimension) {\n this(new ElasticsearchClient(new RestClientTransport(restClient, new JacksonJsonpMapper())), indexName, dimension);\n }\n\n public static Builder builder() {\n return new Builder();\n }\n\n public static class Builder {\n\n private String serverUrl;\n private String apiKey;\n private String userName;\n private String password;\n private RestClient restClient;\n private String indexName = \"default\";\n private Integer dimension;\n\n /**\n * @param serverUrl Elasticsearch Server URL\n * @return builder\n */\n public Builder serverUrl(String serverUrl) {\n this.serverUrl = serverUrl;\n return this;\n }\n\n /**\n * @param apiKey Elasticsearch API key (optional)\n * @return builder\n */\n public Builder apiKey(String apiKey) {\n this.apiKey = apiKey;\n return this;\n }\n\n /**\n * @param userName Elasticsearch userName (optional)\n * @return builder\n */\n public Builder userName(String userName) {\n this.userName = userName;\n return this;\n }\n\n /**\n * @param password Elasticsearch password (optional)\n * @return builder\n */\n public Builder password(String password) {\n this.password = password;\n return this;\n }\n\n /**\n * @param restClient Elasticsearch RestClient (optional).\n * Effectively overrides all other connection parameters like serverUrl, etc.\n * @return builder\n */\n public Builder restClient(RestClient restClient) {\n this.restClient = restClient;\n return this;\n }\n\n /**\n * @param indexName Elasticsearch index name (optional). Default value: \"default\".\n * Index will be created automatically if not exists.\n * @return builder\n */\n public Builder indexName(String indexName) {\n this.indexName = indexName;\n return this;\n }\n\n /**\n * @param dimension Embedding vector dimension (mandatory when index does not exist yet).\n * @return builder\n */\n public Builder dimension(Integer dimension) {\n this.dimension = dimension;\n return this;\n }\n\n public ElasticsearchEmbeddingStore build() {\n if (restClient != null) {\n return new ElasticsearchEmbeddingStore(restClient, indexName, dimension);\n } else {\n return new ElasticsearchEmbeddingStore(serverUrl, apiKey, userName, password, indexName, dimension);\n }\n }\n }\n\n @Override\n public String add(Embedding embedding) {\n String id = randomUUID();\n add(id, embedding);\n return id;\n }\n\n @Override\n public void add(String id, Embedding embedding) {\n addInternal(id, embedding, null);\n }\n\n @Override\n public String add(Embedding embedding, TextSegment textSegment) {\n String id = randomUUID();\n addInternal(id, embedding, textSegment);\n return id;\n }\n\n @Override\n public List<String> addAll(List<Embedding> embeddings) {\n List<String> ids = embeddings.stream()\n .map(ignored -> randomUUID())\n .collect(toList());\n addAllInternal(ids, embeddings, null);\n return ids;\n }\n\n @Override\n public List<String> addAll(List<Embedding> embeddings, List<TextSegment> embedded) {\n List<String> ids = embeddings.stream()\n .map(ignored -> randomUUID())\n .collect(toList());\n addAllInternal(ids, embeddings, embedded);\n return ids;\n }\n\n @Override\n public List<EmbeddingMatch<TextSegment>> findRelevant(Embedding referenceEmbedding, int maxResults, double minScore) {\n try {\n // Use Script Score and cosineSimilarity to calculate\n // see https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-script-score-query.html#vector-functions-cosine\n ScriptScoreQuery scriptScoreQuery = buildDefaultScriptScoreQuery(referenceEmbedding.vector(), (float) minScore);\n SearchResponse<Document> response = client.search(\n SearchRequest.of(s -> s.index(indexName)\n .query(n -> n.scriptScore(scriptScoreQuery))\n .size(maxResults)),\n Document.class\n );\n\n return toEmbeddingMatch(response);\n } catch (IOException e) {\n log.error(\"[ElasticSearch encounter I/O Exception]\", e);\n throw new ElasticsearchRequestFailedException(e.getMessage());\n }\n }\n\n public ElasticsearchClient getElasticsearchClient() {\n return this.client;\n }\n\n private void addInternal(String id, Embedding embedding, TextSegment embedded) {\n addAllInternal(singletonList(id), singletonList(embedding), embedded == null ? null : singletonList(embedded));\n }\n\n private void addAllInternal(List<String> ids, List<Embedding> embeddings, List<TextSegment> embedded) {\n if (isCollectionEmpty(ids) || isCollectionEmpty(embeddings)) {\n log.info(\"[do not add empty embeddings to elasticsearch]\");\n return;\n }\n ensureTrue(ids.size() == embeddings.size(), \"ids size is not equal to embeddings size\");\n ensureTrue(embedded == null || embeddings.size() == embedded.size(), \"embeddings size is not equal to embedded size\");\n\n try {\n bulk(ids, embeddings, embedded);\n } catch (IOException e) {\n log.error(\"[ElasticSearch encounter I/O Exception]\", e);\n throw new ElasticsearchRequestFailedException(e.getMessage());\n }\n }\n\n private void createIndexIfNotExist(String indexName, Integer dimension) {\n try {\n BooleanResponse response = client.indices().exists(c -> c.index(indexName));\n if (!response.value()) {\n client.indices().create(c -> c.index(indexName)\n .mappings(getDefaultMappings(dimension)));\n }\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }\n\n private TypeMapping getDefaultMappings(Integer dimension) {\n Map<String, Property> properties = new HashMap<>(4);\n properties.put(\"text\", Property.of(p -> p.text(TextProperty.of(t -> t))));\n properties.put(\"vector\", Property.of(p -> p.denseVector(d -> {\n if (dimension != null) d.dims(dimension);\n return d;\n })));\n return TypeMapping.of(c -> c.properties(properties));\n }\n\n private void bulk(List<String> ids, List<Embedding> embeddings, List<TextSegment> embedded) throws IOException {\n int size = ids.size();\n BulkRequest.Builder bulkBuilder = new BulkRequest.Builder();\n for (int i = 0; i < size; i++) {\n int finalI = i;\n Document document = Document.builder()\n .vector(embeddings.get(i).vector())\n .text(embedded == null ? null : embedded.get(i).text())\n .metadata(embedded == null ? null : Optional.ofNullable(embedded.get(i).metadata())\n .map(Metadata::asMap)\n .orElse(null))\n .build();\n bulkBuilder.operations(op -> op.index(idx -> idx\n .index(indexName)\n .id(ids.get(finalI))\n .document(document)));\n }\n\n BulkResponse response = client.bulk(bulkBuilder.build());\n if (response.errors()) {\n for (BulkResponseItem item : response.items()) {\n if (item.error() != null) {\n throw new ElasticsearchRequestFailedException(\"type: \" + item.error().type() + \", reason: \" + item.error().reason());\n }\n }\n }\n }\n\n private ScriptScoreQuery buildDefaultScriptScoreQuery(float[] vector, float minScore) throws JsonProcessingException {\n JsonData queryVector = toJsonData(vector);\n return ScriptScoreQuery.of(q -> q\n .minScore(minScore)\n .query(Query.of(qu -> qu.matchAll(m -> m)))\n .script(s -> s.inline(InlineScript.of(i -> i\n // The script adds 1.0 to the cosine similarity to prevent the score from being negative.\n // divided by 2 to keep score in the range [0, 1]\n .source(\"(cosineSimilarity(params.query_vector, 'vector') + 1.0) / 2\")\n .params(\"query_vector\", queryVector)))));\n }\n\n private <T> JsonData toJsonData(T rawData) throws JsonProcessingException {\n return JsonData.fromJson(objectMapper.writeValueAsString(rawData));\n }\n\n private List<EmbeddingMatch<TextSegment>> toEmbeddingMatch(SearchResponse<Document> response) {\n return response.hits().hits().stream()\n .map(hit -> Optional.ofNullable(hit.source())\n .map(document -> new EmbeddingMatch<>(\n hit.score(),\n hit.id(),\n new Embedding(document.getVector()),\n document.getText() == null\n ? null\n : TextSegment.from(document.getText(), new Metadata(document.getMetadata()))\n )).orElse(null))\n .collect(toList());\n }\n}"
}
] | import dev.langchain4j.model.ollama.OllamaEmbeddingModel;
import dev.langchain4j.model.ollama.OllamaStreamingLanguageModel;
import dev.langchain4j.store.embedding.elasticsearch.ElasticsearchEmbeddingStore;
import org.jline.reader.LineReader;
import org.jline.reader.LineReaderBuilder;
import org.jline.terminal.Terminal;
import org.jline.terminal.TerminalBuilder;
import java.io.FileInputStream;
import java.io.IOException;
import java.time.Duration;
import java.util.Map;
import java.util.Properties; | 3,452 | package co.elastic.examples;
public class Components {
private static final Map<String, String> config;
static {
try (var input = new FileInputStream("config.properties")) {
var props = new Properties();
props.load(input);
@SuppressWarnings("unchecked")
Map<String, String> map = (Map<String, String>) (Map<?, ?>) props;
config = map;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static LineReader createLineReader() throws IOException {
Terminal terminal = TerminalBuilder.builder().dumb(true).build();
return LineReaderBuilder.builder().terminal(terminal).build();
}
| package co.elastic.examples;
public class Components {
private static final Map<String, String> config;
static {
try (var input = new FileInputStream("config.properties")) {
var props = new Properties();
props.load(input);
@SuppressWarnings("unchecked")
Map<String, String> map = (Map<String, String>) (Map<?, ?>) props;
config = map;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static LineReader createLineReader() throws IOException {
Terminal terminal = TerminalBuilder.builder().dumb(true).build();
return LineReaderBuilder.builder().terminal(terminal).build();
}
| public static OllamaEmbeddingModel createEmbeddingModel() { | 0 | 2023-12-06 16:38:44+00:00 | 4k |
Zergatul/java-scripting-language | src/main/java/com/zergatul/scripting/compiler/MethodVisitorWrapper.java | [
{
"identifier": "SType",
"path": "src/main/java/com/zergatul/scripting/compiler/types/SType.java",
"snippet": "public abstract class SType {\r\n\r\n public abstract Class<?> getJavaClass();\r\n public abstract void storeDefaultValue(CompilerMethodVisitor visitor);\r\n public abstract int getLoadInst();\r\n public abstract int getStoreInst();\r\n public abstract int getArrayLoadInst();\r\n public abstract int getArrayStoreInst();\r\n public abstract boolean isReference();\r\n public abstract int getReturnInst();\r\n\r\n public String getDescriptor() {\r\n return Type.getDescriptor(getJavaClass());\r\n }\r\n\r\n public BinaryOperation add(SType other) {\r\n return null;\r\n }\r\n\r\n public BinaryOperation subtract(SType other) {\r\n return null;\r\n }\r\n\r\n public BinaryOperation multiply(SType other) {\r\n return null;\r\n }\r\n\r\n public BinaryOperation divide(SType other) {\r\n return null;\r\n }\r\n\r\n public BinaryOperation modulo(SType other) {\r\n return null;\r\n }\r\n\r\n public BinaryOperation floorMod(SType other) {\r\n return null;\r\n }\r\n\r\n public BinaryOperation floorDiv(SType other) {\r\n return null;\r\n }\r\n\r\n public BinaryOperation lessThan(SType other) {\r\n return null;\r\n }\r\n\r\n public BinaryOperation greaterThan(SType other) {\r\n return null;\r\n }\r\n\r\n public BinaryOperation lessEquals(SType other) {\r\n return null;\r\n }\r\n\r\n public BinaryOperation greaterEquals(SType other) {\r\n return null;\r\n }\r\n\r\n public BinaryOperation equalsOp(SType other) {\r\n return null;\r\n }\r\n\r\n public BinaryOperation notEqualsOp(SType other) {\r\n return null;\r\n }\r\n\r\n public BinaryOperation and(SType other) {\r\n return null;\r\n }\r\n\r\n public BinaryOperation or(SType other) {\r\n return null;\r\n }\r\n\r\n public BinaryOperation binary(Node node, SType other) throws ScriptCompileException {\r\n if (node instanceof ASTPlus) {\r\n return add(other);\r\n } if (node instanceof ASTMinus) {\r\n return subtract(other);\r\n } if (node instanceof ASTMult) {\r\n return multiply(other);\r\n } if (node instanceof ASTDiv) {\r\n return divide(other);\r\n } if (node instanceof ASTMod) {\r\n return modulo(other);\r\n } if (node instanceof ASTFloorDiv) {\r\n return floorDiv(other);\r\n } if (node instanceof ASTFloorMod) {\r\n return floorMod(other);\r\n } if (node instanceof ASTLessThan) {\r\n return lessThan(other);\r\n } if (node instanceof ASTGreaterThan) {\r\n return greaterThan(other);\r\n } if (node instanceof ASTLessEquals) {\r\n return lessEquals(other);\r\n } if (node instanceof ASTGreaterEquals) {\r\n return greaterEquals(other);\r\n } if (node instanceof ASTEquality) {\r\n return equalsOp(other);\r\n } if (node instanceof ASTInequality) {\r\n return notEqualsOp(other);\r\n } if (node instanceof ASTAnd) {\r\n return and(other);\r\n } if (node instanceof ASTOr) {\r\n return or(other);\r\n } else {\r\n throw new ScriptCompileException(String.format(\"Unexpected operator %s.\", node.getClass().getSimpleName()));\r\n }\r\n }\r\n\r\n public UnaryOperation plus() {\r\n return null;\r\n }\r\n\r\n public UnaryOperation minus() {\r\n return null;\r\n }\r\n\r\n public UnaryOperation not() {\r\n return null;\r\n }\r\n\r\n public UnaryOperation unary(Node node) throws ScriptCompileException {\r\n if (node instanceof ASTPlus) {\r\n return plus();\r\n } else if (node instanceof ASTMinus) {\r\n return minus();\r\n } else if (node instanceof ASTNot) {\r\n return not();\r\n } else {\r\n throw new ScriptCompileException(String.format(\"Unexpected operator %s.\", node.getClass().getSimpleName()));\r\n }\r\n }\r\n\r\n public SType compileGetField(String field, CompilerMethodVisitor visitor) throws ScriptCompileException {\r\n return null;\r\n }\r\n\r\n public static SType fromJavaClass(Class<?> type) throws ScriptCompileException {\r\n if (type == void.class) {\r\n return SVoidType.instance;\r\n }\r\n if (type == boolean.class) {\r\n return SBoolean.instance;\r\n }\r\n if (type == int.class) {\r\n return SIntType.instance;\r\n }\r\n if (type == double.class) {\r\n return SFloatType.instance;\r\n }\r\n if (type == String.class) {\r\n return SStringType.instance;\r\n }\r\n if (type.isArray()) {\r\n return new SArrayType(fromJavaClass(type.getComponentType()));\r\n }\r\n throw new ScriptCompileException(\"Invalid java type.\");\r\n }\r\n}"
},
{
"identifier": "SVoidType",
"path": "src/main/java/com/zergatul/scripting/compiler/types/SVoidType.java",
"snippet": "public class SVoidType extends SPrimitiveType {\r\n\r\n public static final SVoidType instance = new SVoidType();\r\n\r\n private SVoidType() {\r\n super(void.class);\r\n }\r\n\r\n @Override\r\n public boolean isReference() {\r\n throw new IllegalStateException();\r\n }\r\n\r\n @Override\r\n public void storeDefaultValue(CompilerMethodVisitor visitor) {\r\n throw new IllegalStateException();\r\n }\r\n\r\n @Override\r\n public int getLoadInst() {\r\n throw new IllegalStateException();\r\n }\r\n\r\n @Override\r\n public int getStoreInst() {\r\n throw new IllegalStateException();\r\n }\r\n\r\n @Override\r\n public int getArrayTypeInst() {\r\n throw new IllegalStateException();\r\n }\r\n\r\n @Override\r\n public int getArrayLoadInst() {\r\n throw new IllegalStateException();\r\n }\r\n\r\n @Override\r\n public int getArrayStoreInst() {\r\n throw new IllegalStateException();\r\n }\r\n\r\n @Override\r\n public int getReturnInst() {\r\n return RETURN;\r\n }\r\n\r\n @Override\r\n public String toString() {\r\n return \"void\";\r\n }\r\n}\r"
},
{
"identifier": "VariableContextStack",
"path": "src/main/java/com/zergatul/scripting/compiler/variables/VariableContextStack.java",
"snippet": "public class VariableContextStack {\r\n\r\n private final Map<String, StaticVariableEntry> staticVariables = new HashMap<>();\r\n private final Map<String, FunctionEntry> functions = new HashMap<>();\r\n private final Stack<VariableContext> stack = new Stack<>();\r\n private int index;\r\n\r\n public VariableContextStack(int initialLocalVarIndex) {\r\n index = initialLocalVarIndex;\r\n stack.add(new VariableContext(index));\r\n }\r\n\r\n public LocalVariableEntry addLocal(String identifier, SType type) throws ScriptCompileException {\r\n if (identifier != null) {\r\n checkIdentifier(identifier);\r\n }\r\n\r\n LocalVariableEntry entry = new LocalVariableEntry(type, index);\r\n stack.peek().add(identifier, entry);\r\n\r\n if (type == SFloatType.instance) {\r\n index += 2;\r\n } else {\r\n index += 1;\r\n }\r\n\r\n return entry;\r\n }\r\n\r\n public StaticVariableEntry addStatic(String identifier, SType type, String className) throws ScriptCompileException {\r\n if (identifier == null) {\r\n throw new ScriptCompileException(\"Identifier is required.\");\r\n }\r\n\r\n if (staticVariables.containsKey(identifier)) {\r\n throw new ScriptCompileException(String.format(\"Static variable %s is already declared.\", identifier));\r\n }\r\n\r\n StaticVariableEntry entry = new StaticVariableEntry(type, className, identifier);\r\n staticVariables.put(identifier, entry);\r\n return entry;\r\n }\r\n\r\n public void addFunction(String identifier, SType returnType, SType[] arguments, String className) throws ScriptCompileException {\r\n if (identifier == null) {\r\n throw new ScriptCompileException(\"Identifier is required.\");\r\n }\r\n\r\n if (staticVariables.containsKey(identifier)) {\r\n throw new ScriptCompileException(String.format(\"Cannot declare function with the same name as static variable %s.\", identifier));\r\n }\r\n\r\n if (functions.containsKey(identifier)) {\r\n throw new ScriptCompileException(String.format(\"Function %s is already declared.\", identifier));\r\n }\r\n\r\n FunctionEntry entry = new FunctionEntry(className, identifier, arguments, returnType);\r\n functions.put(identifier, entry);\r\n }\r\n\r\n public void begin() {\r\n stack.add(new VariableContext(index));\r\n }\r\n\r\n public void end() {\r\n index = stack.pop().getStartIndex();\r\n }\r\n\r\n public VariableEntry get(String identifier) {\r\n for (int i = stack.size() - 1; i >= 0; i--) {\r\n VariableEntry entry = stack.get(i).get(identifier);\r\n if (entry != null) {\r\n return entry;\r\n }\r\n }\r\n\r\n if (staticVariables.containsKey(identifier)) {\r\n return staticVariables.get(identifier);\r\n }\r\n\r\n return null;\r\n }\r\n\r\n public FunctionEntry getFunction(String identifier) {\r\n return functions.get(identifier);\r\n }\r\n\r\n public Collection<StaticVariableEntry> getStaticVariables() {\r\n return staticVariables.values();\r\n }\r\n\r\n public VariableContextStack newWithStaticVariables(int initialLocalVarIndex) {\r\n VariableContextStack context = new VariableContextStack(initialLocalVarIndex);\r\n for (StaticVariableEntry entry : staticVariables.values()) {\r\n context.staticVariables.put(entry.getIdentifier(), entry);\r\n }\r\n for (FunctionEntry entry : functions.values()) {\r\n context.functions.put(entry.getIdentifier(), entry);\r\n }\r\n return context;\r\n }\r\n\r\n private void checkIdentifier(String identifier) throws ScriptCompileException {\r\n for (int i = stack.size() - 1; i >= 0; i--) {\r\n if (stack.get(i).contains(identifier)) {\r\n throw new ScriptCompileException(String.format(\"Identifier %s is already declared.\", identifier));\r\n }\r\n }\r\n }\r\n}"
}
] | import com.zergatul.scripting.compiler.types.SType;
import com.zergatul.scripting.compiler.types.SVoidType;
import com.zergatul.scripting.compiler.variables.VariableContextStack;
import org.objectweb.asm.Label;
import org.objectweb.asm.MethodVisitor;
| 2,446 | package com.zergatul.scripting.compiler;
public class MethodVisitorWrapper extends CompilerMethodVisitor {
private final MethodVisitor visitor;
private final String className;
private final VariableContextStack contexts;
private final LoopContextStack loops;
private final SType returnType;
public MethodVisitorWrapper(MethodVisitor visitor, String className, VariableContextStack contexts) {
| package com.zergatul.scripting.compiler;
public class MethodVisitorWrapper extends CompilerMethodVisitor {
private final MethodVisitor visitor;
private final String className;
private final VariableContextStack contexts;
private final LoopContextStack loops;
private final SType returnType;
public MethodVisitorWrapper(MethodVisitor visitor, String className, VariableContextStack contexts) {
| this(visitor, className, contexts, SVoidType.instance);
| 1 | 2023-12-10 00:37:27+00:00 | 4k |
Pigalala/TrackExchange | src/main/java/me/pigalala/trackexchange/CommandTrackExchange.java | [
{
"identifier": "ProcessLoad",
"path": "src/main/java/me/pigalala/trackexchange/processes/ProcessLoad.java",
"snippet": "public class ProcessLoad extends Process {\n\n private final String fileName;\n private final String loadAs;\n\n private final TaskChain<?> chain;\n private final Location origin;\n\n public ProcessLoad(Player player, String fileName, String loadAs) {\n super(player, \"LOAD\");\n this.fileName = fileName;\n this.loadAs = loadAs;\n\n chain = TrackExchange.newChain();\n origin = player.getLocation().clone();\n }\n\n @Override\n public void execute() {\n final long startTime = System.currentTimeMillis();\n notifyProcessStartText();\n\n chain.async(this::doReadStage)\n .asyncFutures((f) -> List.of(CompletableFuture.supplyAsync(this::doTrackStage), CompletableFuture.supplyAsync(this::doPasteStage)))\n .execute((success) -> {\n if (success)\n notifyProcessFinishText(System.currentTimeMillis() - startTime);\n else\n notifyProcessFinishExceptionallyText();\n }\n );\n }\n\n private void doReadStage() {\n final String stage = \"READ\";\n final long startTime = System.currentTimeMillis();\n\n notifyStageBeginText(stage);\n try {\n TrackExchangeFile trackExchangeFile = TrackExchangeFile.read(new File(TrackExchange.instance.getDataFolder(), fileName), loadAs);\n chain.setTaskData(\"trackExchangeFile\", trackExchangeFile);\n notifyStageFinishText(stage, System.currentTimeMillis() - startTime);\n } catch (Exception e) {\n notifyStageFinishExceptionallyText(stage, e);\n chain.abortChain();\n }\n }\n\n private Void doTrackStage() {\n final String stage = \"TRACK\";\n final long startTime = System.currentTimeMillis();\n\n notifyStageBeginText(stage);\n TrackExchangeFile trackExchangeFile = chain.getTaskData(\"trackExchangeFile\");\n try {\n trackExchangeFile.getTrack().createTrack(player);\n notifyStageFinishText(stage, System.currentTimeMillis() - startTime);\n } catch (SQLException e) {\n notifyStageFinishExceptionallyText(stage, e);\n chain.abortChain();\n }\n\n return null;\n }\n\n private Void doPasteStage() {\n final String stage = \"PASTE\";\n final long startTime = System.currentTimeMillis();\n\n TrackExchangeFile trackExchangeFile = chain.getTaskData(\"trackExchangeFile\");\n trackExchangeFile.getSchematic().ifPresentOrElse(schematic -> {\n notifyStageBeginText(stage);\n try {\n schematic.pasteAt(origin);\n notifyStageFinishText(stage, System.currentTimeMillis() - startTime);\n } catch (WorldEditException e) {\n notifyStageFinishExceptionallyText(stage, e);\n }\n }, () -> {\n notifyPlayer(Component.text(\"Skipping stage '\" + stage + \"'.\", NamedTextColor.YELLOW));\n });\n\n return null;\n }\n}"
},
{
"identifier": "ProcessSave",
"path": "src/main/java/me/pigalala/trackexchange/processes/ProcessSave.java",
"snippet": "public class ProcessSave extends Process {\n\n private final Track track;\n private final String saveAs;\n\n private final TaskChain<?> chain;\n private final Location origin;\n\n public ProcessSave(Player player, Track track, String saveAs) {\n super(player, \"SAVE\");\n this.track = track;\n this.saveAs = saveAs;\n\n this.chain = TrackExchange.newChain();\n this.origin = player.getLocation();\n }\n\n @Override\n public void execute() {\n final long startTime = System.currentTimeMillis();\n notifyProcessStartText();\n\n chain.asyncFutures((f) -> List.of(CompletableFuture.supplyAsync(this::doTrackStage), CompletableFuture.supplyAsync(this::doSchematicStage)))\n .async(this::doWriteStage)\n .execute((success) -> {\n if(success)\n notifyProcessFinishText(System.currentTimeMillis() - startTime);\n else\n notifyProcessFinishExceptionallyText();\n });\n }\n\n private Void doTrackStage() {\n final String stage = \"TRACK\";\n final long startTime = System.currentTimeMillis();\n\n notifyStageBeginText(stage);\n TrackExchangeTrack trackExchangeTrack = new TrackExchangeTrack(track, new SimpleLocation(origin));\n chain.setTaskData(\"track\", trackExchangeTrack);\n notifyStageFinishText(stage, System.currentTimeMillis() - startTime);\n\n return null;\n }\n\n private Void doSchematicStage() {\n final String stage = \"SCHEMATIC\";\n final long startTime = System.currentTimeMillis();\n\n notifyStageBeginText(stage);\n try {\n Region selection = WorldEdit.getInstance().getSessionManager().get(BukkitAdapter.adapt(player)).getSelection();\n BlockArrayClipboard clipboard = new BlockArrayClipboard(selection);\n try(EditSession session = WorldEdit.getInstance().newEditSession(BukkitAdapter.adapt(player.getWorld()))) {\n ForwardExtentCopy op = new ForwardExtentCopy(session, selection, clipboard, selection.getMinimumPoint());\n op.setCopyingEntities(true);\n Operations.complete(op);\n }\n chain.setTaskData(\"schematic\", new TrackExchangeSchematic(clipboard));\n notifyStageFinishText(stage, System.currentTimeMillis() - startTime);\n } catch (WorldEditException e) {\n if(e instanceof IncompleteRegionException)\n notifyPlayer(Component.text(\"Saving without Schematic.\", NamedTextColor.YELLOW));\n else\n notifyPlayer(Component.text(\"Saving without Schematic...\", NamedTextColor.YELLOW).hoverEvent(Component.text(e.getMessage(), NamedTextColor.RED)));\n chain.setTaskData(\"schematic\", null);\n }\n\n return null;\n }\n\n private void doWriteStage() {\n final String stage = \"WRITE\";\n final long startTime = System.currentTimeMillis();\n\n notifyStageBeginText(stage);\n TrackExchangeTrack trackExchangeTrack = chain.getTaskData(\"track\");\n TrackExchangeSchematic trackExchangeSchematic = chain.getTaskData(\"schematic\");\n TrackExchangeFile trackExchangeFile = new TrackExchangeFile(trackExchangeTrack, new SimpleLocation(origin), trackExchangeSchematic);\n try {\n trackExchangeFile.write(new File(TrackExchange.instance.getDataFolder(), saveAs));\n notifyStageFinishText(stage, System.currentTimeMillis() - startTime);\n } catch (IOException e) {\n notifyStageFinishExceptionallyText(stage, e);\n notifyStageFinishExceptionallyText(stage, e);\n }\n }\n}"
},
{
"identifier": "TrackExchangeFile",
"path": "src/main/java/me/pigalala/trackexchange/trackcomponents/TrackExchangeFile.java",
"snippet": "@Getter\npublic class TrackExchangeFile {\n private final TrackExchangeTrack track;\n private final SimpleLocation origin;\n private final TrackExchangeSchematic schematic;\n\n public TrackExchangeFile(TrackExchangeTrack track, SimpleLocation origin, TrackExchangeSchematic schematic) {\n this.track = track;\n this.origin = origin;\n this.schematic = schematic;\n }\n\n public Optional<TrackExchangeSchematic> getSchematic() {\n return Optional.ofNullable(schematic);\n }\n\n public void write(File dir) throws IOException {\n dir.mkdir();\n\n File dataFile = new File(dir, \"data.component\");\n File trackFile = new File(dir, \"track.component\");\n File schematicFile = new File(dir, \"schematic.component\");\n\n JSONObject data = new JSONObject();\n data.put(\"version\", TrackExchange.TRACK_VERSION);\n if(getSchematic().isPresent())\n data.put(\"clipboardOffset\", new SimpleLocation(SimpleLocation.getOffset(getSchematic().get().getClipboard().getOrigin(), origin.toBlockVector3())).toJson());\n\n dataFile.createNewFile();\n try (FileWriter writer = new FileWriter(dataFile)) {\n writer.write(data.toJSONString());\n }\n\n trackFile.createNewFile();\n try(FileOutputStream fileOut = new FileOutputStream(trackFile); ObjectOutputStream out = new ObjectOutputStream(fileOut)) {\n out.writeObject(track);\n }\n\n if(getSchematic().isPresent()) {\n schematicFile.createNewFile();\n schematic.saveTo(schematicFile);\n }\n\n zipDir(dir);\n cleanup(dir);\n }\n\n public static TrackExchangeFile read(File trackDir, String newName) throws Exception {\n unzipDir(findFile(trackDir.getName() + \".trackexchange\", TrackExchange.instance.getDataFolder()), TrackExchange.instance.getDataFolder());\n\n File dataFile = new File(TrackExchange.instance.getDataFolder(), \"data.component\");\n File trackFile = new File(TrackExchange.instance.getDataFolder(), \"track.component\");\n File schematicFile = new File(TrackExchange.instance.getDataFolder(), \"schematic.component\");\n\n SimpleLocation clipboardOffset = new SimpleLocation(BlockVector3.at(0, 0, 0));\n try (FileReader reader = new FileReader(dataFile)) {\n JSONParser parser = new JSONParser();\n JSONObject data = (JSONObject) parser.parse(reader);\n int version = Integer.parseInt(String.valueOf(data.get(\"version\")));\n if(version != TrackExchange.TRACK_VERSION)\n throw new RuntimeException(\"This track's version does not match the server's version. (Track: \" + version + \". Server: \" + TrackExchange.TRACK_VERSION + \")\");\n\n JSONObject clipboardOffsetObject = (JSONObject) data.get(\"clipboardOffset\");\n if(clipboardOffsetObject != null)\n clipboardOffset = SimpleLocation.fromJson(clipboardOffsetObject);\n }\n\n TrackExchangeTrack trackExchangeTrack;\n try(FileInputStream fileIn = new FileInputStream(trackFile); ObjectInputStream in = new ObjectInputStream(fileIn)) {\n trackExchangeTrack = (TrackExchangeTrack) in.readObject();\n trackExchangeTrack.setDisplayName(newName);\n }\n\n TrackExchangeSchematic trackExchangeSchematic = null;\n if (schematicFile.exists()) {\n try(FileInputStream fileIn = new FileInputStream(schematicFile)) {\n ClipboardReader clipboardReader = BuiltInClipboardFormat.SPONGE_SCHEMATIC.getReader(fileIn);\n Clipboard clipboard = clipboardReader.read();\n trackExchangeSchematic = new TrackExchangeSchematic(clipboard);\n trackExchangeSchematic.setOffset(clipboardOffset);\n }\n }\n\n cleanup(trackDir);\n return new TrackExchangeFile(trackExchangeTrack, trackExchangeTrack.getOrigin(), trackExchangeSchematic);\n }\n\n private static void zipDir(File dir) throws IOException {\n try(ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(dir.getPath() + \".trackexchange\"))) {\n Files.walkFileTree(dir.toPath(), new SimpleFileVisitor<>() {\n @Override\n public FileVisitResult visitFile(Path file, BasicFileAttributes attributes) {\n if(attributes.isSymbolicLink())\n return FileVisitResult.CONTINUE;\n\n try(FileInputStream fileIn = new FileInputStream(file.toFile())) {\n Path targetFile = dir.toPath().relativize(file);\n zipOut.putNextEntry(new ZipEntry(targetFile.toString()));\n\n byte[] buffer = new byte[1024];\n int len;\n while((len = fileIn.read(buffer)) > 0)\n zipOut.write(buffer, 0, len);\n zipOut.closeEntry();\n } catch (IOException e) {\n e.printStackTrace();\n }\n\n return FileVisitResult.CONTINUE;\n }\n\n @Override\n public FileVisitResult visitFileFailed(Path file, IOException e) {\n TrackExchange.instance.getLogger().log(Level.SEVERE, \"Error visiting file: \" + file.toString());\n return FileVisitResult.CONTINUE;\n }\n });\n }\n }\n\n private static void unzipDir(File dir, File dest) throws IOException {\n try (ZipInputStream zipIn = new ZipInputStream(new FileInputStream(dir.getPath()))) {\n ZipEntry zipEntry = zipIn.getNextEntry();\n while(zipEntry != null) {\n Path newPath = dest.toPath().resolve(zipEntry.getName()).normalize();\n Files.copy(zipIn, newPath, StandardCopyOption.REPLACE_EXISTING);\n zipIn.closeEntry();\n zipEntry = zipIn.getNextEntry();\n }\n }\n }\n\n // Check to see if file 'find' is in 'dir' when the file name cases do not match.\n private static File findFile(String find, File dir) {\n File[] files = dir.listFiles();\n if(files == null)\n return null;\n\n for(File file : files) {\n if(find.equalsIgnoreCase(file.getName()))\n return file;\n }\n\n return null;\n }\n\n public static boolean trackExchangeFileExists(String fileName) {\n File f = findFile(fileName + \".trackexchange\", TrackExchange.instance.getDataFolder());\n return f != null && f.exists();\n }\n\n public static void cleanup(File dir) {\n if(dir.listFiles() != null)\n Arrays.stream(dir.listFiles()).forEach(File::delete);\n dir.delete();\n new File(TrackExchange.instance.getDataFolder(), \"data.component\").delete();\n new File(TrackExchange.instance.getDataFolder(), \"track.component\").delete();\n new File(TrackExchange.instance.getDataFolder(), \"schematic.component\").delete();\n }\n}"
}
] | import co.aikar.commands.BaseCommand;
import co.aikar.commands.ConditionFailedException;
import co.aikar.commands.annotation.*;
import me.makkuusen.timing.system.ApiUtilities;
import me.makkuusen.timing.system.database.TrackDatabase;
import me.makkuusen.timing.system.track.Track;
import me.pigalala.trackexchange.processes.ProcessLoad;
import me.pigalala.trackexchange.processes.ProcessSave;
import me.pigalala.trackexchange.trackcomponents.TrackExchangeFile;
import org.bukkit.entity.Player; | 3,270 | package me.pigalala.trackexchange;
@CommandAlias("trackexchange|tex|tx")
public class CommandTrackExchange extends BaseCommand {
@Subcommand("copy")
@CommandCompletion("@track <saveas>")
@CommandPermission("trackexchange.export")
public static void onCopy(Player player, Track track, @Optional @Single String saveAs) {
if(saveAs == null)
saveAs = track.getCommandName();
if(TrackExchangeFile.trackExchangeFileExists(saveAs))
throw new ConditionFailedException("This trackexchange file already exists");
if(!saveAs.matches("[A-Za-z0-9_]+"))
throw new ConditionFailedException("You cannot save a trackexchange track with that name");
| package me.pigalala.trackexchange;
@CommandAlias("trackexchange|tex|tx")
public class CommandTrackExchange extends BaseCommand {
@Subcommand("copy")
@CommandCompletion("@track <saveas>")
@CommandPermission("trackexchange.export")
public static void onCopy(Player player, Track track, @Optional @Single String saveAs) {
if(saveAs == null)
saveAs = track.getCommandName();
if(TrackExchangeFile.trackExchangeFileExists(saveAs))
throw new ConditionFailedException("This trackexchange file already exists");
if(!saveAs.matches("[A-Za-z0-9_]+"))
throw new ConditionFailedException("You cannot save a trackexchange track with that name");
| new ProcessSave(player, track, saveAs).execute(); | 1 | 2023-12-06 12:43:51+00:00 | 4k |
Lampadina17/MorpheusLauncher | src/team/morpheus/launcher/Launcher.java | [
{
"identifier": "MyLogger",
"path": "src/team/morpheus/launcher/logging/MyLogger.java",
"snippet": "public class MyLogger {\r\n\r\n public Class clazz;\r\n\r\n public MyLogger(Class clazz) {\r\n this.clazz = clazz;\r\n }\r\n\r\n public void info(String message) {\r\n printLog(LogLevel.INFO, message);\r\n }\r\n\r\n public void warn(String message) {\r\n printLog(LogLevel.WARN, message);\r\n }\r\n\r\n public void error(String message) {\r\n printLog(LogLevel.ERROR, message);\r\n }\r\n\r\n public void debug(String message) {\r\n printLog(LogLevel.DEBUG, message);\r\n }\r\n\r\n public void printLog(LogLevel type, String message) {\r\n System.out.println(String.format(\"[%s]: %s\", type.name(), message));\r\n }\r\n}\r"
},
{
"identifier": "MojangProduct",
"path": "src/team/morpheus/launcher/model/products/MojangProduct.java",
"snippet": "public class MojangProduct {\r\n\r\n @SerializedName(\"latest\")\r\n public Latest latest;\r\n\r\n @SerializedName(\"versions\")\r\n public ArrayList<Version> versions;\r\n\r\n public class Latest {\r\n\r\n @SerializedName(\"release\")\r\n public String release;\r\n\r\n @SerializedName(\"snapshot\")\r\n public String snapshot;\r\n }\r\n\r\n public class Version {\r\n\r\n @SerializedName(\"id\")\r\n public String id;\r\n\r\n @SerializedName(\"type\")\r\n public String type;\r\n\r\n @SerializedName(\"url\")\r\n public String url;\r\n\r\n @SerializedName(\"time\")\r\n public Date time;\r\n\r\n @SerializedName(\"releaseTime\")\r\n public Date releaseTime;\r\n }\r\n\r\n public class Game {\r\n\r\n @SerializedName(\"assetIndex\")\r\n public AssetIndex assetIndex;\r\n\r\n @SerializedName(\"assets\")\r\n public String assets;\r\n\r\n @SerializedName(\"complianceLevel\")\r\n public int complianceLevel;\r\n\r\n @SerializedName(\"downloads\")\r\n public Downloads downloads;\r\n\r\n @SerializedName(\"id\")\r\n public String id;\r\n\r\n @SerializedName(\"inheritsFrom\")\r\n public String inheritsFrom;\r\n\r\n @SerializedName(\"javaVersion\")\r\n public JavaVersion javaVersion;\r\n\r\n @SerializedName(\"libraries\")\r\n public ArrayList<Library> libraries;\r\n\r\n @SerializedName(\"mainClass\")\r\n public String mainClass;\r\n\r\n @SerializedName(\"minimumLauncherVersion\")\r\n public int minimumLauncherVersion;\r\n\r\n @SerializedName(\"releaseTime\")\r\n public Date releaseTime;\r\n\r\n @SerializedName(\"time\")\r\n public Date time;\r\n\r\n @SerializedName(\"type\")\r\n public String type;\r\n\r\n @SerializedName(\"arguments\")\r\n public Arguments arguments; // latest\r\n\r\n @SerializedName(\"minecraftArguments\")\r\n public String minecraftArguments; // legacy\r\n\r\n public class Arguments {\r\n\r\n @SerializedName(\"game\")\r\n public ArrayList<Object> game;\r\n\r\n @SerializedName(\"jvm\")\r\n public ArrayList<Object> jvm;\r\n }\r\n\r\n public class Artifact {\r\n\r\n @SerializedName(\"path\")\r\n public String path;\r\n\r\n @SerializedName(\"sha1\")\r\n public String sha1;\r\n\r\n @SerializedName(\"size\")\r\n public int size;\r\n\r\n @SerializedName(\"url\")\r\n public String url;\r\n }\r\n\r\n public class AssetIndex {\r\n\r\n @SerializedName(\"id\")\r\n public String id;\r\n\r\n @SerializedName(\"sha1\")\r\n public String sha1;\r\n\r\n @SerializedName(\"size\")\r\n public int size;\r\n\r\n @SerializedName(\"totalSize\")\r\n public int totalSize;\r\n\r\n @SerializedName(\"url\")\r\n public String url;\r\n }\r\n\r\n public class Client {\r\n\r\n @SerializedName(\"sha1\")\r\n public String sha1;\r\n\r\n @SerializedName(\"size\")\r\n public int size;\r\n\r\n @SerializedName(\"url\")\r\n public String url;\r\n\r\n @SerializedName(\"argument\")\r\n public String argument;\r\n\r\n @SerializedName(\"file\")\r\n public File file;\r\n\r\n @SerializedName(\"type\")\r\n public String type;\r\n }\r\n\r\n public class Downloads {\r\n\r\n @SerializedName(\"client\")\r\n public Client client;\r\n\r\n @SerializedName(\"artifact\")\r\n public Artifact artifact;\r\n\r\n @SerializedName(\"classifiers\")\r\n public Classifiers classifiers;\r\n }\r\n\r\n public class File {\r\n\r\n @SerializedName(\"id\")\r\n public String id;\r\n\r\n @SerializedName(\"sha1\")\r\n public String sha1;\r\n\r\n @SerializedName(\"size\")\r\n public int size;\r\n\r\n @SerializedName(\"url\")\r\n public String url;\r\n }\r\n\r\n public class JavaVersion {\r\n\r\n @SerializedName(\"component\")\r\n public String component;\r\n\r\n @SerializedName(\"majorVersion\")\r\n public int majorVersion;\r\n }\r\n\r\n public class Library {\r\n\r\n @SerializedName(\"downloads\")\r\n public Downloads downloads;\r\n\r\n @SerializedName(\"name\")\r\n public String name;\r\n\r\n @SerializedName(\"rules\")\r\n public ArrayList<Rule> rules;\r\n\r\n @SerializedName(\"natives\")\r\n public Natives natives;\r\n\r\n @SerializedName(\"url\")\r\n public String url;\r\n }\r\n\r\n public class Rule {\r\n\r\n @SerializedName(\"action\")\r\n public String action;\r\n\r\n @SerializedName(\"os\")\r\n public Os os;\r\n }\r\n\r\n public class Os {\r\n\r\n @SerializedName(\"name\")\r\n public String name;\r\n }\r\n\r\n // Legacy stuff\r\n public class Classifiers {\r\n\r\n @SerializedName(\"natives-linux\")\r\n public NativesLinux natives_linux;\r\n\r\n @SerializedName(\"natives-osx\")\r\n public NativesOsx natives_osx;\r\n\r\n @SerializedName(\"natives-macos\")\r\n public NativesOsx natives_macos;\r\n\r\n @SerializedName(\"natives-windows\")\r\n public NativesWindows natives_windows;\r\n\r\n @SerializedName(\"natives-windows-32\")\r\n public NativesWindows natives_windows_32;\r\n\r\n @SerializedName(\"natives-windows-64\")\r\n public NativesWindows natives_windows_64;\r\n }\r\n\r\n public class Natives {\r\n\r\n @SerializedName(\"linux\")\r\n public String linux;\r\n\r\n @SerializedName(\"osx\")\r\n public String osx;\r\n\r\n @SerializedName(\"windows\")\r\n public String windows;\r\n }\r\n\r\n public class NativesLinux {\r\n\r\n @SerializedName(\"path\")\r\n public String path;\r\n\r\n @SerializedName(\"sha1\")\r\n public String sha1;\r\n\r\n @SerializedName(\"size\")\r\n public int size;\r\n\r\n @SerializedName(\"url\")\r\n public String url;\r\n }\r\n\r\n public class NativesOsx {\r\n\r\n @SerializedName(\"path\")\r\n public String path;\r\n\r\n @SerializedName(\"sha1\")\r\n public String sha1;\r\n\r\n @SerializedName(\"size\")\r\n public int size;\r\n\r\n @SerializedName(\"url\")\r\n public String url;\r\n }\r\n\r\n public class NativesWindows {\r\n\r\n @SerializedName(\"path\")\r\n public String path;\r\n\r\n @SerializedName(\"sha1\")\r\n public String sha1;\r\n\r\n @SerializedName(\"size\")\r\n public int size;\r\n\r\n @SerializedName(\"url\")\r\n public String url;\r\n }\r\n }\r\n}\r"
},
{
"identifier": "MorpheusProduct",
"path": "src/team/morpheus/launcher/model/products/MorpheusProduct.java",
"snippet": "public class MorpheusProduct {\r\n\r\n @SerializedName(\"data\")\r\n public Data data;\r\n\r\n public class Data {\r\n\r\n @SerializedName(\"id\")\r\n public String id;\r\n\r\n @SerializedName(\"name\")\r\n public String name;\r\n\r\n @SerializedName(\"version\")\r\n public String version;\r\n\r\n @SerializedName(\"gameversion\")\r\n public String gameversion;\r\n\r\n @SerializedName(\"sha256\")\r\n public String sha256;\r\n\r\n @SerializedName(\"mainclass\")\r\n public String mainclass;\r\n\r\n @SerializedName(\"libraries\")\r\n public ArrayList<Library> libraries;\r\n }\r\n\r\n public class Library {\r\n\r\n @SerializedName(\"name\")\r\n public String name;\r\n\r\n @SerializedName(\"sha256\")\r\n public String sha256;\r\n }\r\n}\r"
}
] | import com.google.gson.Gson;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import team.morpheus.launcher.logging.MyLogger;
import team.morpheus.launcher.model.products.MojangProduct;
import team.morpheus.launcher.model.products.MorpheusProduct;
import team.morpheus.launcher.utils.*;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.lang.reflect.InvocationTargetException;
import java.net.*;
import java.nio.file.Files;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
| 2,165 | package team.morpheus.launcher;
public class Launcher {
private static final MyLogger log = new MyLogger(Launcher.class);
public JSONParser jsonParser = new JSONParser();
private File gameFolder, assetsFolder;
| package team.morpheus.launcher;
public class Launcher {
private static final MyLogger log = new MyLogger(Launcher.class);
public JSONParser jsonParser = new JSONParser();
private File gameFolder, assetsFolder;
| private MojangProduct vanilla;
| 1 | 2023-12-07 14:34:54+00:00 | 4k |
ranizouaoui/CANalyzer | Controllers/UserOption2.java | [
{
"identifier": "CANFrameTransmission",
"path": "Classes/CANFrameTransmission.java",
"snippet": "public class CANFrameTransmission {\n\n private static final int MAX_DATA_POINTS = 500;\n private static final double TIME_PERIOD_PER_BIT = 1; // Adjust as needed\n private int xSeriesData = 0;\n private XYChart.Series<Number, Number> series;\n\n public void initialize(Stage primaryStage) {\n primaryStage.setTitle(\"Real-Time CAN Frame Transmission\");\n\n NumberAxis xAxis = new NumberAxis(0, MAX_DATA_POINTS * TIME_PERIOD_PER_BIT, MAX_DATA_POINTS * TIME_PERIOD_PER_BIT / 10);\n NumberAxis yAxis = new NumberAxis(0, 2, 1); // Adjust yAxis range as needed\n xAxis.setForceZeroInRange(false);\n\n LineChart<Number, Number> lineChart = new LineChart<>(xAxis, yAxis);\n lineChart.setCreateSymbols(false);\n lineChart.setAnimated(false);\n lineChart.setTitle(\"CAN Frame Transmission\");\n\n series = new XYChart.Series<>();\n series.setName(\"CAN Frame Data\");\n lineChart.getData().add(series);\n\n Scene scene = new Scene(lineChart, 800, 600);\n primaryStage.setScene(scene);\n\n final AnimationTimer animationTimer = new AnimationTimer() {\n @Override\n public void handle(long now) {\n addDataToSeries();\n }\n };\n animationTimer.start();\n }\n\n private void addDataToSeries() {\n // Define binary CAN frame data\n String binaryData = \"110101010111111110000000001111111111111111001111000001111\"; // Replace this with your desired binary frame\n\n if (binaryData.matches(\"[01]+\")) {\n updateSeries(binaryData);\n } else {\n System.out.println(\"Invalid binary frame. Please provide a valid binary string.\");\n }\n }\n\n private void updateSeries(String binaryData) {\n for (char bit : binaryData.toCharArray()) {\n int value = (bit == '1') ? 1 : 0;\n double timePeriod = xSeriesData * TIME_PERIOD_PER_BIT;\n series.getData().add(new XYChart.Data<>(timePeriod, value));\n xSeriesData++;\n\n if (xSeriesData > MAX_DATA_POINTS) {\n series.getData().remove(0, series.getData().size() - MAX_DATA_POINTS);\n }\n }\n\n // Pause the animation for a short duration to make the waveform visible\n try {\n Thread.sleep(50); // Adjust as needed\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n }\n}"
},
{
"identifier": "FrameModel",
"path": "Classes/FrameModel.java",
"snippet": "public class FrameModel {\n private int index;\n private String identifier;\n private String dlc;\n private String data;\n private String frameName;\n\n public FrameModel(int index, String identifier, String dlc, String data, String frameName) {\n\t\tthis.index = index;\n\t\tthis.identifier = identifier;\n\t\tthis.dlc = dlc;\n\t\tthis.data = data;\n\t\tthis.frameName = frameName;\n\t}\n \n \n public FrameModel() {\n\n\t}\n\n\n\tpublic int getIndex() {\n return index;\n }\n\n\n\tpublic void setIndex(int index) {\n this.index = index;\n }\n\n public String getIdentifier() {\n return identifier;\n }\n\n public void setIdentifier(String identifier) {\n this.identifier = identifier;\n }\n\n public String getDlc() {\n return dlc;\n }\n\n public void setDlc(String dlc) {\n this.dlc = dlc;\n }\n\n public String getData() {\n return data;\n }\n\n public void setData(String data) {\n this.data = data;\n }\n\n public String getFrameName() {\n return frameName;\n }\n\n public void setFrameName(String frameName) {\n this.frameName = frameName;\n }\n}"
},
{
"identifier": "DataBase",
"path": "helpers/DataBase.java",
"snippet": "public class DataBase {\n @FXML\n TableView<FrameModel> frameTable;\n\tpublic static Connection connecterBase() {\n\t\tConnection con = null;\n\t\tString url = \"jdbc:mysql://localhost:3306/can\";\n\t\tString user = \"root\";\n\t\tString password = \"\";\n\t\ttry {\n\t\t\tClass.forName(\"com.mysql.cj.jdbc.Driver\");\n\t\t\tcon = DriverManager.getConnection(url, user, password);\n\t\t\tSystem.out.println(\"connexion �tablie.\");\n\t\t} catch (ClassNotFoundException | SQLException e) {\n\t\t\tSystem.out.println(\"erreur de connexion !\");\n\t\t}\n\t\treturn con;\n\t}\n\tpublic void insertFrame(String identifier, String dlc, String data, String frameName) {\n Connection con = connecterBase();\n\n if (con != null) {\n try {\n String query = \"INSERT INTO can_frames (IDENTIFIER, DLC, DATA, Frame_Name) VALUES (?, ?, ?, ?)\";\n try (PreparedStatement pstmt = con.prepareStatement(query)) {\n pstmt.setString(1, identifier);\n pstmt.setString(2, dlc);\n pstmt.setString(3, data);\n pstmt.setString(4, frameName);\n\n int rowsAffected = pstmt.executeUpdate();\n System.out.println(rowsAffected + \" row(s) inserted.\");\n }\n } catch (SQLException e) {\n e.printStackTrace();\n } finally {\n try {\n con.close();\n } catch (SQLException e) {\n e.printStackTrace();\n }\n }\n }\n }\n\n\n\n}"
}
] | import java.util.logging.Level;
import java.util.logging.Logger;
import java.math.BigInteger;
import java.net.URL;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.ResourceBundle;
import Classes.CANFrameTransmission;
import Classes.FrameModel;
import helpers.DataBase;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.concurrent.Task;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.stage.Stage;
import jssc.SerialPort;
import jssc.SerialPortException;
import jssc.SerialPortList; | 1,643 | package Controllers;
public class UserOption2 implements Initializable {
@FXML
private Label noFrameTypeLabel;
@FXML
private Label errorLabel;
@FXML
private ComboBox<String> serialPortComboBox;
@FXML
private ComboBox<String> frameTypeComboBox;
@FXML
private Label noPortLabel;
@FXML
private TextField dataTextField;
@FXML
private TextField rtrTextField;
@FXML
private TextField IDENTIFIERTextField;
@FXML
private TextField DLCTextField;
@FXML
private TextField frameNameTextField;
@FXML
private Button sendButton;
// Assuming FrameTable is a TableView<FrameModel>
@FXML | package Controllers;
public class UserOption2 implements Initializable {
@FXML
private Label noFrameTypeLabel;
@FXML
private Label errorLabel;
@FXML
private ComboBox<String> serialPortComboBox;
@FXML
private ComboBox<String> frameTypeComboBox;
@FXML
private Label noPortLabel;
@FXML
private TextField dataTextField;
@FXML
private TextField rtrTextField;
@FXML
private TextField IDENTIFIERTextField;
@FXML
private TextField DLCTextField;
@FXML
private TextField frameNameTextField;
@FXML
private Button sendButton;
// Assuming FrameTable is a TableView<FrameModel>
@FXML | TableView<FrameModel> frameTable; | 1 | 2023-12-13 22:00:14+00:00 | 4k |
Serilum/Collective | Common/src/main/java/com/natamus/collective/globalcallbacks/MainMenuLoadedCallback.java | [
{
"identifier": "Event",
"path": "Common/src/main/java/com/natamus/collective/implementations/event/Event.java",
"snippet": "public abstract class Event<T> {\n\t/**\n\t * The invoker field. This should be updated by the implementation to\n\t * always refer to an instance containing all code that should be\n\t * executed upon event emission.\n\t */\n\tprotected volatile T invoker;\n\n\t/**\n\t * Returns the invoker instance.\n\t *\n\t * <p>An \"invoker\" is an object which hides multiple registered\n\t * listeners of type T under one instance of type T, executing\n\t * them and leaving early as necessary.\n\t *\n\t * @return The invoker instance.\n\t */\n\tpublic final T invoker() {\n\t\treturn invoker;\n\t}\n\n\t/**\n\t * Register a listener to the event, in the default phase.\n\t * Have a look at {@link #addPhaseOrdering} for an explanation of event phases.\n\t *\n\t * @param listener The desired listener.\n\t */\n\tpublic abstract void register(T listener);\n\n\t/**\n\t * The identifier of the default phase.\n\t */\n\tpublic static final ResourceLocation DEFAULT_PHASE = new ResourceLocation(CollectiveReference.MOD_ID, \"default\");\n\n\t/**\n\t * Register a listener to the event for the specified phase.\n\t *\n\t * @param phase Identifier of the phase this listener should be registered for. It will be created if it didn't exist yet.\n\t * @param listener The desired listener.\n\t */\n\tpublic void register(ResourceLocation phase, T listener) {\n\t\t// This is done to keep compatibility with existing Event subclasses, but they should really not be subclassing Event.\n\t\tregister(listener);\n\t}\n\n\t/**\n\t * Request that listeners registered for one phase be executed before listeners registered for another phase.\n\t * registering phase ordering dependencies.\n\t *\n\t * <p>Incompatible ordering constraints such as cycles will lead to inconsistent behavior:\n\t * some constraints will be respected and some will be ignored. If this happens, a warning will be logged.\n\t *\n\t * @param firstPhase The identifier of the phase that should run before the other. It will be created if it didn't exist yet.\n\t * @param secondPhase The identifier of the phase that should run after the other. It will be created if it didn't exist yet.\n\t */\n\tpublic void addPhaseOrdering(ResourceLocation firstPhase, ResourceLocation secondPhase) {\n\t\t// This is not abstract to avoid breaking existing Event subclasses, but they should really not be subclassing Event.\n\t}\n}"
},
{
"identifier": "EventFactory",
"path": "Common/src/main/java/com/natamus/collective/implementations/event/EventFactory.java",
"snippet": "public final class EventFactory {\n\tprivate EventFactory() { }\n\n\t/**\n\t * Create an \"array-backed\" Event instance.\n\t *\n\t * <p>If your factory simply delegates to the listeners without adding custom behavior,\n\t * consider using {@linkplain #createArrayBacked(Class, Object, Function) the other overload}\n\t * if performance of this event is critical.\n\t *\n\t * @param type The listener class type.\n\t * @param invokerFactory The invoker factory, combining multiple listeners into one instance.\n\t * @param <T> The listener type.\n\t * @return The Event instance.\n\t */\n\tpublic static <T> Event<T> createArrayBacked(Class<? super T> type, Function<T[], T> invokerFactory) {\n\t\treturn EventFactoryImpl.createArrayBacked(type, invokerFactory);\n\t}\n\n\t/**\n\t * Create an \"array-backed\" Event instance with a custom empty invoker,\n\t * for an event whose {@code invokerFactory} only delegates to the listeners.\n\t * <ul>\n\t * <li>If there is no listener, the custom empty invoker will be used.</li>\n\t * <li><b>If there is only one listener, that one will be used as the invoker\n\t * and the factory will not be called.</b></li>\n\t * <li>Only when there are at least two listeners will the factory be used.</li>\n\t * </ul>\n\t *\n\t * <p>Having a custom empty invoker (of type (...) -> {}) increases performance\n\t * relative to iterating over an empty array; however, it only really matters\n\t * if the event is executed thousands of times a second.\n\t *\n\t * @param type The listener class type.\n\t * @param emptyInvoker The custom empty invoker.\n\t * @param invokerFactory The invoker factory, combining multiple listeners into one instance.\n\t * @param <T> The listener type.\n\t * @return The Event instance.\n\t */\n\tpublic static <T> Event<T> createArrayBacked(Class<T> type, T emptyInvoker, Function<T[], T> invokerFactory) {\n\t\treturn createArrayBacked(type, listeners -> {\n\t\t\tif (listeners.length == 0) {\n\t\t\t\treturn emptyInvoker;\n\t\t\t} else if (listeners.length == 1) {\n\t\t\t\treturn listeners[0];\n\t\t\t} else {\n\t\t\t\treturn invokerFactory.apply(listeners);\n\t\t\t}\n\t\t});\n\t}\n\n\t/**\n\t * Create an array-backed event with a list of default phases that get invoked in order.\n\t * Exposing the identifiers of the default phases as {@code public static final} constants is encouraged.\n\t *\n\t * <p>An event phase is a named group of listeners, which may be ordered before or after other groups of listeners.\n\t * This allows some listeners to take priority over other listeners.\n\t * Adding separate events should be considered before making use of multiple event phases.\n\t *\n\t * <p>Phases may be freely added to events created with any of the factory functions,\n\t * however using this function is preferred for widely used event phases.\n\t * If more phases are necessary, discussion with the author of the Event is encouraged.\n\t *\n\t * <p>Refer to {@link Event#addPhaseOrdering} for an explanation of event phases.\n\t *\n\t * @param type The listener class type.\n\t * @param invokerFactory The invoker factory, combining multiple listeners into one instance.\n\t * @param defaultPhases The default phases of this event, in the correct order. Must contain {@link Event#DEFAULT_PHASE}.\n\t * @param <T> The listener type.\n\t * @return The Event instance.\n\t */\n\tpublic static <T> Event<T> createWithPhases(Class<? super T> type, Function<T[], T> invokerFactory, ResourceLocation... defaultPhases) {\n\t\tEventFactoryImpl.ensureContainsDefault(defaultPhases);\n\t\tEventFactoryImpl.ensureNoDuplicates(defaultPhases);\n\n\t\tEvent<T> event = createArrayBacked(type, invokerFactory);\n\n\t\tfor (int i = 1; i < defaultPhases.length; ++i) {\n\t\t\tevent.addPhaseOrdering(defaultPhases[i-1], defaultPhases[i]);\n\t\t}\n\n\t\treturn event;\n\t}\n\n\t/**\n\t * @deprecated This is not to be used in events anymore.\n\t */\n\t@Deprecated\n\tpublic static String getHandlerName(Object handler) {\n\t\treturn handler.getClass().getName();\n\t}\n\n\t/**\n\t * @deprecated Always returns {@code false}, do not use. This is not to be used in events anymore, standard Java profilers will do fine.\n\t */\n\t@Deprecated\n\tpublic static boolean isProfilingEnabled() {\n\t\treturn false;\n\t}\n\n\t/**\n\t * Invalidate and re-create all existing \"invoker\" instances across\n\t * events created by this EventFactory. Use this if, for instance,\n\t * the profilingEnabled field changes.\n\t *\n\t * @deprecated Do not use, will be removed in a future release.\n\t */\n\t@Deprecated(forRemoval = true)\n\tpublic static void invalidate() {\n\t\tEventFactoryImpl.invalidate();\n\t}\n}"
}
] | import com.natamus.collective.implementations.event.Event;
import com.natamus.collective.implementations.event.EventFactory; | 1,924 | package com.natamus.collective.globalcallbacks;
public class MainMenuLoadedCallback {
private MainMenuLoadedCallback() { }
| package com.natamus.collective.globalcallbacks;
public class MainMenuLoadedCallback {
private MainMenuLoadedCallback() { }
| public static final Event<On_Main_Menu_Loaded> MAIN_MENU_LOADED = EventFactory.createArrayBacked(On_Main_Menu_Loaded.class, callbacks -> () -> { | 0 | 2023-12-11 22:37:15+00:00 | 4k |
MrXiaoM/plugin-template | src/main/java/top/mrxiaom/example/func/AbstractPluginHolder.java | [
{
"identifier": "ColorHelper",
"path": "src/main/java/top/mrxiaom/example/utils/ColorHelper.java",
"snippet": "public class ColorHelper {\n private static final Pattern startWithColor = Pattern.compile(\"^(&[LMNKOlmnko])+\");\n private static final Pattern gradientPattern = Pattern.compile(\"\\\\{(#[ABCDEFabcdef0123456789]{6}):(#[ABCDEFabcdef0123456789]{6}):(.*?)}\");\n private static final Pattern hexPattern = Pattern.compile(\"&(#[ABCDEFabcdef0123456789]{6})\");\n\n public static String parseColor(String s) {\n String fin = parseHexText(s);\n fin = parseGradientText(fin);\n return fin.replace(\"&\", \"§\");\n }\n public static String parseHexText(String s) {\n return String.join(\"\", split(hexPattern, s, regexResult -> {\n if (!regexResult.isMatched) return regexResult.text;\n String hex = regexResult.text.substring(1);\n return parseHex(hex);\n }));\n }\n public static String parseGradientText(String s) {\n return String.join(\"\", split(gradientPattern, s, regexResult -> {\n if (!regexResult.isMatched) return regexResult.text;\n String[] args = regexResult.text.substring(1, regexResult.text.length() - 1).split(\":\", 3);\n String extra = \"\";\n Matcher m = startWithColor.matcher(args[2]);\n if (m.find()) {\n extra = ChatColor.translateAlternateColorCodes('&', m.group());\n }\n return parseGradient(m.replaceAll(\"\"), extra, args[0], args[1]);\n }));\n }\n /**\n * 生成 Minecraft 1.16+ 渐变颜色文字\n * @param s 字符串\n * @param extraFormat 额外样式\n * @param startHex 开始颜色 (#XXXXXX)\n * @param endHex 结束颜色 (#XXXXXX)\n * @return 渐变文字\n */\n public static String parseGradient(String s, String extraFormat, String startHex, String endHex) {\n s = s.replaceAll(\"[&§].\", \"\");\n int color1 = hex(startHex);\n int color2 = hex(endHex);\n int[] colors = createGradient(color1, color2, s.length());\n StringBuilder result = new StringBuilder();\n for (int i = 0; i < colors.length; i++) {\n result.append(hexToMc(colors[i])).append(extraFormat).append(s.charAt(i));\n }\n return result.toString();\n }\n\n /**\n * 生成 Minecraft 1.16+ 16进制颜色代码\n * @param hex 16进制颜色 (#XXXXXX)\n * @return 颜色代码\n */\n public static String parseHex(String hex) {\n StringBuilder result = new StringBuilder(\"§x\");\n for (char c : hex.substring(1, hex.length() - 1).toLowerCase().toCharArray()) {\n result.append('§').append(c);\n }\n result.append(\"§F\");\n return result.toString();\n }\n public static int[] createGradient(int startHex, int endHex, int step) {\n if (step == 1) return new int[] { startHex };\n\n int[] colors = new int[step];\n int[] start = hexToRGB(startHex);\n int[] end = hexToRGB(endHex);\n\n int stepR = (end[0] - start[0]) / (step - 1);\n int stepG = (end[1] - start[1]) / (step - 1);\n int stepB = (end[2] - start[2]) / (step - 1);\n\n for (int i = 0; i < step; i++) {\n colors[i] = rgbToHex(\n start[0] + stepR * i,\n start[1] + stepG * i,\n start[2] + stepB * i\n );\n }\n return colors;\n }\n public static String hexToMc(int hex) {\n return parseHex(hex(hex));\n }\n public static int hex(String hex) {\n return Integer.parseInt(hex.substring(1), 16);\n }\n public static String hex(int hex) {\n return \"#\" + String.format(\"%06x\", hex);\n }\n public static int[] hexToRGB(int hex) {\n return new int[] {\n (hex >> 16) & 0xff,\n (hex >> 8) & 0xff,\n hex & 0xff\n };\n }\n public static int rgbToHex(int r, int g, int b) {\n return (r << 16) + (g << 8) + b;\n }\n}"
},
{
"identifier": "ExamplePlugin",
"path": "src/main/java/top/mrxiaom/example/ExamplePlugin.java",
"snippet": "@SuppressWarnings({\"unused\"})\npublic class ExamplePlugin extends JavaPlugin implements Listener, TabCompleter {\n private static ExamplePlugin instance;\n public static ExamplePlugin getInstance() {\n return instance;\n }\n private GuiManager guiManager = null;\n Placeholder papi = null;\n Economy economy;\n public GuiManager getGuiManager() {\n return guiManager;\n }\n @NotNull\n public Economy getEconomy() {\n return economy;\n }\n @NotNull\n public Placeholder getPapi() {\n return papi;\n }\n @Override\n public void onEnable() {\n instance = this;\n\n loadHooks();\n\n loadFunctions();\n reloadConfig();\n\n Bukkit.getPluginManager().registerEvents(this, this);\n\n getLogger().info(\"插件加载完毕\");\n }\n\n public void loadFunctions() {\n try {\n for (Class<?> clazz : Lists.newArrayList(\n CommandMain.class, DatabaseManager.class\n )) {\n clazz.getDeclaredConstructor(getClass()).newInstance(this);\n }\n } catch (Throwable t) {\n t.printStackTrace();\n }\n guiManager = new GuiManager(this);\n }\n\n public void loadHooks() {\n RegisteredServiceProvider<Economy> economyProvider = Bukkit.getServicesManager().getRegistration(Economy.class);\n if (economyProvider != null) {\n economy = economyProvider.getProvider();\n }\n Util.registerPlaceholder(getLogger(), papi = new Placeholder(this));\n }\n\n @Override\n public void onDisable() {\n AbstractPluginHolder.disableAllModule();\n getLogger().info(\"插件已卸载\");\n }\n\n @Override\n public void reloadConfig() {\n this.saveDefaultConfig();\n super.reloadConfig();\n\n FileConfiguration config = getConfig();\n AbstractPluginHolder.reloadAllConfig(config);\n }\n}"
},
{
"identifier": "Util",
"path": "src/main/java/top/mrxiaom/example/utils/Util.java",
"snippet": "@SuppressWarnings({\"unused\"})\npublic class Util {\n public static String getPlayerName(String s) {\n return getOnlinePlayer(s).map(HumanEntity::getName).orElse(s);\n }\n\n public static Optional<OfflinePlayer> getOfflinePlayer(String s) {\n for (OfflinePlayer p : Bukkit.getOfflinePlayers()) {\n if (p.getName() != null && p.getName().equalsIgnoreCase(s)) {\n return Optional.of(p);\n }\n }\n return Optional.empty();\n }\n\n public static List<String> startsWith(String s, String... texts) {\n return startsWith(s, Lists.newArrayList(texts));\n }\n public static List<String> startsWith(String s, Iterable<String> texts) {\n List<String> list = new ArrayList<>();\n s = s.toLowerCase();\n for (String text : texts) {\n if (text.toLowerCase().startsWith(s)) list.add(text);\n }\n return list;\n }\n public static Location toLocation(String world, String loc) {\n Location l = null;\n try {\n String[] s = loc.split(\",\");\n double x = Double.parseDouble(s[0].trim());\n double y = Double.parseDouble(s[1].trim());\n double z = Double.parseDouble(s[2].trim());\n float yaw = s.length > 3 ? Float.parseFloat(s[3].trim()) : 0;\n float pitch = s.length > 4 ? Float.parseFloat(s[4].trim()) : 0;\n l = new Location(Bukkit.getWorld(world), x, y, z, yaw, pitch);\n } catch (Throwable ignored) {\n }\n return l;\n }\n\n public static String toString(Location loc) {\n return String.format(\"%.2f, %.2f, %.2f, %.2f, %.2f\", loc.getX(), loc.getY(), loc.getZ(), loc.getYaw(), loc.getPitch());\n }\n public static Optional<Player> getOnlinePlayer(String name) {\n for (Player player : Bukkit.getOnlinePlayers()) {\n if (player.getName().equalsIgnoreCase(name)) return Optional.of(player);\n }\n return Optional.empty();\n }\n public static List<Player> getOnlinePlayers(List<UUID> uuidList) {\n List<Player> players = new ArrayList<>();\n for (Player player : Bukkit.getOnlinePlayers()) {\n if (uuidList.contains(player.getUniqueId())) players.add(player);\n }\n return players;\n }\n public static Optional<Double> parseDouble(String s) {\n if (s == null) return Optional.empty();\n try {\n return Optional.of(Double.parseDouble(s));\n } catch (NumberFormatException e) {\n return Optional.empty();\n }\n }\n public static Optional<Integer> parseInt(String s) {\n if (s == null) return Optional.empty();\n try {\n return Optional.of(Integer.parseInt(s));\n } catch (NumberFormatException e) {\n return Optional.empty();\n }\n }\n public static Optional<Long> parseLong(String s) {\n if (s == null) return Optional.empty();\n try {\n return Optional.of(Long.parseLong(s));\n } catch (NumberFormatException e) {\n return Optional.empty();\n }\n }\n public static <T extends Enum<?>> T valueOr(Class<T> c, String s, T def) {\n if (s == null) return def;\n for (T t : c.getEnumConstants()) {\n if (t.name().equalsIgnoreCase(s)) return t;\n }\n return def;\n }\n\n public static void registerPlaceholder(Logger logger, PlaceholderExpansion placeholder) {\n PlaceholderAPIPlugin.getInstance()\n .getLocalExpansionManager()\n .findExpansionByIdentifier(placeholder.getIdentifier())\n .ifPresent(PlaceholderExpansion::unregister);\n if (placeholder.isRegistered()) return;\n if (!placeholder.register()) {\n logger.info(\"无法注册 \" + placeholder.getName() + \" PAPI 变量\");\n }\n }\n\n public static boolean isMoved(PlayerMoveEvent e) {\n Location loc1 = e.getFrom();\n Location loc2 = e.getTo();\n return loc1.getBlockX() != loc2.getBlockX()\n || loc1.getBlockZ() != loc2.getBlockZ();\n }\n\n public static boolean isPresent(String className) {\n try {\n Class.forName(className);\n return true;\n } catch (ClassNotFoundException ignored) {\n return false;\n }\n }\n\n public static String stackTraceToString(Throwable t) {\n StringWriter sw = new StringWriter();\n try (PrintWriter pw = new PrintWriter(sw)) {\n t.printStackTrace(pw);\n }\n return sw.toString();\n }\n\n public static <T> List<T> split(Pattern regex, String s, Function<RegexResult, T> transform) {\n List<T> list = new ArrayList<>();\n int index = 0;\n Matcher m = regex.matcher(s);\n while (m.find()) {\n int first = m.start();\n int last = m.end();\n if (first > index) {\n T value = transform.apply(new RegexResult(false, s.substring(index, first)));\n if (value != null) list.add(value);\n }\n T value = transform.apply(new RegexResult(true, s.substring(first, last)));\n if (value != null) list.add(value);\n index = last;\n }\n if (index < s.length()) {\n T value = transform.apply(new RegexResult(false, s.substring(index)));\n if (value != null) list.add(value);\n }\n return list;\n }\n\n public static class RegexResult {\n public boolean isMatched;\n public String text;\n\n public RegexResult(boolean isMatched, String text) {\n this.isMatched = isMatched;\n this.text = text;\n }\n }\n}"
}
] | import org.bukkit.Bukkit;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.command.PluginCommand;
import org.bukkit.command.TabCompleter;
import org.bukkit.configuration.MemoryConfiguration;
import org.bukkit.event.Listener;
import org.jetbrains.annotations.Nullable;
import top.mrxiaom.example.utils.ColorHelper;
import top.mrxiaom.example.ExamplePlugin;
import top.mrxiaom.example.utils.Util;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional; | 3,467 | package top.mrxiaom.example.func;
@SuppressWarnings({"unused"})
public abstract class AbstractPluginHolder {
private static final Map<Class<?>, AbstractPluginHolder> registeredHolders = new HashMap<>();
public final ExamplePlugin plugin;
public AbstractPluginHolder(ExamplePlugin plugin) {
this.plugin = plugin;
}
public void reloadConfig(MemoryConfiguration config) {
}
public void onDisable() {
}
protected void registerEvents(Listener listener) {
try {
Bukkit.getPluginManager().registerEvents(listener, plugin);
} catch (Throwable t) {
warn("在注册事件监听器 " + this.getClass().getSimpleName() + " 时出现一个异常", t);
}
}
protected void registerCommand(String label, Object inst) {
PluginCommand command = plugin.getCommand(label);
if (command != null) {
if (inst instanceof CommandExecutor){
command.setExecutor((CommandExecutor) inst);
} else{
warn(inst.getClass().getSimpleName() + " 不是一个命令执行器");
}
if (inst instanceof TabCompleter) command.setTabCompleter((TabCompleter) inst);
} else {
info("无法注册命令 /" + label);
}
}
protected void register() {
registeredHolders.put(getClass(), this);
}
protected void unregister() {
registeredHolders.remove(getClass());
}
protected boolean isRegistered() {
return registeredHolders.containsKey(getClass());
}
public void info(String... lines) {
for (String line : lines) {
plugin.getLogger().info(line);
}
}
public void warn(String... lines) {
for (String line : lines) {
plugin.getLogger().warning(line);
}
}
public void warn(String s, Throwable t) {
plugin.getLogger().warning(s); | package top.mrxiaom.example.func;
@SuppressWarnings({"unused"})
public abstract class AbstractPluginHolder {
private static final Map<Class<?>, AbstractPluginHolder> registeredHolders = new HashMap<>();
public final ExamplePlugin plugin;
public AbstractPluginHolder(ExamplePlugin plugin) {
this.plugin = plugin;
}
public void reloadConfig(MemoryConfiguration config) {
}
public void onDisable() {
}
protected void registerEvents(Listener listener) {
try {
Bukkit.getPluginManager().registerEvents(listener, plugin);
} catch (Throwable t) {
warn("在注册事件监听器 " + this.getClass().getSimpleName() + " 时出现一个异常", t);
}
}
protected void registerCommand(String label, Object inst) {
PluginCommand command = plugin.getCommand(label);
if (command != null) {
if (inst instanceof CommandExecutor){
command.setExecutor((CommandExecutor) inst);
} else{
warn(inst.getClass().getSimpleName() + " 不是一个命令执行器");
}
if (inst instanceof TabCompleter) command.setTabCompleter((TabCompleter) inst);
} else {
info("无法注册命令 /" + label);
}
}
protected void register() {
registeredHolders.put(getClass(), this);
}
protected void unregister() {
registeredHolders.remove(getClass());
}
protected boolean isRegistered() {
return registeredHolders.containsKey(getClass());
}
public void info(String... lines) {
for (String line : lines) {
plugin.getLogger().info(line);
}
}
public void warn(String... lines) {
for (String line : lines) {
plugin.getLogger().warning(line);
}
}
public void warn(String s, Throwable t) {
plugin.getLogger().warning(s); | plugin.getLogger().warning(Util.stackTraceToString(t)); | 2 | 2023-12-08 15:50:57+00:00 | 4k |
ExcaliburFRC/2024RobotTamplate | src/main/java/frc/robot/Constants.java | [
{
"identifier": "Color",
"path": "src/main/java/frc/lib/Color.java",
"snippet": "public class Color extends edu.wpi.first.wpilibj.util.Color {\n public Color(double red, double green, double blue) {\n super(green, red, blue);\n }\n\n public Color(int red, int green, int blue) {\n super(green, red, blue);\n }\n\n public Color(){\n super(0, 0, 0);\n }\n\n public static Color balance(Color color) {\n double v = Math.max(Math.max(color.red, color.green), color.blue);\n Color newColor = new Color(color.red, color.green / 2, color.blue / 4);\n double newV = Math.max(Math.max(newColor.red, newColor.green), newColor.blue);\n double ratio = v / newV;\n return new Color(newColor.red * ratio, newColor.green * ratio, newColor.blue * ratio);\n }\n\n public enum Colors {\n OFF(new Color(0, 0, 0)),\n\n TEAM_GOLD(new Color(255, 170, 0)),\n TEAM_BLUE(new Color(1, 30, 202)),\n\n RED(new Color(255, 0, 0)),\n GREEN(new Color(0, 255, 0)),\n BLUE(new Color(0, 0, 255)),\n\n WHITE(new Color(255, 255, 255)),\n\n YELLOW(new Color(255, 255, 0)),\n CYAN(new Color(0, 255, 255)),\n PINK(new Color(255, 0, 255)),\n\n ORANGE(new Color(255, 165, 0)),\n PURPLE(new Color(75, 0, 130));\n\n // TODO: add more colors\n\n public final Color color;\n\n Colors(Color color) {\n this.color = color;\n }\n }\n}"
},
{
"identifier": "Gains",
"path": "src/main/java/frc/lib/Gains.java",
"snippet": "public class Gains {\n public double kp, ki, kd;\n public double ks, kg, kv, ka;\n\n private Gains(double kp, double ki, double kd, double ks, double kg, double kv, double ka) {\n this.kp = kp;\n this.ki = ki;\n this.kd = kd;\n this.ks = ks;\n this.kg = kg;\n this.kv = kv;\n this.ka = ka;\n }\n\n public Gains(double kp, double ki, double kd) {\n this(kp, ki, kd, 0, 0, 0, 0);\n }\n\n public Gains(double ks, double kg, double kv, double ka) {\n this(0, 0, 0, ks, kg, kv, ka);\n }\n\n public void setPIDgains(double kp, double ki, double kd) {\n this.kp = kp;\n this.ki = ki;\n this.kd = kd;\n }\n\n public void setFeedForwardGains(double ks, double kg, double kv, double ka) {\n this.ks = ks;\n this.kg = kg;\n this.kv = kv;\n this.ka = ka;\n }\n}"
}
] | import com.pathplanner.lib.path.PathConstraints;
import edu.wpi.first.math.geometry.Translation2d;
import edu.wpi.first.math.kinematics.SwerveDriveKinematics;
import edu.wpi.first.math.util.Units;
import frc.lib.Color;
import frc.lib.Gains;
import static java.lang.Math.PI; | 2,080 | // Copyright (c) FIRST and other WPILib contributors.
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
package frc.robot;
/**
* The Constants class provides a convenient place for teams to hold robot-wide numerical or boolean
* constants. This class should not be used for any other purpose. All constants should be declared
* globally (i.e. public static). Do not put anything functional in this class.
*
* <p>It is advised to statically import this class (or one of its inner classes) wherever the
* constants are needed, to reduce verbosity.
*/
public final class Constants {
public static final class SwerveConstants {
public enum Modules {
// drive ID, spin ID, abs encoder channel, offset angle, drive reversed, angle reversed
FL(18, 17, 5, 0.842, true, true),
FR(12, 11, 9, 0.122, true, true),
BL(16, 15, 4, 0.55, true, true),
BR(14, 13, 8, 0.3339, true, true);
public int DRIVE_MOTOR_ID;
public int SPIN_MOTOR_ID;
public int ABS_ENCODER_CHANNEL;
public double OFFSET_ANGLE;
public boolean DRIVE_MOTOR_REVERSED;
public boolean SPIN_MOTOR_REVERSED;
public static final int FRONT_LEFT = 0;
public static final int FRONT_RIGHT = 1;
public static final int BACK_LEFT = 2;
public static final int BACK_RIGHT = 3;
Modules(int DRIVE_MOTOR_ID,
int SPIN_MOTOR_ID,
int ABS_ENCODER_CHANNEL,
double OFFSET_ANGLE,
boolean DRIVE_MOTOR_REVERSED,
boolean SPIN_MOTOR_REVERSED) {
this.DRIVE_MOTOR_ID = DRIVE_MOTOR_ID;
this.SPIN_MOTOR_ID = SPIN_MOTOR_ID;
this.ABS_ENCODER_CHANNEL = ABS_ENCODER_CHANNEL;
this.OFFSET_ANGLE = OFFSET_ANGLE;
this.DRIVE_MOTOR_REVERSED = DRIVE_MOTOR_REVERSED;
this.SPIN_MOTOR_REVERSED = SPIN_MOTOR_REVERSED;
}
}
public static final double TRACK_WIDTH = 0.56665; // m
public static final SwerveDriveKinematics kSwerveKinematics = new SwerveDriveKinematics(
new Translation2d(TRACK_WIDTH / 2, TRACK_WIDTH / 2),
new Translation2d(TRACK_WIDTH / 2, -TRACK_WIDTH / 2),
new Translation2d(-TRACK_WIDTH / 2, TRACK_WIDTH / 2),
new Translation2d(-TRACK_WIDTH / 2, -TRACK_WIDTH / 2));
public static final double MAX_VELOCITY_METER_PER_SECOND = Units.feetToMeters(12); //TODO: find values
public static final double MAX_VELOCITY_ACCELERATION_METER_PER_SECOND = 3; //TODO: find values
public static final double MAX_ANGULAR_VELOCITY_RAD_PER_SECOND = 2 * PI; //TODO: find values
public static final double MAX_ANGULAR_ACCELERATION_RAD_PER_SECOND = 2 * 2 * PI; //TODO: find values
// intentional limitations
public static final double DRIVE_SPEED_PERCENTAGE = 20; // %
// autonomous constants
public static final Gains ANGLE_GAINS = new Gains(0.12, 0, 0.00015);
public static final Gains TRANSLATION_GAINS = new Gains(0, 0, 0);
public static final Gains PATHPLANNER_ANGLE_GAINS = new Gains(3.5, 0, 0);
public static final Gains PATHPLANNER_TRANSLATION_GAINS = new Gains(2.5, 0, 0);
public static final PathConstraints PATH_CONSTRAINTS = new PathConstraints(
MAX_VELOCITY_METER_PER_SECOND, MAX_VELOCITY_ACCELERATION_METER_PER_SECOND,
MAX_ANGULAR_VELOCITY_RAD_PER_SECOND, MAX_ANGULAR_ACCELERATION_RAD_PER_SECOND);
public static final double FIELD_LENGTH_METERS = 16.54175;
public static final double FIELD_WIDTH_METERS = 8.02;
}
public static final class ModuleConstants {
public static final double kWheelDiameterMeters = Units.inchesToMeters(4);
public static final double kDriveMotorGearRatio = 1 / 8.14;
public static final double kDriveEncoderRotationsToMeters = kDriveMotorGearRatio * PI * kWheelDiameterMeters;
public static final double kDriveEncoderRPMToMeterPerSec = kDriveEncoderRotationsToMeters / 60;
public static final double kTurningMotorGearRatio = 1 / 21.4285714;
public static final double kTurningEncoderRotationsToRadians = kTurningMotorGearRatio * 2 * PI;
public static final double kTurningEncoderRPMToRadiansPerSec = kTurningEncoderRotationsToRadians / 60;
public static final Gains MODULE_ANGLE_GAINS = new Gains(0.75, 0, 0);
public static final double TOLERANCE = 0.05;
public static final int DRIVE_CURRENT_LIMIT = 65;
public static final int ANGLE_CURRENT_LIMIT = 25;
}
public static class LedsConstants {
public static final int LEDS_PORT = 0; // pwm
public static final int LENGTH = 139;
public enum GamePiece { | // Copyright (c) FIRST and other WPILib contributors.
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
package frc.robot;
/**
* The Constants class provides a convenient place for teams to hold robot-wide numerical or boolean
* constants. This class should not be used for any other purpose. All constants should be declared
* globally (i.e. public static). Do not put anything functional in this class.
*
* <p>It is advised to statically import this class (or one of its inner classes) wherever the
* constants are needed, to reduce verbosity.
*/
public final class Constants {
public static final class SwerveConstants {
public enum Modules {
// drive ID, spin ID, abs encoder channel, offset angle, drive reversed, angle reversed
FL(18, 17, 5, 0.842, true, true),
FR(12, 11, 9, 0.122, true, true),
BL(16, 15, 4, 0.55, true, true),
BR(14, 13, 8, 0.3339, true, true);
public int DRIVE_MOTOR_ID;
public int SPIN_MOTOR_ID;
public int ABS_ENCODER_CHANNEL;
public double OFFSET_ANGLE;
public boolean DRIVE_MOTOR_REVERSED;
public boolean SPIN_MOTOR_REVERSED;
public static final int FRONT_LEFT = 0;
public static final int FRONT_RIGHT = 1;
public static final int BACK_LEFT = 2;
public static final int BACK_RIGHT = 3;
Modules(int DRIVE_MOTOR_ID,
int SPIN_MOTOR_ID,
int ABS_ENCODER_CHANNEL,
double OFFSET_ANGLE,
boolean DRIVE_MOTOR_REVERSED,
boolean SPIN_MOTOR_REVERSED) {
this.DRIVE_MOTOR_ID = DRIVE_MOTOR_ID;
this.SPIN_MOTOR_ID = SPIN_MOTOR_ID;
this.ABS_ENCODER_CHANNEL = ABS_ENCODER_CHANNEL;
this.OFFSET_ANGLE = OFFSET_ANGLE;
this.DRIVE_MOTOR_REVERSED = DRIVE_MOTOR_REVERSED;
this.SPIN_MOTOR_REVERSED = SPIN_MOTOR_REVERSED;
}
}
public static final double TRACK_WIDTH = 0.56665; // m
public static final SwerveDriveKinematics kSwerveKinematics = new SwerveDriveKinematics(
new Translation2d(TRACK_WIDTH / 2, TRACK_WIDTH / 2),
new Translation2d(TRACK_WIDTH / 2, -TRACK_WIDTH / 2),
new Translation2d(-TRACK_WIDTH / 2, TRACK_WIDTH / 2),
new Translation2d(-TRACK_WIDTH / 2, -TRACK_WIDTH / 2));
public static final double MAX_VELOCITY_METER_PER_SECOND = Units.feetToMeters(12); //TODO: find values
public static final double MAX_VELOCITY_ACCELERATION_METER_PER_SECOND = 3; //TODO: find values
public static final double MAX_ANGULAR_VELOCITY_RAD_PER_SECOND = 2 * PI; //TODO: find values
public static final double MAX_ANGULAR_ACCELERATION_RAD_PER_SECOND = 2 * 2 * PI; //TODO: find values
// intentional limitations
public static final double DRIVE_SPEED_PERCENTAGE = 20; // %
// autonomous constants
public static final Gains ANGLE_GAINS = new Gains(0.12, 0, 0.00015);
public static final Gains TRANSLATION_GAINS = new Gains(0, 0, 0);
public static final Gains PATHPLANNER_ANGLE_GAINS = new Gains(3.5, 0, 0);
public static final Gains PATHPLANNER_TRANSLATION_GAINS = new Gains(2.5, 0, 0);
public static final PathConstraints PATH_CONSTRAINTS = new PathConstraints(
MAX_VELOCITY_METER_PER_SECOND, MAX_VELOCITY_ACCELERATION_METER_PER_SECOND,
MAX_ANGULAR_VELOCITY_RAD_PER_SECOND, MAX_ANGULAR_ACCELERATION_RAD_PER_SECOND);
public static final double FIELD_LENGTH_METERS = 16.54175;
public static final double FIELD_WIDTH_METERS = 8.02;
}
public static final class ModuleConstants {
public static final double kWheelDiameterMeters = Units.inchesToMeters(4);
public static final double kDriveMotorGearRatio = 1 / 8.14;
public static final double kDriveEncoderRotationsToMeters = kDriveMotorGearRatio * PI * kWheelDiameterMeters;
public static final double kDriveEncoderRPMToMeterPerSec = kDriveEncoderRotationsToMeters / 60;
public static final double kTurningMotorGearRatio = 1 / 21.4285714;
public static final double kTurningEncoderRotationsToRadians = kTurningMotorGearRatio * 2 * PI;
public static final double kTurningEncoderRPMToRadiansPerSec = kTurningEncoderRotationsToRadians / 60;
public static final Gains MODULE_ANGLE_GAINS = new Gains(0.75, 0, 0);
public static final double TOLERANCE = 0.05;
public static final int DRIVE_CURRENT_LIMIT = 65;
public static final int ANGLE_CURRENT_LIMIT = 25;
}
public static class LedsConstants {
public static final int LEDS_PORT = 0; // pwm
public static final int LENGTH = 139;
public enum GamePiece { | CONE(Color.Colors.PURPLE), | 0 | 2023-12-13 22:33:35+00:00 | 4k |
muchfish/ruoyi-vue-pro-sample | yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/controller/admin/notice/NoticeController.java | [
{
"identifier": "CommonResult",
"path": "yudao-framework/yudao-common/src/main/java/cn/iocoder/yudao/framework/common/pojo/CommonResult.java",
"snippet": "@Data\npublic class CommonResult<T> implements Serializable {\n\n /**\n * 错误码\n *\n * @see ErrorCode#getCode()\n */\n private Integer code;\n /**\n * 返回数据\n */\n private T data;\n /**\n * 错误提示,用户可阅读\n *\n * @see ErrorCode#getMsg() ()\n */\n private String msg;\n\n /**\n * 将传入的 result 对象,转换成另外一个泛型结果的对象\n *\n * 因为 A 方法返回的 CommonResult 对象,不满足调用其的 B 方法的返回,所以需要进行转换。\n *\n * @param result 传入的 result 对象\n * @param <T> 返回的泛型\n * @return 新的 CommonResult 对象\n */\n public static <T> CommonResult<T> error(CommonResult<?> result) {\n return error(result.getCode(), result.getMsg());\n }\n\n public static <T> CommonResult<T> error(Integer code, String message) {\n Assert.isTrue(!GlobalErrorCodeConstants.SUCCESS.getCode().equals(code), \"code 必须是错误的!\");\n CommonResult<T> result = new CommonResult<>();\n result.code = code;\n result.msg = message;\n return result;\n }\n\n public static <T> CommonResult<T> error(ErrorCode errorCode) {\n return error(errorCode.getCode(), errorCode.getMsg());\n }\n\n public static <T> CommonResult<T> success(T data) {\n CommonResult<T> result = new CommonResult<>();\n result.code = GlobalErrorCodeConstants.SUCCESS.getCode();\n result.data = data;\n result.msg = \"\";\n return result;\n }\n\n public static boolean isSuccess(Integer code) {\n return Objects.equals(code, GlobalErrorCodeConstants.SUCCESS.getCode());\n }\n\n @JsonIgnore // 避免 jackson 序列化\n public boolean isSuccess() {\n return isSuccess(code);\n }\n\n @JsonIgnore // 避免 jackson 序列化\n public boolean isError() {\n return !isSuccess();\n }\n\n // ========= 和 Exception 异常体系集成 =========\n\n /**\n * 判断是否有异常。如果有,则抛出 {@link ServiceException} 异常\n */\n public void checkError() throws ServiceException {\n if (isSuccess()) {\n return;\n }\n // 业务异常\n throw new ServiceException(code, msg);\n }\n\n /**\n * 判断是否有异常。如果有,则抛出 {@link ServiceException} 异常\n * 如果没有,则返回 {@link #data} 数据\n */\n @JsonIgnore // 避免 jackson 序列化\n public T getCheckedData() {\n checkError();\n return data;\n }\n\n public static <T> CommonResult<T> error(ServiceException serviceException) {\n return error(serviceException.getCode(), serviceException.getMessage());\n }\n\n}"
},
{
"identifier": "PageResult",
"path": "yudao-framework/yudao-common/src/main/java/cn/iocoder/yudao/framework/common/pojo/PageResult.java",
"snippet": "@Schema(description = \"分页结果\")\n@Data\npublic final class PageResult<T> implements Serializable {\n\n @Schema(description = \"数据\", requiredMode = Schema.RequiredMode.REQUIRED)\n private List<T> list;\n\n @Schema(description = \"总量\", requiredMode = Schema.RequiredMode.REQUIRED)\n private Long total;\n\n public PageResult() {\n }\n\n public PageResult(List<T> list, Long total) {\n this.list = list;\n this.total = total;\n }\n\n public PageResult(Long total) {\n this.list = new ArrayList<>();\n this.total = total;\n }\n\n public static <T> PageResult<T> empty() {\n return new PageResult<>(0L);\n }\n\n public static <T> PageResult<T> empty(Long total) {\n return new PageResult<>(total);\n }\n\n}"
},
{
"identifier": "NoticeCreateReqVO",
"path": "yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/controller/admin/notice/vo/NoticeCreateReqVO.java",
"snippet": "@Schema(description = \"管理后台 - 通知公告创建 Request VO\")\n@Data\n@EqualsAndHashCode(callSuper = true)\npublic class NoticeCreateReqVO extends NoticeBaseVO {\n}"
},
{
"identifier": "NoticePageReqVO",
"path": "yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/controller/admin/notice/vo/NoticePageReqVO.java",
"snippet": "@Schema(description = \"管理后台 - 通知公告分页 Request VO\")\n@Data\n@EqualsAndHashCode(callSuper = true)\npublic class NoticePageReqVO extends PageParam {\n\n @Schema(description = \"通知公告名称,模糊匹配\", example = \"芋道\")\n private String title;\n\n @Schema(description = \"展示状态,参见 CommonStatusEnum 枚举类\", example = \"1\")\n private Integer status;\n\n}"
},
{
"identifier": "NoticeRespVO",
"path": "yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/controller/admin/notice/vo/NoticeRespVO.java",
"snippet": "@Schema(description = \"管理后台 - 通知公告信息 Response VO\")\n@Data\n@EqualsAndHashCode(callSuper = true)\npublic class NoticeRespVO extends NoticeBaseVO {\n\n @Schema(description = \"通知公告序号\", requiredMode = Schema.RequiredMode.REQUIRED, example = \"1024\")\n private Long id;\n\n @Schema(description = \"创建时间\", requiredMode = Schema.RequiredMode.REQUIRED, example = \"时间戳格式\")\n private LocalDateTime createTime;\n\n}"
},
{
"identifier": "NoticeUpdateReqVO",
"path": "yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/controller/admin/notice/vo/NoticeUpdateReqVO.java",
"snippet": "@Schema(description = \"管理后台 - 岗位公告更新 Request VO\")\n@Data\n@EqualsAndHashCode(callSuper = true)\npublic class NoticeUpdateReqVO extends NoticeBaseVO {\n\n @Schema(description = \"岗位公告编号\", requiredMode = Schema.RequiredMode.REQUIRED, example = \"1024\")\n @NotNull(message = \"岗位公告编号不能为空\")\n private Long id;\n\n}"
},
{
"identifier": "NoticeConvert",
"path": "yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/convert/notice/NoticeConvert.java",
"snippet": "@Mapper\npublic interface NoticeConvert {\n\n NoticeConvert INSTANCE = Mappers.getMapper(NoticeConvert.class);\n\n PageResult<NoticeRespVO> convertPage(PageResult<NoticeDO> page);\n\n NoticeRespVO convert(NoticeDO bean);\n\n NoticeDO convert(NoticeUpdateReqVO bean);\n\n NoticeDO convert(NoticeCreateReqVO bean);\n\n}"
},
{
"identifier": "NoticeService",
"path": "yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/notice/NoticeService.java",
"snippet": "public interface NoticeService {\n\n /**\n * 创建岗位公告公告\n *\n * @param reqVO 岗位公告公告信息\n * @return 岗位公告公告编号\n */\n Long createNotice(NoticeCreateReqVO reqVO);\n\n /**\n * 更新岗位公告公告\n *\n * @param reqVO 岗位公告公告信息\n */\n void updateNotice(NoticeUpdateReqVO reqVO);\n\n /**\n * 删除岗位公告公告信息\n *\n * @param id 岗位公告公告编号\n */\n void deleteNotice(Long id);\n\n /**\n * 获得岗位公告公告分页列表\n *\n * @param reqVO 分页条件\n * @return 部门分页列表\n */\n PageResult<NoticeDO> getNoticePage(NoticePageReqVO reqVO);\n\n /**\n * 获得岗位公告公告信息\n *\n * @param id 岗位公告公告编号\n * @return 岗位公告公告信息\n */\n NoticeDO getNotice(Long id);\n\n}"
},
{
"identifier": "success",
"path": "yudao-framework/yudao-common/src/main/java/cn/iocoder/yudao/framework/common/pojo/CommonResult.java",
"snippet": "public static <T> CommonResult<T> success(T data) {\n CommonResult<T> result = new CommonResult<>();\n result.code = GlobalErrorCodeConstants.SUCCESS.getCode();\n result.data = data;\n result.msg = \"\";\n return result;\n}"
}
] | import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.module.system.controller.admin.notice.vo.NoticeCreateReqVO;
import cn.iocoder.yudao.module.system.controller.admin.notice.vo.NoticePageReqVO;
import cn.iocoder.yudao.module.system.controller.admin.notice.vo.NoticeRespVO;
import cn.iocoder.yudao.module.system.controller.admin.notice.vo.NoticeUpdateReqVO;
import cn.iocoder.yudao.module.system.convert.notice.NoticeConvert;
import cn.iocoder.yudao.module.system.service.notice.NoticeService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.validation.Valid;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success; | 2,702 | package cn.iocoder.yudao.module.system.controller.admin.notice;
@Tag(name = "管理后台 - 通知公告")
@RestController
@RequestMapping("/system/notice")
@Validated
public class NoticeController {
@Resource
private NoticeService noticeService;
@PostMapping("/create")
@Operation(summary = "创建通知公告")
@PreAuthorize("@ss.hasPermission('system:notice:create')")
public CommonResult<Long> createNotice(@Valid @RequestBody NoticeCreateReqVO reqVO) {
Long noticeId = noticeService.createNotice(reqVO);
return success(noticeId);
}
@PutMapping("/update")
@Operation(summary = "修改通知公告")
@PreAuthorize("@ss.hasPermission('system:notice:update')")
public CommonResult<Boolean> updateNotice(@Valid @RequestBody NoticeUpdateReqVO reqVO) {
noticeService.updateNotice(reqVO);
return success(true);
}
@DeleteMapping("/delete")
@Operation(summary = "删除通知公告")
@Parameter(name = "id", description = "编号", required = true, example = "1024")
@PreAuthorize("@ss.hasPermission('system:notice:delete')")
public CommonResult<Boolean> deleteNotice(@RequestParam("id") Long id) {
noticeService.deleteNotice(id);
return success(true);
}
@GetMapping("/page")
@Operation(summary = "获取通知公告列表")
@PreAuthorize("@ss.hasPermission('system:notice:query')") | package cn.iocoder.yudao.module.system.controller.admin.notice;
@Tag(name = "管理后台 - 通知公告")
@RestController
@RequestMapping("/system/notice")
@Validated
public class NoticeController {
@Resource
private NoticeService noticeService;
@PostMapping("/create")
@Operation(summary = "创建通知公告")
@PreAuthorize("@ss.hasPermission('system:notice:create')")
public CommonResult<Long> createNotice(@Valid @RequestBody NoticeCreateReqVO reqVO) {
Long noticeId = noticeService.createNotice(reqVO);
return success(noticeId);
}
@PutMapping("/update")
@Operation(summary = "修改通知公告")
@PreAuthorize("@ss.hasPermission('system:notice:update')")
public CommonResult<Boolean> updateNotice(@Valid @RequestBody NoticeUpdateReqVO reqVO) {
noticeService.updateNotice(reqVO);
return success(true);
}
@DeleteMapping("/delete")
@Operation(summary = "删除通知公告")
@Parameter(name = "id", description = "编号", required = true, example = "1024")
@PreAuthorize("@ss.hasPermission('system:notice:delete')")
public CommonResult<Boolean> deleteNotice(@RequestParam("id") Long id) {
noticeService.deleteNotice(id);
return success(true);
}
@GetMapping("/page")
@Operation(summary = "获取通知公告列表")
@PreAuthorize("@ss.hasPermission('system:notice:query')") | public CommonResult<PageResult<NoticeRespVO>> getNoticePage(@Validated NoticePageReqVO reqVO) { | 3 | 2023-12-08 02:48:42+00:00 | 4k |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.