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 |
---|---|---|---|---|---|---|---|---|---|---|
Invadermonky/Omniwand | src/main/java/com/invadermonky/omniwand/handlers/TransformHandler.java | [
{
"identifier": "Omniwand",
"path": "src/main/java/com/invadermonky/omniwand/Omniwand.java",
"snippet": "@Mod(\n modid = Omniwand.MOD_ID,\n name = Omniwand.MOD_NAME,\n version = Omniwand.MOD_VERSION,\n acceptedMinecraftVersions = Omniwand.MC_VERSION,\n guiFactory = Omniwand.GUI_FACTORY\n)\npublic class Omniwand {\n public static final String MOD_ID = \"omniwand\";\n public static final String MOD_NAME = \"Omniwand\";\n public static final String MOD_VERSION = \"1.12.2-1.0.1\";\n public static final String GUI_FACTORY = \"com.invadermonky.omniwand.client.GuiFactory\";\n public static final String MC_VERSION = \"[1.12.2]\";\n\n public static final String ProxyClientClass = \"com.invadermonky.omniwand.proxy.ClientProxy\";\n public static final String ProxyServerClass = \"com.invadermonky.omniwand.proxy.CommonProxy\";\n\n public static SimpleNetworkWrapper network;\n\n @Mod.Instance(MOD_ID)\n public static Omniwand INSTANCE;\n\n @SidedProxy(clientSide = ProxyClientClass, serverSide = ProxyServerClass)\n public static CommonProxy proxy;\n\n @Mod.EventHandler\n public void preInit(FMLPreInitializationEvent event) {\n LogHelper.info(\"Starting Omniwand.\");\n\n //Config and config event subscriber\n ConfigHandler.preInit();\n MinecraftForge.EVENT_BUS.register(new ConfigHandler());\n\n proxy.preInit(event);\n LogHelper.debug(\"Finished preInit phase.\");\n }\n\n @Mod.EventHandler\n public void init(FMLInitializationEvent event) {\n proxy.init(event);\n LogHelper.debug(\"Finished init phase.\");\n }\n\n @Mod.EventHandler\n public void postInit(FMLPostInitializationEvent event) {\n proxy.postInit(event);\n LogHelper.debug(\"Finished postInit phase.\");\n }\n}"
},
{
"identifier": "RegistryOW",
"path": "src/main/java/com/invadermonky/omniwand/init/RegistryOW.java",
"snippet": "@Mod.EventBusSubscriber(modid = Omniwand.MOD_ID)\npublic class RegistryOW {\n public static Item OMNIWAND;\n\n @SubscribeEvent\n public static void registerItems(RegistryEvent.Register<Item> event) {\n IForgeRegistry<Item> registry = event.getRegistry();\n OMNIWAND = new ItemWand(\"wand\");\n registry.register(OMNIWAND);\n }\n\n @SubscribeEvent\n public static void registerItemRenders(ModelRegistryEvent event) {\n LogHelper.debug(\"Registering model of item: \" + OMNIWAND.delegate.name());\n ModelResourceLocation loc;\n \n if(ConfigHandler.alternateAppearance)\n loc = new ModelResourceLocation(new ResourceLocation(Omniwand.MOD_ID, \"wand_alt\"), \"inventory\");\n else\n loc = new ModelResourceLocation(OMNIWAND.delegate.name(), \"inventory\");\n\n ModelLoader.setCustomModelResourceLocation(OMNIWAND, 0, loc);\n }\n\n @SubscribeEvent\n public static void registerRecipes(RegistryEvent.Register<IRecipe> event) {\n IForgeRegistry<IRecipe> registry = event.getRegistry();\n registry.register(((ItemWand) OMNIWAND).getAttachmentRecipe());\n }\n}"
},
{
"identifier": "MessageRevertWand",
"path": "src/main/java/com/invadermonky/omniwand/network/MessageRevertWand.java",
"snippet": "public class MessageRevertWand implements IMessage {\n public MessageRevertWand() {}\n\n @Override\n public void fromBytes(ByteBuf buf) {}\n\n @Override\n public void toBytes(ByteBuf buf) {}\n\n public static class MsgHandler implements IMessageHandler<MessageRevertWand,IMessage> {\n @Override\n public IMessage onMessage(MessageRevertWand message, MessageContext ctx) {\n EntityPlayer player = ctx.getServerHandler().player;\n ItemStack stack = player.getHeldItemMainhand();\n\n if(stack != null && TransformHandler.isOmniwand(stack) && stack.getItem() != RegistryOW.OMNIWAND) {\n ItemStack newStack = TransformHandler.getTransformStackForMod(stack, References.MINECRAFT);\n player.setHeldItem(EnumHand.MAIN_HAND, newStack);\n Omniwand.proxy.updateEquippedItem();\n }\n return null;\n }\n }\n}"
},
{
"identifier": "NBTHelper",
"path": "src/main/java/com/invadermonky/omniwand/util/NBTHelper.java",
"snippet": "public class NBTHelper {\n public static boolean detectNBT(ItemStack stack) {\n return stack.hasTagCompound();\n }\n\n public static void initNBT(ItemStack stack) {\n if(!detectNBT(stack))\n injectNBT(stack, new NBTTagCompound());\n }\n\n public static void injectNBT(ItemStack stack, NBTTagCompound tagCompound) {\n stack.setTagCompound(tagCompound);\n }\n\n public static NBTTagCompound getNBT(ItemStack stack) {\n initNBT(stack);\n return stack.getTagCompound();\n }\n\n public static boolean verifyExistence(ItemStack stack, String tag) {\n return !stack.isEmpty() && detectNBT(stack) && getNBT(stack).hasKey(tag);\n }\n\n public static void setString(ItemStack stack, String tag, String str) {\n getNBT(stack).setString(tag, str);\n }\n\n public static NBTTagCompound getTagCompound(ItemStack stack, String tag) {\n return verifyExistence(stack, tag) ? getNBT(stack).getCompoundTag(tag) : new NBTTagCompound();\n }\n\n public static String getString(ItemStack stack, String tag, String defaultExpected) {\n return verifyExistence(stack, tag) ? getNBT(stack).getString(tag) : defaultExpected;\n }\n}"
},
{
"identifier": "References",
"path": "src/main/java/com/invadermonky/omniwand/util/References.java",
"snippet": "public class References {\n public static final String MINECRAFT = \"minecraft\";\n\n public static final String TAG_IS_TRANSFORMING = \"omniwand:is_transforming\";\n public static final String TAG_AUTO_TRANSFORM = \"omniwand:auto_transform\";\n public static final String TAG_WAND_DATA = \"omniwand:data\";\n public static final String TAG_WAND_DISPLAY_NAME = \"omniwand:displayName\";\n public static final String TAG_ITEM_DEFINED_MOD = \"omniwand:definedMod\";\n\n public static final Property ENABLE_TRANSFORM = new Property(\"enableTransforms\", \"true\", Property.Type.BOOLEAN);\n public static final Property RESTRICT_TOOLTIP = new Property(\"restrictTooltip\", \"true\", Property.Type.BOOLEAN);\n public static final Property OFFHAND_TRANSFORM = new Property(\"offhandTransformOnly\", \"false\", Property.Type.BOOLEAN);\n public static final Property CROUCH_REVERT = new Property(\"crouchRevert\", \"false\", Property.Type.BOOLEAN);\n public static final Property ALT_APPEARANCE = new Property(\"alternateAppearance\", \"false\", Property.Type.BOOLEAN);\n public static final Property TRANSFORM_ITEMS = new Property(\"transformItems\", \"\", Property.Type.STRING);\n public static final Property MOD_ALIASES = new Property(\"modAliases\", \"\", Property.Type.STRING);\n public static final Property BLACKLIST_MODS = new Property(\"blacklistedMods\", \"\", Property.Type.STRING);\n public static final Property WHITELIST_ITEMS = new Property(\"whitelistedItems\", \"\", Property.Type.STRING);\n public static final Property WHITELIST_NAMES = new Property(\"whitelistedNames\", \"\", Property.Type.STRING);\n\n //public static void initProps() {\n static {\n ENABLE_TRANSFORM.setComment(\"Enables Omniwand auto-transform.\");\n ENABLE_TRANSFORM.setDefaultValue(true);\n\n RESTRICT_TOOLTIP.setComment(\"Restricts the Omniwand tooltip to only show items that used for transforms.\");\n RESTRICT_TOOLTIP.setDefaultValue(false);\n\n OFFHAND_TRANSFORM.setComment(\"Omniwand will only transform when held in the offhand.\");\n OFFHAND_TRANSFORM.setDefaultValue(false);\n\n CROUCH_REVERT.setComment(\"Omniwand requires crouch + swing to revert from a transformed item.\");\n CROUCH_REVERT.setDefaultValue(false);\n\n ALT_APPEARANCE.setComment(\"If for some reason you hate the fact the Omniwand is a staff you can set this to true. REQUIRES RESTART.\");\n ALT_APPEARANCE.setDefaultValue(false);\n ALT_APPEARANCE.setRequiresMcRestart(true);\n\n TRANSFORM_ITEMS.setComment( \"List of items that will be associated with Omniwand auto-transform. This must be set before\\n\" +\n \"items are crafted into the wand. Only one transform item per mod can be stored in the Omniwand.\\n\\n\" +\n \"This will override the \\\"blacklistedMods\\\" setting.\\n\\n\");\n TRANSFORM_ITEMS.setDefaultValues(new String[]{\n \"appliedenergistics2:certus_quartz_wrench\",\n \"appliedenergistics2:nether_quartz_wrench\",\n \"appliedenergistics2:network_tool\",\n \"astralsorcery:itemwand\",\n \"botania:twigwand\",\n \"draconicevolution:crystal_binder\",\n \"embers:tinker_hammer\",\n \"enderio:item_yeta_wrench\",\n \"immersiveengineering:tool:0\",\n \"mekanism:configurator\",\n \"rftools:smartwrench\",\n \"teslacorelib:wrench\",\n \"thermalfoundation:wrench\"\n });\n\n MOD_ALIASES.setComment(\"List of mod aliases used for Omniwand transforming.\\n\");\n MOD_ALIASES.setDefaultValues(new String[]{\n \"ae2stuff=appliedenergistics2\",\n \"threng=appliedenergistics2\",\n \"animus=bloodmagic\",\n \"bloodarsenal=bloodmagic\",\n \"nautralpledge=botania\",\n \"immersivetech=immersiveengineering\",\n \"immersivepetrolium=immersiveengineering\",\n \"industrialforegoing=teslacorelib\",\n \"redstonearsenal=thermalfoundation\",\n \"thermalcultivation=thermalfoundation\",\n \"thermaldynamics=thermalfoundation\",\n \"thermalexpansion=thermalfoundation\",\n \"rftoolsdim=rftools\",\n \"rftoolspower=rftools\",\n \"rftoolscontrol=rftools\",\n \"integrateddynamics=integratedtunnels\",\n \"mekanismgenerators=mekanism\",\n \"mekanismtools=mekanism\",\n \"deepresonance=rftools\",\n \"xnet=rftools\",\n \"buildcrafttransport=buildcraft\",\n \"buildcraftfactory=buildcraft\",\n \"buildcraftsilicon=buildcraft\"\n });\n\n BLACKLIST_MODS.setComment(\"List of mods to deny attachment to the Omniwand.\\n\");\n BLACKLIST_MODS.setDefaultValues(new String[]{\n \"intangible\",\n \"immersiveengineering\",\n \"tconstruct\"\n });\n\n WHITELIST_ITEMS.setComment(\"List of items that can be attached to the Omniwand.\\nThis will override the \\\"blacklistedMods\\\" setting.\\n\");\n WHITELIST_ITEMS.setDefaultValues(new String[]{\n \"immersiveengineering:tool:1\",\n \"immersiveengineering:tool:2\"\n });\n\n WHITELIST_NAMES.setComment(\"List of names contained within item ids that can be attached to the Omniwand.\\n\");\n WHITELIST_NAMES.setDefaultValues(new String[]{\n \"configurator\",\n \"crowbar\",\n \"hammer\",\n \"rod\",\n \"rotator\",\n \"screwdriver\",\n \"wand\",\n \"wrench\"\n });\n }\n}"
}
] | import com.invadermonky.omniwand.Omniwand;
import com.invadermonky.omniwand.init.RegistryOW;
import com.invadermonky.omniwand.network.MessageRevertWand;
import com.invadermonky.omniwand.util.NBTHelper;
import com.invadermonky.omniwand.util.References;
import gnu.trove.map.hash.THashMap;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.Entity;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.text.TextFormatting;
import net.minecraftforge.event.entity.item.ItemTossEvent;
import net.minecraftforge.event.entity.player.PlayerDestroyItemEvent;
import net.minecraftforge.event.entity.player.PlayerInteractEvent;
import net.minecraftforge.fml.common.Loader;
import net.minecraftforge.fml.common.ModContainer;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import java.util.Locale;
import java.util.Map;
import java.util.function.Consumer; | 3,224 | package com.invadermonky.omniwand.handlers;
public class TransformHandler {
public static final TransformHandler INSTANCE = new TransformHandler();
public static final THashMap<String,String> modNames = new THashMap<>();
public static boolean autoMode = true;
@SubscribeEvent
public void onItemDropped(ItemTossEvent event) {
if(event.getPlayer().isSneaking()) {
EntityItem e = event.getEntityItem();
ItemStack stack = e.getItem();
TransformHandler.removeItemFromWand(e, stack, false, e::setItem);
autoMode = true;
}
}
@SubscribeEvent
public void onItemBroken(PlayerDestroyItemEvent event) {
TransformHandler.removeItemFromWand(event.getEntityPlayer(), event.getOriginal(), true, (transform) -> {
event.getEntityPlayer().setHeldItem(event.getHand(), transform);
autoMode = true;
});
}
@SideOnly(Side.CLIENT)
@SubscribeEvent
public void onPlayerSwing(PlayerInteractEvent.LeftClickEmpty event) {
ItemStack stack = event.getItemStack();
if(!ConfigHandler.crouchRevert || event.getEntityPlayer().isSneaking()) {
if (stack != null && TransformHandler.isOmniwand(stack) && stack.getItem() != RegistryOW.OMNIWAND) { | package com.invadermonky.omniwand.handlers;
public class TransformHandler {
public static final TransformHandler INSTANCE = new TransformHandler();
public static final THashMap<String,String> modNames = new THashMap<>();
public static boolean autoMode = true;
@SubscribeEvent
public void onItemDropped(ItemTossEvent event) {
if(event.getPlayer().isSneaking()) {
EntityItem e = event.getEntityItem();
ItemStack stack = e.getItem();
TransformHandler.removeItemFromWand(e, stack, false, e::setItem);
autoMode = true;
}
}
@SubscribeEvent
public void onItemBroken(PlayerDestroyItemEvent event) {
TransformHandler.removeItemFromWand(event.getEntityPlayer(), event.getOriginal(), true, (transform) -> {
event.getEntityPlayer().setHeldItem(event.getHand(), transform);
autoMode = true;
});
}
@SideOnly(Side.CLIENT)
@SubscribeEvent
public void onPlayerSwing(PlayerInteractEvent.LeftClickEmpty event) {
ItemStack stack = event.getItemStack();
if(!ConfigHandler.crouchRevert || event.getEntityPlayer().isSneaking()) {
if (stack != null && TransformHandler.isOmniwand(stack) && stack.getItem() != RegistryOW.OMNIWAND) { | Omniwand.network.sendToServer(new MessageRevertWand()); | 0 | 2023-10-16 00:48:26+00:00 | 4k |
hmcts/opal-fines-service | src/test/java/uk/gov/hmcts/opal/service/PartyServiceTest.java | [
{
"identifier": "AccountSearchDto",
"path": "src/main/java/uk/gov/hmcts/opal/dto/AccountSearchDto.java",
"snippet": "@Data\n@Builder\npublic class AccountSearchDto implements ToJsonString {\n /** The court (CT) or MET (metropolitan area). */\n private String court;\n /** Defendant Surname, Company Name or A/C number. */\n private String surname;\n /** Can be either Defendant, Minor Creditor or Company. */\n private String searchType;\n /** Defendant Forenames. */\n private String forename;\n /** Defendant Initials. */\n private String initials;\n /** Defendant Date of Birth. */\n private DateDto dateOfBirth;\n /** Defendant Address, typically just first line. */\n private String addressLineOne;\n /** National Insurance Number. */\n private String niNumber;\n /** Prosecutor Case Reference. */\n private String pcr;\n /** Major Creditor account selection. */\n private String majorCreditor;\n /** Unsure. */\n private String tillNumber;\n}"
},
{
"identifier": "PartyDto",
"path": "src/main/java/uk/gov/hmcts/opal/dto/PartyDto.java",
"snippet": "@Data\n@Builder\n@NoArgsConstructor\n@AllArgsConstructor\n@Jacksonized\npublic class PartyDto implements ToJsonString {\n private Long partyId;\n private boolean organisation;\n private String organisationName;\n private String surname;\n private String forenames;\n private String initials;\n private String title;\n private String addressLine1;\n private String addressLine2;\n private String addressLine3;\n private String addressLine4;\n private String addressLine5;\n private String postcode;\n private String accountType;\n private LocalDate dateOfBirth;\n private Short age;\n private String niNumber;\n private LocalDateTime lastChangedDate;\n private String accountNo;\n private BigDecimal amountImposed;\n}"
},
{
"identifier": "PartyEntity",
"path": "src/main/java/uk/gov/hmcts/opal/entity/PartyEntity.java",
"snippet": "@Entity\n@Data\n@Table(name = \"parties\")\n@NoArgsConstructor\n@AllArgsConstructor\n@Builder\npublic class PartyEntity {\n\n @Id\n @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = \"party_id_seq\")\n @SequenceGenerator(name = \"party_id_seq\", sequenceName = \"party_id_seq\", allocationSize = 1)\n @Column(name = \"party_id\")\n private Long partyId;\n\n @Column(name = \"organisation\")\n private boolean organisation;\n\n @Column(name = \"organisation_name\", length = 80)\n private String organisationName;\n\n @Column(name = \"surname\", length = 50)\n private String surname;\n\n @Column(name = \"forenames\", length = 50)\n private String forenames;\n\n @Column(name = \"initials\", length = 2)\n private String initials;\n\n @Column(name = \"title\", length = 20)\n private String title;\n\n @Column(name = \"address_line_1\", length = 35)\n private String addressLine1;\n\n @Column(name = \"address_line_2\", length = 35)\n private String addressLine2;\n\n @Column(name = \"address_line_3\", length = 35)\n private String addressLine3;\n\n @Column(name = \"address_line_4\", length = 35)\n private String addressLine4;\n\n @Column(name = \"address_line_5\", length = 35)\n private String addressLine5;\n\n @Column(name = \"postcode\", length = 10)\n private String postcode;\n\n @Column(name = \"account_type\", length = 20)\n private String accountType;\n\n @Column(name = \"birth_date\")\n @Temporal(TemporalType.DATE)\n private LocalDate dateOfBirth;\n\n @Column(name = \"age\")\n private Short age;\n\n @Column(name = \"national_insurance_number\", length = 20)\n private String niNumber;\n\n @Column(name = \"last_changed_date\")\n @Temporal(TemporalType.TIMESTAMP)\n private LocalDateTime lastChangedDate;\n\n @OneToMany(mappedBy = \"party\", cascade = CascadeType.ALL, fetch = FetchType.EAGER)\n private List<DefendantAccountPartiesEntity> defendantAccounts;\n}"
},
{
"identifier": "PartySummary",
"path": "src/main/java/uk/gov/hmcts/opal/entity/PartySummary.java",
"snippet": "public interface PartySummary {\n\n String getTitle();\n\n String getForenames();\n\n String getSurname();\n\n /**\n * The name of the defendant, being an aggregation of surname, firstnames and title.\n */\n default String getName() {\n return getTitle().concat(\" \").concat(getForenames()).concat(\" \").concat(getSurname());\n }\n\n /**\n * The date of birth of the defendant.\n */\n LocalDate getDateOfBirth();\n\n /**\n * First line of the defendant's address.\n */\n String getAddressLine1();\n\n Set<DefendantAccountLink> getDefendantAccounts();\n\n interface DefendantAccountLink {\n DefendantAccountPartySummary getDefendantAccount();\n }\n\n interface DefendantAccountPartySummary {\n\n /**\n * The defendant account number.\n */\n String getAccountNumber();\n\n /**\n * The balance on the defendant account.\n */\n BigDecimal getAccountBalance();\n\n /**\n * The Court (traditionally abbreviated to CT) 'Accounting Division' or 'Metropolitan Area' (MET).\n */\n String getImposingCourtId();\n\n }\n}"
},
{
"identifier": "PartyRepository",
"path": "src/main/java/uk/gov/hmcts/opal/repository/PartyRepository.java",
"snippet": "@Repository\npublic interface PartyRepository extends JpaRepository<PartyEntity, Long> {\n\n List<PartySummary> findBySurnameContaining(String surname);\n\n}"
}
] | 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 uk.gov.hmcts.opal.dto.AccountSearchDto;
import uk.gov.hmcts.opal.dto.PartyDto;
import uk.gov.hmcts.opal.entity.PartyEntity;
import uk.gov.hmcts.opal.entity.PartySummary;
import uk.gov.hmcts.opal.repository.PartyRepository;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when; | 1,849 | package uk.gov.hmcts.opal.service;
@ExtendWith(MockitoExtension.class)
class PartyServiceTest {
@Mock
private PartyRepository partyRepository;
@InjectMocks
private PartyService partyService;
@Test
void testSaveParty() {
PartyDto partyDto = buildPartyDto();
PartyEntity partyEntity = buildPartyEntity();
when(partyRepository.save(any(PartyEntity.class))).thenReturn(partyEntity);
// Act
PartyDto savedPartyDto = partyService.saveParty(partyDto);
// Assert
assertEquals(partyEntity.getPartyId(), savedPartyDto.getPartyId());
verify(partyRepository, times(1)).save(any(PartyEntity.class));
}
@Test
void testGetParty() {
PartyEntity partyEntity = buildPartyEntity();
when(partyRepository.getReferenceById(any(Long.class))).thenReturn(partyEntity);
// Act
PartyDto savedPartyDto = partyService.getParty(1L);
// Assert
assertEquals(partyEntity.getPartyId(), savedPartyDto.getPartyId());
verify(partyRepository, times(1)).getReferenceById(any(Long.class));
}
@Test
void testSearchForParty() {
List<PartySummary> partyEntity = Collections.<PartySummary>emptyList();
when(partyRepository.findBySurnameContaining(any())).thenReturn(partyEntity);
// Act | package uk.gov.hmcts.opal.service;
@ExtendWith(MockitoExtension.class)
class PartyServiceTest {
@Mock
private PartyRepository partyRepository;
@InjectMocks
private PartyService partyService;
@Test
void testSaveParty() {
PartyDto partyDto = buildPartyDto();
PartyEntity partyEntity = buildPartyEntity();
when(partyRepository.save(any(PartyEntity.class))).thenReturn(partyEntity);
// Act
PartyDto savedPartyDto = partyService.saveParty(partyDto);
// Assert
assertEquals(partyEntity.getPartyId(), savedPartyDto.getPartyId());
verify(partyRepository, times(1)).save(any(PartyEntity.class));
}
@Test
void testGetParty() {
PartyEntity partyEntity = buildPartyEntity();
when(partyRepository.getReferenceById(any(Long.class))).thenReturn(partyEntity);
// Act
PartyDto savedPartyDto = partyService.getParty(1L);
// Assert
assertEquals(partyEntity.getPartyId(), savedPartyDto.getPartyId());
verify(partyRepository, times(1)).getReferenceById(any(Long.class));
}
@Test
void testSearchForParty() {
List<PartySummary> partyEntity = Collections.<PartySummary>emptyList();
when(partyRepository.findBySurnameContaining(any())).thenReturn(partyEntity);
// Act | List<PartySummary> partySummaries = partyService.searchForParty(AccountSearchDto.builder().build()); | 0 | 2023-10-23 14:12:11+00:00 | 4k |
IronRiders/MockSeason23-24 | src/main/java/org/ironriders/commands/RobotCommands.java | [
{
"identifier": "Arm",
"path": "src/main/java/org/ironriders/constants/Arm.java",
"snippet": "public class Arm {\n public static final double LENGTH_FROM_ORIGIN = Units.inchesToMeters(39);\n public static final double TOLERANCE = 1;\n public static final double FAILSAFE_DIFFERENCE = 7;\n public static final double GEARING = 500;\n public static final double PRIMARY_ENCODER_OFFSET = -124;\n public static final double SECONDARY_ENCODER_OFFSET = 44;\n public static final double TIMEOUT = 4;\n public static final int CURRENT_LIMIT = 15;\n\n public enum State {\n REST(0),\n SWITCH(40),\n EXCHANGE(0),\n EXCHANGE_RETURN(30),\n PORTAL(30),\n FULL(70);\n\n final int position;\n\n State(int position) {\n this.position = position;\n }\n\n public int getPosition() {\n return position;\n }\n }\n\n public static class Limit {\n public static final float REVERSE = 0;\n public static final float FORWARD = 70;\n }\n\n public static class PID {\n\n public static final double P = 0.075;\n public static final double I = 0;\n public static final double D = 0;\n\n public static final TrapezoidProfile.Constraints PROFILE =\n new TrapezoidProfile.Constraints(70, 50);\n }\n}"
},
{
"identifier": "Manipulator",
"path": "src/main/java/org/ironriders/constants/Manipulator.java",
"snippet": "public class Manipulator {\n public static final int CURRENT_LIMIT = 20;\n public static final double GRAB_SPEED = 0.6;\n public static final double EJECT_SPEED = 1;\n public static final double EJECT_TIMEOUT = 0.7;\n\n public enum State {\n GRAB,\n EJECT,\n STOP\n }\n}"
},
{
"identifier": "ArmSubsystem",
"path": "src/main/java/org/ironriders/subsystems/ArmSubsystem.java",
"snippet": "public class ArmSubsystem extends SubsystemBase {\n private final ArmCommands commands;\n private final CANSparkMax leader = new CANSparkMax(Ports.Arm.RIGHT_MOTOR, kBrushless);\n @SuppressWarnings(\"FieldCanBeLocal\")\n private final CANSparkMax follower = new CANSparkMax(Ports.Arm.LEFT_MOTOR, kBrushless);\n private final DutyCycleEncoder primaryEncoder = new DutyCycleEncoder(Ports.Arm.PRIMARY_ENCODER);\n private final DutyCycleEncoder secondaryEncoder = new DutyCycleEncoder(Ports.Arm.SECONDARY_ENCODER);\n private final ProfiledPIDController pid = new ProfiledPIDController(P, I, D, PROFILE);\n\n public ArmSubsystem() {\n leader.setSmartCurrentLimit(CURRENT_LIMIT);\n follower.setSmartCurrentLimit(CURRENT_LIMIT);\n\n leader.setIdleMode(kCoast);\n follower.setIdleMode(kCoast);\n\n primaryEncoder.setPositionOffset(PRIMARY_ENCODER_OFFSET);\n primaryEncoder.setDistancePerRotation(360);\n secondaryEncoder.setPositionOffset(SECONDARY_ENCODER_OFFSET);\n secondaryEncoder.setDistancePerRotation(360);\n\n leader.getEncoder().setPositionConversionFactor(360.0 / GEARING);\n leader.getEncoder().setPosition(getPrimaryPosition());\n\n follower.getEncoder().setPositionConversionFactor(360.0 / GEARING);\n follower.getEncoder().setPosition(getPrimaryPosition());\n\n leader.setSoftLimit(kReverse, Limit.REVERSE);\n leader.enableSoftLimit(kReverse, true);\n leader.setSoftLimit(kForward, Limit.FORWARD);\n leader.enableSoftLimit(kForward, true);\n follower.setSoftLimit(kReverse, Limit.REVERSE);\n follower.enableSoftLimit(kReverse, true);\n follower.setSoftLimit(kForward, Limit.FORWARD);\n follower.enableSoftLimit(kForward, true);\n\n follower.follow(leader, true);\n resetPID();\n\n SmartDashboard.putData(\"arm/Arm PID\", pid);\n SmartDashboard.putData(\"arm/Leader\", primaryEncoder);\n SmartDashboard.putData(\"arm/Follower\", secondaryEncoder);\n\n commands = new ArmCommands(this);\n }\n\n @Override\n public void periodic() {\n SmartDashboard.putNumber(\"arm/Leader (integrated)\", leader.getEncoder().getPosition());\n SmartDashboard.putNumber(\"arm/Follower (integrated)\", follower.getEncoder().getPosition());\n\n if (!Utils.isWithinTolerance(getPrimaryPosition(), getSecondaryPosition(), FAILSAFE_DIFFERENCE)) {\n leader.set(0);\n return;\n }\n\n leader.set(pid.calculate(getPosition()));\n }\n\n\n public ArmCommands getCommands() {\n return commands;\n }\n\n public double getPrimaryPosition() {\n return primaryEncoder.getDistance() + PRIMARY_ENCODER_OFFSET;\n }\n\n public double getSecondaryPosition() {\n return -(secondaryEncoder.getDistance() + SECONDARY_ENCODER_OFFSET);\n }\n\n /**\n * In degrees.\n */\n public double getPosition() {\n return getPrimaryPosition();\n }\n\n public void set(double target) {\n pid.setGoal(target);\n }\n\n public void resetPID() {\n pid.reset(getPosition());\n pid.setGoal(getPosition());\n }\n}"
},
{
"identifier": "DriveSubsystem",
"path": "src/main/java/org/ironriders/subsystems/DriveSubsystem.java",
"snippet": "public class DriveSubsystem extends SubsystemBase {\n private final DriveCommands commands;\n private final VisionSubsystem vision = new VisionSubsystem();\n private final SwerveDrive swerveDrive;\n private final EnumSendableChooser<PathfindingConstraintProfile> constraintProfile = new EnumSendableChooser<>(\n PathfindingConstraintProfile.class,\n PathfindingConstraintProfile.getDefault(),\n \"auto/Pathfinding Constraint Profile\"\n );\n\n public DriveSubsystem() {\n try {\n swerveDrive = new SwerveParser(\n new File(Filesystem.getDeployDirectory(), Drive.SWERVE_CONFIG_LOCATION)\n ).createSwerveDrive(MAX_SPEED, STEERING_CONVERSION_FACTOR, DRIVE_CONVERSION_FACTOR);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n\n SwerveDriveTelemetry.verbosity = SwerveDriveTelemetry.TelemetryVerbosity.HIGH;\n\n AutoBuilder.configureHolonomic(\n swerveDrive::getPose,\n swerveDrive::resetOdometry,\n swerveDrive::getRobotVelocity,\n swerveDrive::setChassisSpeeds,\n new HolonomicPathFollowerConfig(\n 4.5,\n Dimensions.DRIVEBASE_RADIUS,\n new ReplanningConfig()\n ),\n () -> DriverStation.getAlliance().orElse(Alliance.Blue).equals(Alliance.Red),\n this\n );\n\n commands = new DriveCommands(this);\n }\n\n @Override\n public void periodic() {\n PathPlannerLogging.setLogActivePathCallback((poses) -> {\n List<Trajectory.State> states = new ArrayList<>();\n for (Pose2d pose : poses) {\n Trajectory.State state = new Trajectory.State();\n state.poseMeters = pose;\n states.add(state);\n }\n\n swerveDrive.postTrajectory(new Trajectory(states));\n });\n\n getVision().getPoseEstimate().ifPresent(estimatedRobotPose -> {\n swerveDrive.resetOdometry(estimatedRobotPose.estimatedPose.toPose2d());\n swerveDrive.setGyro(estimatedRobotPose.estimatedPose.getRotation());\n// swerveDrive.addVisionMeasurement(\n// estimatedRobotPose.estimatedPose.toPose2d(),\n// estimatedRobotPose.timestampSeconds\n// );\n// swerveDrive.setGyro(estimatedRobotPose.estimatedPose.getRotation());\n });\n }\n\n public DriveCommands getCommands() {\n return commands;\n }\n\n public void setGyro(Rotation3d rotation) {\n swerveDrive.setGyro(new Rotation3d());\n }\n\n public VisionSubsystem getVision() {\n return vision;\n }\n\n public PathfindingConstraintProfile getPathfindingConstraint() {\n return constraintProfile.getSelected();\n }\n\n public SwerveDrive getSwerveDrive() {\n return swerveDrive;\n }\n}"
},
{
"identifier": "ManipulatorSubsystem",
"path": "src/main/java/org/ironriders/subsystems/ManipulatorSubsystem.java",
"snippet": "public class ManipulatorSubsystem extends SubsystemBase {\n private final ManipulatorCommands commands;\n private final CANSparkMax leader = new CANSparkMax(Ports.Manipulator.RIGHT_MOTOR, kBrushless);\n @SuppressWarnings(\"FieldCanBeLocal\")\n private final CANSparkMax follower = new CANSparkMax(Ports.Manipulator.LEFT_MOTOR, kBrushless);\n\n public ManipulatorSubsystem() {\n leader.setSmartCurrentLimit(CURRENT_LIMIT);\n follower.setSmartCurrentLimit(CURRENT_LIMIT);\n leader.setIdleMode(kBrake);\n follower.setIdleMode(kBrake);\n\n follower.follow(leader, true);\n\n SmartDashboard.putString(\"manipulator/State\", \"STOP\");\n\n commands = new ManipulatorCommands(this);\n }\n\n public ManipulatorCommands getCommands() {\n return commands;\n }\n\n public void set(State state) {\n switch (state) {\n case GRAB -> grab();\n case EJECT -> eject();\n case STOP -> stop();\n }\n }\n\n private void grab() {\n SmartDashboard.putString(\"manipulator/State\", \"GRAB\");\n leader.set(-GRAB_SPEED);\n }\n\n private void eject() {\n SmartDashboard.putString(\"manipulator/State\", \"EJECT\");\n leader.set(EJECT_SPEED);\n }\n\n private void stop() {\n SmartDashboard.putString(\"manipulator/State\", \"STOP\");\n leader.set(0);\n }\n}"
},
{
"identifier": "VisionSubsystem",
"path": "src/main/java/org/ironriders/subsystems/VisionSubsystem.java",
"snippet": "public class VisionSubsystem extends SubsystemBase {\n private final PhotonCamera camera = new PhotonCamera(CAMERA);\n private final PhotonPoseEstimator estimator;\n private final AprilTagFieldLayout tagLayout;\n private boolean useVisionForEstimation = false;\n\n public VisionSubsystem() {\n try {\n tagLayout = new AprilTagFieldLayout(\n Filesystem.getDeployDirectory() + APRIL_TAG_FIELD_LAYOUT_LOCATION\n );\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n\n estimator = new PhotonPoseEstimator(tagLayout, LOWEST_AMBIGUITY, camera, LIMELIGHT_POSITION);\n\n setPipeline(APRIL_TAGS);\n camera.setLED(VisionLEDMode.kOff);\n camera.setDriverMode(false);\n\n SmartDashboard.putString(\"vision/pipeline\", getPipeline().name());\n }\n\n public AprilTagFieldLayout getTagLayout() {\n return tagLayout;\n }\n\n public Optional<EstimatedRobotPose> getPoseEstimate() {\n if (useVisionForEstimation) {\n setPipeline(APRIL_TAGS);\n return estimator.update();\n }\n return Optional.empty();\n }\n\n public int bestTagFor(Game.Field.AprilTagLocation location) {\n setPipeline(APRIL_TAGS);\n SmartDashboard.putBoolean(\"not found\", false);\n SmartDashboard.putBoolean(\"not correct\", false);\n\n if (!getResult().hasTargets()) {\n SmartDashboard.putBoolean(\"not found\", true);\n return -1;\n }\n if (!location.has(getResult().getBestTarget().getFiducialId())) {\n SmartDashboard.putBoolean(\"not correct\", true);\n return -1;\n }\n\n return getResult().getBestTarget().getFiducialId();\n }\n\n public Optional<Pose3d> getTag(int id) {\n return getTagLayout().getTagPose(id);\n }\n\n public void useVisionForPoseEstimation(boolean useVision) {\n useVisionForEstimation = useVision;\n }\n\n public PhotonPipelineResult getResult() {\n return camera.getLatestResult();\n }\n\n public VisionPipeline getPipeline() {\n return VisionPipeline.fromIndex(camera.getPipelineIndex());\n }\n\n public void setPipeline(VisionPipeline pipeline) {\n camera.setPipelineIndex(pipeline.getIndex());\n SmartDashboard.putString(\"vision/pipeline\", pipeline.name());\n }\n}"
},
{
"identifier": "AprilTagLocation",
"path": "src/main/java/org/ironriders/constants/Game.java",
"snippet": "public enum AprilTagLocation {\n EXCHANGE(1, 2),\n PORTAL(3, 4, 5, 6),\n SWITCH(7, 8, 9, 10, 11, 12, 13, 14);\n\n final int[] ids;\n\n AprilTagLocation(int... ids) {\n this.ids = ids;\n }\n\n public boolean has(int id) {\n return Arrays.stream(ids).anyMatch(i -> i == id);\n }\n\n public int[] getIds() {\n return ids;\n }\n}"
},
{
"identifier": "WAIT_TIME",
"path": "src/main/java/org/ironriders/constants/Vision.java",
"snippet": "public static final double WAIT_TIME = 0.3;"
}
] | import com.pathplanner.lib.auto.AutoBuilder;
import com.pathplanner.lib.auto.NamedCommands;
import edu.wpi.first.wpilibj2.command.Command;
import edu.wpi.first.wpilibj2.command.Commands;
import org.ironriders.constants.Arm;
import org.ironriders.constants.Manipulator;
import org.ironriders.subsystems.ArmSubsystem;
import org.ironriders.subsystems.DriveSubsystem;
import org.ironriders.subsystems.ManipulatorSubsystem;
import org.ironriders.subsystems.VisionSubsystem;
import java.util.Set;
import static org.ironriders.constants.Game.Field.AprilTagLocation;
import static org.ironriders.constants.Vision.WAIT_TIME; | 3,279 | package org.ironriders.commands;
public class RobotCommands {
private final ArmCommands arm;
private final DriveCommands drive;
private final DriveSubsystem driveSubsystem;
private final VisionSubsystem vision;
private final ManipulatorCommands manipulator;
| package org.ironriders.commands;
public class RobotCommands {
private final ArmCommands arm;
private final DriveCommands drive;
private final DriveSubsystem driveSubsystem;
private final VisionSubsystem vision;
private final ManipulatorCommands manipulator;
| public RobotCommands(ArmSubsystem arm, DriveSubsystem drive, ManipulatorSubsystem manipulator) { | 4 | 2023-10-23 20:31:46+00:00 | 4k |
ChrisGenti/DiscordTickets | src/main/java/com/github/chrisgenti/discordtickets/managers/TicketManager.java | [
{
"identifier": "Ticket",
"path": "src/main/java/com/github/chrisgenti/discordtickets/objects/Ticket.java",
"snippet": "public class Ticket {\n private final int id;\n private final TicketType ticketType;\n private final String userID, channelID;\n private final Date openDate;\n private Date closeDate;\n\n public Ticket(int id, TicketType ticketType, String userID, String channelID, Date openDate) {\n this.id = id;\n this.ticketType = ticketType;\n this.userID = userID;\n this.channelID = channelID;\n this.openDate = openDate;\n this.closeDate = null;\n }\n\n public int getId() {\n return id;\n }\n\n public TicketType getTicketType() {\n return ticketType;\n }\n\n public String getUserID() {\n return userID;\n }\n\n public String getChannelID() {\n return channelID;\n }\n\n public Date getOpenDate() {\n return openDate;\n }\n\n public Date getCloseDate() {\n return closeDate;\n }\n\n public void setCloseDate(Date closeDate) {\n this.closeDate = closeDate;\n }\n}"
},
{
"identifier": "DiscordTickets",
"path": "src/main/java/com/github/chrisgenti/discordtickets/DiscordTickets.java",
"snippet": "public class DiscordTickets {\n private final DecimalFormat decimalFormat = new DecimalFormat(\"##0,000\");\n\n private DiscordApi discord;\n private MongoManager mongoManager;\n private TicketManager ticketManager;\n\n public static final String CONFIG_LOCATION = System.getProperty(\"config.location\", \"config.json\");\n\n public void init() {\n /*\n LAUNCH MESSAGE\n */\n Logger.info(MessageUtil.LAUNCH_MESSAGE);\n\n /*\n LOAD\n */\n this.load();\n }\n\n private void load() {\n long mills = System.currentTimeMillis();\n\n ObjectTriple<FileResult, DiscordData, Exception> objectTriple = FileUtil.loadData(Paths.get(CONFIG_LOCATION));\n\n switch (objectTriple.left()) {\n case CREATED, EXISTING -> {\n /*\n START\n */\n this.start(mills, objectTriple.left(), objectTriple.mid()); break;\n }\n case MALFORMED -> {\n /*\n SHUTDOWN\n */\n this.shutdown(); break;\n }\n }\n }\n\n private void start(long mills, @NotNull FileResult result, @NotNull DiscordData data) {\n DiscordData.Discord discordData = data.discord(); DiscordData.Mongo mongoData = data.mongo();\n\n if (discordData.token().isEmpty()) {\n this.shutdown();\n return;\n }\n\n if (mongoData.hostname().isEmpty() || mongoData.username().isEmpty() || mongoData.password().isEmpty()) {\n this.shutdown();\n return;\n }\n\n /*\n DISCORD INSTANCE\n */\n this.discord = new DiscordApiBuilder()\n .setToken(\"MTE1ODc1MjcxMzA5MDI4OTY4NQ.GtV-Us.yBnbC-K-NYr6yErlDxx4oUATUuzaaQqXroYHEg\")\n .addIntents(Intent.MESSAGE_CONTENT, Intent.GUILDS)\n .login()\n .join();\n\n /*\n MANAGERS INSTANCE\n */\n this.mongoManager = new MongoManager(mongoData.hostname(), mongoData.username(), mongoData.password());\n this.ticketManager = new TicketManager(this);\n\n /*\n CREATE COMMANDS\n */\n SlashCommand.with(\"message\", \"Send message for ticket management.\")\n .setDefaultEnabledForPermissions(PermissionType.ADMINISTRATOR)\n .createGlobal(discord)\n .join();\n SlashCommand.with(\"close\", \"Close the ticket linked to this channel.\")\n .setDefaultEnabledForPermissions(PermissionType.ADMINISTRATOR)\n .createGlobal(discord)\n .join();\n Logger.info(\"Successfully logged commands: [Message, Stop]\");\n\n /*\n REGISTER LISTENERS\n */\n this.discord.addListener(new CommandListener(this));\n this.discord.addListener(new MenuListener());\n this.discord.addListener(new ModalListener(this));\n Logger.info(\"Successfully logged events: [SlashCommandCreateEvent, SelectMenuChooseEvent, ModalSubmitEvent]\");\n\n /*\n CONFIG MESSAGE\n */\n Logger.info(\n MessageUtil.CONFIG_MESSAGE\n .replace(\"%config_result%\", result.reason())\n .replace(\"%opened_tickets%\", mongoManager.openedTicketsCount() + \"\")\n .replace(\"%closed_tickets%\", mongoManager.closedTicketsCount() + \"\")\n .replace(\"%mills%\", decimalFormat.format(System.currentTimeMillis() - mills))\n );\n }\n\n private void shutdown() {\n Logger.info(MessageUtil.MALFORMED_CONFIG_MESSAGE);\n\n try {\n Thread.sleep(5000);\n } catch (IllegalArgumentException | InterruptedException exc) {\n throw new RuntimeException(exc);\n }\n }\n\n public DiscordApi getDiscord() {\n return discord;\n }\n\n public MongoManager getMongoManager() {\n return mongoManager;\n }\n\n public TicketManager getTicketManager() {\n return ticketManager;\n }\n}"
},
{
"identifier": "MongoManager",
"path": "src/main/java/com/github/chrisgenti/discordtickets/managers/mongo/MongoManager.java",
"snippet": "public class MongoManager {\n private final MongoClientSettings settings;\n\n public MongoManager(String hostname, String username, String password) {\n LoggerFactory.getLogger(MongoManager.class);\n\n this.settings = MongoClientSettings.builder()\n .applyConnectionString(new ConnectionString(\"mongodb+srv://\" + username + \":\" + password + \"@\" + hostname + \"/?retryWrites=true&w=majority\"))\n .serverApi(\n ServerApi.builder()\n .version(ServerApiVersion.V1)\n .build()\n )\n .build();\n }\n\n public void createTicket(Ticket ticket) {\n try (MongoClient mongoClient = MongoClients.create(this.settings)) {\n try {\n MongoDatabase database = mongoClient.getDatabase(\"discord_tickets\");\n MongoCollection<Document> collection = database.getCollection(\"opened_tickets\");\n\n Document document = new Document(); document.put(\"id\", ticket.getId()); document.put(\"type\", ticket.getTicketType().toString()); document.put(\"user_id\", ticket.getUserID()); document.put(\"channel_id\", ticket.getChannelID()); document.put(\"open_date\", Util.formatDate(ticket.getOpenDate()));\n collection.insertOne(document);\n } catch (MongoException ignored) {}\n }\n }\n\n public void closeTicket(Ticket ticket) {\n try (MongoClient mongoClient = MongoClients.create(this.settings)) {\n try {\n MongoDatabase database = mongoClient.getDatabase(\"discord_tickets\");\n MongoCollection<Document> openCollection = database.getCollection(\"opened_tickets\");\n MongoCollection<Document> closeConnection = database.getCollection(\"closed_tickets\");\n\n Document searchDocument = new Document(); searchDocument.put(\"id\", ticket.getId());\n openCollection.deleteOne(searchDocument);\n\n Document document = new Document(); document.put(\"id\", ticket.getId()); document.put(\"type\", ticket.getTicketType().toString()); document.put(\"user_id\", ticket.getUserID()); document.put(\"channel_id\", ticket.getChannelID()); document.put(\"open_date\", Util.formatDate(ticket.getOpenDate())); document.put(\"close_date\", Util.formatDate(ticket.getCloseDate()));\n closeConnection.insertOne(document);\n } catch (MongoException ignored) {}\n }\n }\n\n public int ticketLastNumber() {\n List<Integer> values = new ArrayList<>();\n try (MongoClient mongoClient = MongoClients.create(this.settings)) {\n try {\n MongoDatabase database = mongoClient.getDatabase(\"discord_tickets\");\n MongoCollection<Document> collection;\n\n collection = database.getCollection(\"opened_tickets\");\n try (MongoCursor<Document> cursor = collection.find().cursor()) {\n while (cursor.hasNext())\n values.add(cursor.next().getInteger(\"id\"));\n }\n\n collection = database.getCollection(\"closed_tickets\");\n try (MongoCursor<Document> cursor = collection.find().cursor()) {\n while (cursor.hasNext())\n values.add(cursor.next().getInteger(\"id\"));\n }\n } catch (MongoException ignored) {}\n }\n return values.isEmpty() ? 0 : Collections.max(values);\n }\n\n public List<Ticket> ticketsToList() {\n List<Ticket> values = new ArrayList<>();\n try (MongoClient mongoClient = MongoClients.create(this.settings)) {\n try {\n MongoDatabase database = mongoClient.getDatabase(\"discord_tickets\");\n MongoCollection<Document> collection = database.getCollection(\"opened_tickets\");\n\n try (MongoCursor<Document> cursor = collection.find().cursor()) {\n while (cursor.hasNext()) {\n Document document = cursor.next();\n\n values.add(new Ticket(\n document.getInteger(\"id\"), TicketType.valueOf(document.getString(\"type\")), document.getString(\"user_id\"), document.getString(\"channel_id\"), Util.parseDate(document.getString(\"open_date\"))\n ));\n }\n }\n } catch (MongoException ignored) {}\n }\n return values;\n }\n\n public int openedTicketsCount() {\n try (MongoClient mongoClient = MongoClients.create(this.settings)) {\n try {\n MongoDatabase database = mongoClient.getDatabase(\"discord_tickets\");\n MongoCollection<Document> collection = database.getCollection(\"opened_tickets\");\n return Math.toIntExact(collection.countDocuments());\n } catch (MongoException ignored) {}\n }\n return 0;\n }\n\n public int closedTicketsCount() {\n try (MongoClient mongoClient = MongoClients.create(this.settings)) {\n try {\n MongoDatabase database = mongoClient.getDatabase(\"discord_tickets\");\n MongoCollection<Document> collection = database.getCollection(\"closed_tickets\");\n return Math.toIntExact(collection.countDocuments());\n } catch (MongoException ignored) {}\n }\n return 0;\n }\n}"
}
] | import com.github.chrisgenti.discordtickets.objects.Ticket;
import com.github.chrisgenti.discordtickets.DiscordTickets;
import com.github.chrisgenti.discordtickets.managers.mongo.MongoManager;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors; | 2,436 | package com.github.chrisgenti.discordtickets.managers;
public class TicketManager {
private int lastNumber;
private final List<Ticket> ticketCache;
public TicketManager(DiscordTickets discord) {
this.ticketCache = new ArrayList<>();
| package com.github.chrisgenti.discordtickets.managers;
public class TicketManager {
private int lastNumber;
private final List<Ticket> ticketCache;
public TicketManager(DiscordTickets discord) {
this.ticketCache = new ArrayList<>();
| MongoManager mongoManager = discord.getMongoManager(); | 2 | 2023-10-23 13:24:05+00:00 | 4k |
moonstoneid/aero-cast | apps/feed-aggregator/src/main/java/com/moonstoneid/aerocast/aggregator/controller/SSEController.java | [
{
"identifier": "Subscriber",
"path": "apps/feed-aggregator/src/main/java/com/moonstoneid/aerocast/aggregator/model/Subscriber.java",
"snippet": "@Data\n@Entity\n@Table(name = \"subscriber\")\npublic class Subscriber implements Serializable {\n\n @Id\n @Column(name = \"account_address\", length = 42, nullable = false)\n private String accountAddress;\n\n @Column(name = \"contract_address\", length = 42, nullable = false)\n private String contractAddress;\n\n @Column(name = \"block_number\", length = 42, nullable = false)\n private String blockNumber;\n\n}"
},
{
"identifier": "SubscriberService",
"path": "apps/feed-aggregator/src/main/java/com/moonstoneid/aerocast/aggregator/service/SubscriberService.java",
"snippet": "@Service\n@Slf4j\npublic class SubscriberService implements EthSubscriberAdapter.EventCallback {\n\n public interface EventListener {\n void onSubscriptionChange(String subContractAddr);\n }\n\n private final SubscriberRepo subscriberRepo;\n private final SubscriptionRepo subscriptionRepo;\n private final PublisherService publisherService;\n\n private final EthSubscriberAdapter ethSubscriberAdapter;\n\n private final List<EventListener> eventListeners = new ArrayList<>();\n\n public SubscriberService(SubscriberRepo subscriberRepo, SubscriptionRepo subscriptionRepo,\n PublisherService publisherService, EthSubscriberAdapter ethSubscriberAdapter) {\n this.subscriberRepo = subscriberRepo;\n this.subscriptionRepo = subscriptionRepo;\n this.publisherService = publisherService;\n this.ethSubscriberAdapter = ethSubscriberAdapter;\n }\n\n public void registerEventListener(EventListener listener) {\n eventListeners.add(listener);\n }\n\n public void unregisterEventListener(EventListener listener) {\n eventListeners.remove(listener);\n }\n\n // Register listeners after Spring Boot has started\n @org.springframework.context.event.EventListener(ApplicationReadyEvent.class)\n public void initEventListener() {\n getSubscribers().forEach(s -> ethSubscriberAdapter.registerSubscriptionEventListener(\n s.getContractAddress(), s.getBlockNumber(), this));\n }\n\n @Override\n public void onCreateSubscription(String subContractAddr, String blockNumber,\n String pubContractAddr) {\n String contractAddr = subContractAddr.toLowerCase();\n\n updateSubscriberEventBlockNumber(contractAddr, blockNumber);\n\n createSubscription(contractAddr, pubContractAddr);\n\n eventListeners.forEach(l -> l.onSubscriptionChange(subContractAddr));\n }\n\n @Override\n public void onRemoveSubscription(String subContractAddr, String blockNumber,\n String pubContractAddr) {\n String contractAddr = subContractAddr.toLowerCase();\n\n updateSubscriberEventBlockNumber(contractAddr, blockNumber);\n\n removeSubscription(contractAddr, pubContractAddr);\n\n eventListeners.forEach(l -> l.onSubscriptionChange(subContractAddr));\n }\n\n public List<Subscriber> getSubscribers() {\n return subscriberRepo.findAll();\n }\n\n private Optional<Subscriber> findSubscriber(String subAccountAddr) {\n String accountAddr = subAccountAddr.toLowerCase();\n return subscriberRepo.findById(accountAddr);\n }\n\n public Subscriber getSubscriber(String subAccountAddr) {\n Optional<Subscriber> subscriber = findSubscriber(subAccountAddr);\n return subscriber\n .orElseThrow(() -> new NotFoundException(\"Subscriber was not found!\"));\n }\n\n public void createSubscriber(String subAccountAddr) {\n String accountAddr = subAccountAddr.toLowerCase();\n\n log.info(\"Trying to create subscriber '{}' ...\", EthUtil.shortenAddress(accountAddr));\n\n String currentBlockNum = ethSubscriberAdapter.getCurrentBlockNumber();\n\n // Check if subscriber exists\n if (subscriberRepo.existsById(accountAddr)) {\n log.error(\"Subscriber '{}' already exists!\", EthUtil.shortenAddress(subAccountAddr));\n throw new ConflictException(\"Subscriber already exists!\");\n }\n\n // Get subscriber contract address\n String contractAddr = ethSubscriberAdapter.getSubscriberContractAddress(accountAddr);\n if (contractAddr == null) {\n log.error(\"Contract for subscriber '{}' was not found!\", EthUtil.shortenAddress(\n accountAddr));\n throw new NotFoundException(\"Subscriber was not found!\");\n }\n\n // Create subscriber\n Subscriber sub = new Subscriber();\n sub.setAccountAddress(accountAddr);\n sub.setContractAddress(contractAddr);\n sub.setBlockNumber(currentBlockNum);\n subscriberRepo.save(sub);\n\n // Create subscriptions\n createSubscriptions(contractAddr, ethSubscriberAdapter.getSubscriberSubscriptions(\n contractAddr));\n\n // Register subscriber event listener\n ethSubscriberAdapter.registerSubscriptionEventListener(contractAddr, currentBlockNum, this);\n\n log.info(\"Subscriber '{}' has been created.\", EthUtil.shortenAddress(accountAddr));\n }\n\n public void removeSubscriber(String subAccountAddr) {\n String accountAddr = subAccountAddr.toLowerCase();\n\n log.info(\"Trying to remove subscriber '{}' ...\", EthUtil.shortenAddress(accountAddr));\n\n // Check if subscriber exists\n Optional<Subscriber> sub = findSubscriber(accountAddr);\n if (sub.isEmpty()) {\n log.error(\"Subscriber '{}' was not found!\", EthUtil.shortenAddress(accountAddr));\n return;\n }\n String subContractAddr = sub.get().getContractAddress();\n\n // Unregister subscriber event listener\n ethSubscriberAdapter.unregisterSubscriptionEventListener(subContractAddr);\n\n // Remove subscriber\n subscriberRepo.deleteById(accountAddr);\n\n // Cleanup publishers\n publisherService.cleanupPublishers();\n\n log.info(\"Subscriber '{}' has been removed.\", EthUtil.shortenAddress(accountAddr));\n }\n\n private void createSubscriptions(String subContractAddr,\n List<FeedSubscriber.Subscription> feedSubs) {\n for (FeedSubscriber.Subscription feedSub : feedSubs) {\n createSubscription(subContractAddr, feedSub.pubAddress);\n }\n }\n\n private void createSubscription(String subContractAddr, String pubContractAddr) {\n log.info(\"Adding subscription '{}/{}' ...\", EthUtil.shortenAddress(subContractAddr),\n EthUtil.shortenAddress(pubContractAddr));\n\n // Create publisher\n publisherService.createPublisherIfNotExists(pubContractAddr);\n\n // Create subscription\n Subscription subscription = new Subscription();\n subscription.setSubContractAddress(subContractAddr);\n subscription.setPubContractAddress(pubContractAddr);\n subscriptionRepo.save(subscription);\n }\n\n private void removeSubscription(String subContractAddr, String pubContractAddr) {\n log.info(\"Removing subscription '{}/{}' ...\", EthUtil.shortenAddress(subContractAddr),\n EthUtil.shortenAddress(pubContractAddr));\n\n // Remove subscription\n subscriptionRepo.deleteById(subContractAddr, pubContractAddr);\n\n // Remove publisher\n publisherService.removePublisherIfNotUsed(pubContractAddr);\n }\n\n private void updateSubscriberEventBlockNumber(String subContractAddr, String blockNumber) {\n subscriberRepo.updateSubscriberBlockNumber(subContractAddr, blockNumber);\n }\n\n public List<Subscription> getPublisherSubscriptions(String pubContractAddr) {\n return subscriptionRepo.findAllByPublisherContractAddress(pubContractAddr);\n }\n\n}"
},
{
"identifier": "SSEService",
"path": "apps/feed-aggregator/src/main/java/com/moonstoneid/aerocast/aggregator/service/SSEService.java",
"snippet": "@Service\n@Slf4j\npublic class SSEService implements EntryService.EventListener, SubscriberService.EventListener {\n\n private final SubscriberService subscriberService;\n private final EntryService entryService;\n\n private final Map<String, Set<SseEmitter>> emitters = new HashMap<>();\n\n public SSEService (SubscriberService subscriberService, EntryService entryService) {\n this.subscriberService = subscriberService;\n this.entryService = entryService;\n }\n\n // Register listeners after Spring Boot has started\n @EventListener(ApplicationReadyEvent.class)\n public void initEventListener() {\n subscriberService.registerEventListener(this);\n entryService.registerEventListener(this);\n }\n\n public void registerEmitter(String subContractAddr, SseEmitter emitter) {\n Set<SseEmitter> em = emitters.get(subContractAddr);\n if (em == null) {\n em = new HashSet<>();\n emitters.put(subContractAddr, em);\n }\n em.add(emitter);\n }\n\n @Override\n public void onSubscriptionChange(String subContractAddr) {\n sendSubscriptionChangeUpdate(subContractAddr);\n }\n\n @Override\n public void onNewEntry(EntryDTO entry) {\n sendNewEntryUpdate(entry);\n }\n\n private void sendNewEntryUpdate(EntryDTO entry) {\n List<Subscription> subscriptions = subscriberService.getPublisherSubscriptions(\n entry.getPubContractAddress());\n for (Subscription subscription : subscriptions) {\n String subContractAddr = subscription.getSubContractAddress();\n sendNewEntryUpdate(subContractAddr, entry);\n }\n }\n\n private void sendNewEntryUpdate(String subContractAddr, EntryDTO entry) {\n Set<SseEmitter> sseEmitters = emitters.get(subContractAddr);\n if (sseEmitters == null) {\n return;\n }\n Iterator<SseEmitter> iterator = sseEmitters.iterator();\n while (iterator.hasNext()) {\n SseEmitter emitter = iterator.next();\n try {\n emitter.send(new SSEEventVM<>(SSEEventVM.Command.INSERT, entry));\n } catch (IOException e) {\n emitter.complete();\n iterator.remove();\n }\n }\n }\n\n private void sendSubscriptionChangeUpdate(String subContractAddr) {\n Set<SseEmitter> sseEmitters = emitters.get(subContractAddr);\n if (sseEmitters == null) {\n return;\n }\n Iterator<SseEmitter> iterator = sseEmitters.iterator();\n while (iterator.hasNext()) {\n SseEmitter emitter = iterator.next();\n try {\n emitter.send(new SSEEventVM<>(SSEEventVM.Command.REFRESH, null));\n } catch (IOException e) {\n emitter.complete();\n iterator.remove();\n }\n }\n }\n\n}"
}
] | import com.moonstoneid.aerocast.aggregator.model.Subscriber;
import com.moonstoneid.aerocast.aggregator.service.SubscriberService;
import com.moonstoneid.aerocast.aggregator.service.SSEService;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter; | 2,510 | package com.moonstoneid.aerocast.aggregator.controller;
/**
* Implements a controller for Server Sent Events (SSE). This allows a client-side EventSource to
* establish a persistent connection through which updates can be sent.
*/
@RestController
@RequestMapping(path = "/sse")
public class SSEController {
| package com.moonstoneid.aerocast.aggregator.controller;
/**
* Implements a controller for Server Sent Events (SSE). This allows a client-side EventSource to
* establish a persistent connection through which updates can be sent.
*/
@RestController
@RequestMapping(path = "/sse")
public class SSEController {
| private final SSEService sseService; | 2 | 2023-10-23 20:33:07+00:00 | 4k |
UnityFoundation-io/Libre311 | app/src/main/java/app/service/service/ServiceService.java | [
{
"identifier": "ServiceDTO",
"path": "app/src/main/java/app/dto/service/ServiceDTO.java",
"snippet": "@Introspected\npublic class ServiceDTO {\n\n @JsonProperty(\"service_code\")\n private String serviceCode;\n\n @JsonProperty(\"jurisdiction_id\")\n private String jurisdictionId;\n\n @JsonProperty(\"service_name\")\n private String serviceName;\n\n private String description;\n\n private boolean metadata;\n\n private ServiceType type;\n\n public ServiceDTO() {\n }\n\n public ServiceDTO(Service service) {\n this.serviceCode = service.getServiceCode();\n this.serviceName = service.getServiceName();\n this.description = service.getDescription();\n this.metadata = service.isMetadata();\n this.type = service.getType();\n if (service.getJurisdiction() != null) {\n this.jurisdictionId = service.getJurisdiction().getId();\n }\n }\n\n public String getServiceCode() {\n return serviceCode;\n }\n\n public void setServiceCode(String serviceCode) {\n this.serviceCode = serviceCode;\n }\n\n public String getJurisdictionId() {\n return jurisdictionId;\n }\n\n public void setJurisdictionId(String jurisdictionId) {\n this.jurisdictionId = jurisdictionId;\n }\n\n public String getServiceName() {\n return serviceName;\n }\n\n public void setServiceName(String serviceName) {\n this.serviceName = serviceName;\n }\n\n public String getDescription() {\n return description;\n }\n\n public void setDescription(String description) {\n this.description = description;\n }\n\n public boolean isMetadata() {\n return metadata;\n }\n\n public void setMetadata(boolean metadata) {\n this.metadata = metadata;\n }\n\n public ServiceType getType() {\n return type;\n }\n\n public void setType(ServiceType type) {\n this.type = type;\n }\n}"
},
{
"identifier": "Service",
"path": "app/src/main/java/app/model/service/Service.java",
"snippet": "@Entity\n@Table(name = \"services\")\npublic class Service {\n\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private Long id;\n\n @Column(unique = true)\n private String serviceCode;\n\n @ManyToOne\n @JoinColumn(name = \"jurisdiction_id\")\n private Jurisdiction jurisdiction;\n\n @Column(columnDefinition = \"TEXT\")\n private String serviceDefinitionJson;\n\n @Column(nullable = false, columnDefinition = \"TEXT\")\n private String serviceName;\n\n @Column(columnDefinition = \"TEXT\")\n private String description;\n\n private boolean metadata = false;\n\n @Enumerated(value = EnumType.STRING)\n private ServiceType type = ServiceType.REALTIME;\n\n @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, orphanRemoval = true, mappedBy = \"service\")\n @OnDelete(action = OnDeleteAction.CASCADE)\n private List<ServiceRequest> serviceRequests = new ArrayList<>();\n\n\n public Service(String serviceName) {\n this.serviceName = serviceName;\n }\n\n public Service() {}\n\n public String getServiceCode() {\n return serviceCode;\n }\n\n public void setServiceCode(String serviceCode) {\n this.serviceCode = serviceCode;\n }\n\n public Jurisdiction getJurisdiction() {\n return jurisdiction;\n }\n\n public void setJurisdiction(Jurisdiction jurisdiction) {\n this.jurisdiction = jurisdiction;\n }\n\n public String getServiceName() {\n return serviceName;\n }\n\n public void setServiceName(String serviceName) {\n this.serviceName = serviceName;\n }\n\n public String getDescription() {\n return description;\n }\n\n public void setDescription(String description) {\n this.description = description;\n }\n\n public boolean isMetadata() {\n return metadata;\n }\n\n public void setMetadata(boolean metadata) {\n this.metadata = metadata;\n }\n\n public ServiceType getType() {\n return type;\n }\n\n public void setType(ServiceType type) {\n this.type = type;\n }\n\n public String getServiceDefinitionJson() {\n return serviceDefinitionJson;\n }\n\n public void setServiceDefinitionJson(String serviceDefinitionJson) {\n this.serviceDefinitionJson = serviceDefinitionJson;\n }\n\n public Long getId() {\n return id;\n }\n\n public void setId(Long id) {\n this.id = id;\n }\n\n public List<ServiceRequest> getServiceRequests() {\n return serviceRequests;\n }\n\n public void setServiceRequests(List<ServiceRequest> serviceRequests) {\n this.serviceRequests = serviceRequests;\n }\n\n public void addServiceRequest(ServiceRequest serviceRequest) {\n serviceRequests.add(serviceRequest);\n }\n}"
},
{
"identifier": "ServiceRepository",
"path": "app/src/main/java/app/model/service/ServiceRepository.java",
"snippet": "@Repository\npublic interface ServiceRepository extends PageableRepository<Service, Long> {\n Optional<Service> findByServiceCode(String serviceCode);\n\n Page<Service> findAllByJurisdictionId(String jurisdictionId, Pageable pageable);\n\n Optional<Service> findByServiceCodeAndJurisdictionId(String serviceCode, String jurisdictionId);\n}"
},
{
"identifier": "StorageService",
"path": "app/src/main/java/app/service/storage/StorageService.java",
"snippet": "@Singleton\npublic class StorageService {\n private static final Logger LOG = LoggerFactory.getLogger(StorageService.class);\n private final ObjectStorageOperations<?, ?, ?> objectStorage;\n private final ReCaptchaService reCaptchaService;\n private final GoogleImageSafeSearchService googleImageClassificationService;\n private final StorageUrlUtil storageUrlUtil;\n\n public StorageService(ObjectStorageOperations<?, ?, ?> objectStorage, ReCaptchaService reCaptchaService, GoogleImageSafeSearchService googleImageClassificationService, StorageUrlUtil storageUrlUtil) {\n this.objectStorage = objectStorage;\n this.reCaptchaService = reCaptchaService;\n this.googleImageClassificationService = googleImageClassificationService;\n this.storageUrlUtil = storageUrlUtil;\n }\n\n public StorageService() {\n this.storageUrlUtil = null;\n this.objectStorage = null;\n this.reCaptchaService = null;\n this.googleImageClassificationService = null;\n }\n\n public String upload(@Valid PhotoUploadDTO photoUploadDTO) {\n if (photoUploadDTO.getgRecaptchaResponse() == null || !reCaptchaService.verifyReCaptcha(photoUploadDTO.getgRecaptchaResponse())) {\n LOG.error(\"ReCaptcha verification failed.\");\n return null;\n }\n\n String base64Image = photoUploadDTO.getImage();\n String dataUri = base64Image.split(\",\")[0];\n MediaType mediaType = MediaType.of(dataUri.substring(dataUri.indexOf(\":\")+1, dataUri.indexOf(\";\")));\n\n if (mediaType != MediaType.IMAGE_JPEG_TYPE && mediaType != MediaType.IMAGE_PNG_TYPE) {\n LOG.error(\"File must be jpeg or png.\");\n return null;\n }\n String extension = mediaType.getExtension();\n\n String image = base64Image.split(\",\")[1];\n\n if (googleImageClassificationService.imageIsExplicit(image)) {\n LOG.error(\"Image does not meet SafeSearch criteria.\");\n return null;\n }\n\n byte[] bytes = Base64.getDecoder().decode(image);\n UploadRequest request = UploadRequest.fromBytes(bytes, UUID.randomUUID()+\".\"+extension);\n UploadResponse<?> response = objectStorage.upload(request);\n\n return storageUrlUtil.getObjectUrlString(response.getKey());\n }\n}"
}
] | import app.dto.service.ServiceDTO;
import app.model.service.Service;
import app.model.service.ServiceRepository;
import app.service.storage.StorageService;
import io.micronaut.data.model.Page;
import io.micronaut.data.model.Pageable;
import io.micronaut.http.HttpResponse;
import jakarta.inject.Singleton;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import java.util.Map;
import java.util.Optional; | 2,082 | // Copyright 2023 Libre311 Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package app.service.service;
@Singleton
public class ServiceService {
private static final Logger LOG = LoggerFactory.getLogger(ServiceService.class);
private final ServiceRepository serviceRepository;
public ServiceService(ServiceRepository serviceRepository) {
this.serviceRepository = serviceRepository;
}
public Page<ServiceDTO> findAll(Pageable pageable, String jurisdictionId) { | // Copyright 2023 Libre311 Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package app.service.service;
@Singleton
public class ServiceService {
private static final Logger LOG = LoggerFactory.getLogger(ServiceService.class);
private final ServiceRepository serviceRepository;
public ServiceService(ServiceRepository serviceRepository) {
this.serviceRepository = serviceRepository;
}
public Page<ServiceDTO> findAll(Pageable pageable, String jurisdictionId) { | Page<Service> servicePage; | 1 | 2023-10-18 15:37:36+00:00 | 4k |
JonnyOnlineYT/xenza | src/minecraft/viamcp/ViaMCP.java | [
{
"identifier": "MCPBackwardsLoader",
"path": "src/minecraft/viamcp/loader/MCPBackwardsLoader.java",
"snippet": "public class MCPBackwardsLoader implements ViaBackwardsPlatform {\n private final File file;\n\n public MCPBackwardsLoader(File file) {\n this.init(this.file = new File(file, \"ViaBackwards\"));\n }\n\n @Override\n public Logger getLogger() {\n return ViaMCP.getInstance().getjLogger();\n }\n\n @Override\n public void disable() {\n }\n\n @Override\n public boolean isOutdated() {\n return false;\n }\n\n @Override\n public File getDataFolder() {\n return new File(this.file, \"config.yml\");\n }\n}"
},
{
"identifier": "MCPRewindLoader",
"path": "src/minecraft/viamcp/loader/MCPRewindLoader.java",
"snippet": "public class MCPRewindLoader implements ViaRewindPlatform {\n public MCPRewindLoader(File file) {\n ViaRewindConfigImpl conf = new ViaRewindConfigImpl(file.toPath().resolve(\"ViaRewind\").resolve(\"config.yml\").toFile());\n conf.reloadConfig();\n this.init(conf);\n }\n\n @Override\n public Logger getLogger() {\n return Via.getPlatform().getLogger();\n }\n}"
},
{
"identifier": "MCPViaLoader",
"path": "src/minecraft/viamcp/loader/MCPViaLoader.java",
"snippet": "public class MCPViaLoader implements ViaPlatformLoader {\n @Override\n public void load() {\n Via.getManager().getProviders().use(MovementTransmitterProvider.class, new BungeeMovementTransmitter());\n Via.getManager().getProviders().use(VersionProvider.class, new BaseVersionProvider() {\n @Override\n public int getClosestServerProtocol(UserConnection connection) throws Exception {\n return connection.isClientSide() ? ViaMCP.getInstance().getVersion() : super.getClosestServerProtocol(connection);\n }\n });\n }\n\n @Override\n public void unload() {\n }\n}"
},
{
"identifier": "MCPViaInjector",
"path": "src/minecraft/viamcp/platform/MCPViaInjector.java",
"snippet": "public class MCPViaInjector implements ViaInjector {\n @Override\n public void inject() {\n }\n\n @Override\n public void uninject() {\n }\n\n @Override\n public int getServerProtocolVersion() {\n return 47;\n }\n\n @Override\n public String getEncoderName() {\n return \"via-encoder\";\n }\n\n @Override\n public String getDecoderName() {\n return \"via-decoder\";\n }\n\n @Override\n public JsonObject getDump() {\n return new JsonObject();\n }\n}"
},
{
"identifier": "MCPViaPlatform",
"path": "src/minecraft/viamcp/platform/MCPViaPlatform.java",
"snippet": "public class MCPViaPlatform implements ViaPlatform<UUID> {\n private final Logger logger = new JLoggerToLog4j(new net.augustus.utils.Logger());\n private final MCPViaConfig config;\n private final File dataFolder;\n private final ViaAPI<UUID> api;\n\n public MCPViaPlatform(File dataFolder) {\n Path configDir = dataFolder.toPath().resolve(\"ViaVersion\");\n this.config = new MCPViaConfig(configDir.resolve(\"viaversion.yml\").toFile());\n this.dataFolder = configDir.toFile();\n this.api = new MCPViaAPI();\n }\n\n public static String legacyToJson(String legacy) {\n return GsonComponentSerializer.gson().serialize(LegacyComponentSerializer.legacySection().deserialize(legacy));\n }\n\n @Override\n public Logger getLogger() {\n return this.logger;\n }\n\n @Override\n public String getPlatformName() {\n return \"ViaMCP\";\n }\n\n @Override\n public String getPlatformVersion() {\n return String.valueOf(47);\n }\n\n @Override\n public String getPluginVersion() {\n return \"4.1.1\";\n }\n\n public FutureTaskId runAsync(Runnable runnable) {\n return new FutureTaskId(CompletableFuture.runAsync(runnable, ViaMCP.getInstance().getAsyncExecutor()).exceptionally(throwable -> {\n if (!(throwable instanceof CancellationException)) {\n throwable.printStackTrace();\n }\n\n return null;\n }));\n }\n\n public FutureTaskId runSync(Runnable runnable) {\n return new FutureTaskId(ViaMCP.getInstance().getEventLoop().submit(runnable).addListener(this.errorLogger()));\n }\n\n @Override\n public PlatformTask runSync(Runnable runnable, long ticks) {\n return new FutureTaskId(\n ViaMCP.getInstance().getEventLoop().schedule(() -> this.runSync(runnable), ticks * 50L, TimeUnit.MILLISECONDS).addListener(this.errorLogger())\n );\n }\n\n @Override\n public PlatformTask runRepeatingSync(Runnable runnable, long ticks) {\n return new FutureTaskId(\n ViaMCP.getInstance()\n .getEventLoop()\n .scheduleAtFixedRate(() -> this.runSync(runnable), 0L, ticks * 50L, TimeUnit.MILLISECONDS)\n .addListener(this.errorLogger())\n );\n }\n\n private <T extends Future<?>> GenericFutureListener<T> errorLogger() {\n return future -> {\n if (!future.isCancelled() && future.cause() != null) {\n future.cause().printStackTrace();\n }\n };\n }\n\n @Override\n public ViaCommandSender[] getOnlinePlayers() {\n return new ViaCommandSender[1337];\n }\n\n private ViaCommandSender[] getServerPlayers() {\n return new ViaCommandSender[1337];\n }\n\n @Override\n public void sendMessage(UUID uuid, String s) {\n }\n\n @Override\n public boolean kickPlayer(UUID uuid, String s) {\n return false;\n }\n\n @Override\n public boolean isPluginEnabled() {\n return true;\n }\n\n @Override\n public ViaAPI<UUID> getApi() {\n return this.api;\n }\n\n @Override\n public ViaVersionConfig getConf() {\n return this.config;\n }\n\n @Override\n public ConfigurationProvider getConfigurationProvider() {\n return this.config;\n }\n\n @Override\n public File getDataFolder() {\n return this.dataFolder;\n }\n\n @Override\n public void onReload() {\n this.logger.info(\"ViaVersion was reloaded? (How did that happen)\");\n }\n\n @Override\n public JsonObject getDump() {\n return new JsonObject();\n }\n\n @Override\n public boolean isOldClientsAllowed() {\n return true;\n }\n\n @Override\n public boolean hasPlugin(String s) {\n return false;\n }\n}"
},
{
"identifier": "JLoggerToLog4j",
"path": "src/minecraft/viamcp/utils/JLoggerToLog4j.java",
"snippet": "public class JLoggerToLog4j extends Logger {\n private final net.augustus.utils.Logger base;\n\n public JLoggerToLog4j(net.augustus.utils.Logger logger) {\n super(\"logger\", null);\n this.base = logger;\n }\n\n @Override\n public void log(LogRecord record) {\n this.log(record.getLevel(), record.getMessage());\n }\n\n @Override\n public void log(Level level, String msg) {\n if (level == Level.FINE) {\n //this.base.debug(msg);\n } else if (level == Level.WARNING) {\n this.base.warn(msg);\n } else if (level == Level.SEVERE) {\n this.base.error(msg);\n } else if (level == Level.INFO) {\n this.base.info(msg);\n }\n }\n\n @Override\n public void log(Level level, String msg, Object param1) {\n if (level == Level.FINE) {\n //this.base.debug(msg, param1);\n } else if (level == Level.WARNING) {\n this.base.warn(msg, param1);\n } else if (level == Level.SEVERE) {\n this.base.error(msg, param1);\n } else if (level == Level.INFO) {\n this.base.info(msg, param1);\n }\n }\n\n @Override\n public void log(Level level, String msg, Object[] params) {\n this.log(level, MessageFormat.format(msg, params));\n }\n\n @Override\n public void log(Level level, String msg, Throwable params) {\n if (level == Level.FINE) {\n //this.base.debug(msg, params);\n } else if (level == Level.WARNING) {\n this.base.warn(msg, params);\n } else if (level == Level.SEVERE) {\n this.base.error(msg, params);\n } else if (level == Level.INFO) {\n this.base.info(msg, params);\n }\n }\n}"
}
] | import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.viaversion.viaversion.ViaManagerImpl;
import com.viaversion.viaversion.api.Via;
import com.viaversion.viaversion.api.data.MappingDataLoader;
import io.netty.channel.EventLoop;
import io.netty.channel.local.LocalEventLoopGroup;
import java.io.File;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.logging.Logger;
import viamcp.loader.MCPBackwardsLoader;
import viamcp.loader.MCPRewindLoader;
import viamcp.loader.MCPViaLoader;
import viamcp.platform.MCPViaInjector;
import viamcp.platform.MCPViaPlatform;
import viamcp.utils.JLoggerToLog4j; | 2,521 | package viamcp;
public class ViaMCP {
public static final int PROTOCOL_VERSION = 47;
private static final ViaMCP instance = new ViaMCP();
private final Logger jLogger = new JLoggerToLog4j(new net.augustus.utils.Logger());
private final CompletableFuture<Void> INIT_FUTURE = new CompletableFuture<>();
private ExecutorService ASYNC_EXEC;
private EventLoop EVENT_LOOP;
private File file;
private int version;
private String lastServer;
public static ViaMCP getInstance() {
return instance;
}
public void start() {
ThreadFactory factory = new ThreadFactoryBuilder().setDaemon(true).setNameFormat("ViaMCP-%d").build();
this.ASYNC_EXEC = Executors.newFixedThreadPool(8, factory);
this.EVENT_LOOP = new LocalEventLoopGroup(1, factory).next();
this.EVENT_LOOP.submit(this.INIT_FUTURE::join);
this.setVersion(47);
this.file = new File("ViaMCP");
if (this.file.mkdir()) {
this.getjLogger().info("Creating ViaMCP Folder");
}
| package viamcp;
public class ViaMCP {
public static final int PROTOCOL_VERSION = 47;
private static final ViaMCP instance = new ViaMCP();
private final Logger jLogger = new JLoggerToLog4j(new net.augustus.utils.Logger());
private final CompletableFuture<Void> INIT_FUTURE = new CompletableFuture<>();
private ExecutorService ASYNC_EXEC;
private EventLoop EVENT_LOOP;
private File file;
private int version;
private String lastServer;
public static ViaMCP getInstance() {
return instance;
}
public void start() {
ThreadFactory factory = new ThreadFactoryBuilder().setDaemon(true).setNameFormat("ViaMCP-%d").build();
this.ASYNC_EXEC = Executors.newFixedThreadPool(8, factory);
this.EVENT_LOOP = new LocalEventLoopGroup(1, factory).next();
this.EVENT_LOOP.submit(this.INIT_FUTURE::join);
this.setVersion(47);
this.file = new File("ViaMCP");
if (this.file.mkdir()) {
this.getjLogger().info("Creating ViaMCP Folder");
}
| Via.init(ViaManagerImpl.builder().injector(new MCPViaInjector()).loader(new MCPViaLoader()).platform(new MCPViaPlatform(this.file)).build()); | 2 | 2023-10-15 00:21:15+00:00 | 4k |
logicaalternativa/algebraictypes | src/test/java/com/logicaalternativa/algebraictypes/examples/ExampleSerializerDeserializerTest.java | [
{
"identifier": "AlgebraDsl",
"path": "src/main/java/com/logicaalternativa/algebraictypes/dsl/AlgebraDsl.java",
"snippet": "public sealed interface AlgebraDsl extends Serializable {\n \n record Number( int value ) implements AlgebraDsl{} \n \n record Addition( AlgebraDsl sumand1, AlgebraDsl summand2 ) implements AlgebraDsl{}\n \n record Negative( AlgebraDsl alg ) implements AlgebraDsl{} \n \n record Subtraction( AlgebraDsl minuend, AlgebraDsl subtrahend ) implements AlgebraDsl{} \n \n record Multiplication( AlgebraDsl one, AlgebraDsl other ) implements AlgebraDsl{} \n\n}"
},
{
"identifier": "AlgebraSerializer",
"path": "src/main/java/com/logicaalternativa/algebraictypes/dsl/interpreter/AlgebraSerializer.java",
"snippet": "public class AlgebraSerializer {\n \n private static String TEMPLATE_NUMBER = \"\"\"\n { \n ~ \"class\": \"%s\", \n ~ \"value\": %d \n ~}\"\"\";\n \n private static String TEMPLATE_OPERATION = \"\"\"\n {\n ~ \"class\": \"%s\", \n ~ \"one\": %s, \n ~ \"other\": %s \n ~}\"\"\";\n \n private static String TEMPLATE_NEGATIVE = \"\"\"\n { \n ~ \"class\": \"%s\", \n ~ \"alg\": %s \n ~}\"\"\";\n \n private static final String DEFAULT_INDENT= \" \";\n \n private static String addDefautlIdent( String ident) {\n return ident + DEFAULT_INDENT;\n }\n \n private static String interpreterJson( AlgebraDsl a, String indent ) {\n \n return switch (a) {\n \n case AlgebraDsl.Number(var value) -> \n TEMPLATE_NUMBER.formatted( \n AlgebraDsl.Number.class.getSimpleName(), \n value \n ).replaceAll( \"~\", indent );\n \n case AlgebraDsl.Addition( var one, var other ) -> \n TEMPLATE_OPERATION.formatted( \n AlgebraDsl.Addition.class.getSimpleName(), \n interpreterJson( one, addDefautlIdent( indent ) ), \n interpreterJson( other, addDefautlIdent( indent ) )\n ).replaceAll( \"~\", indent );\n \n case AlgebraDsl.Subtraction( var one, var other ) -> \n TEMPLATE_OPERATION.formatted(\n AlgebraDsl.Subtraction.class.getSimpleName(), \n interpreterJson( one, addDefautlIdent( indent ) ), \n interpreterJson( other, addDefautlIdent( indent ) )\n ).replaceAll( \"~\", indent );\n \n case AlgebraDsl.Multiplication( var one, var other ) -> \n TEMPLATE_OPERATION.formatted(\n AlgebraDsl.Multiplication.class.getSimpleName(), \n interpreterJson( one, addDefautlIdent( indent ) ), \n interpreterJson( other, addDefautlIdent( indent ) ) \n ).replaceAll( \"~\", indent );\n \n case AlgebraDsl.Negative( var other ) ->\n TEMPLATE_NEGATIVE.formatted( \n AlgebraDsl.Negative.class.getSimpleName(), \n interpreterJson( other, addDefautlIdent( indent ) )\n ).replaceAll( \"~\", indent );\n };\n \n } \n \n \n public static String interpreterJson( AlgebraDsl a ) {\n return interpreterJson( a, \"\" );\n }\n}"
},
{
"identifier": "InterpreterInt",
"path": "src/main/java/com/logicaalternativa/algebraictypes/dsl/interpreter/InterpreterInt.java",
"snippet": "public class InterpreterInt {\n \n private InterpreterInt(){}\n \n public static int interpreter( AlgebraDsl a ) {\n \n return switch (a) {\n \n case AlgebraDsl.Number(var value) -> \n value;\n \n case AlgebraDsl.Addition( var one, var other ) ->\n interpreter( one ) + interpreter(other );\n \n case AlgebraDsl.Subtraction( var one, var other ) ->\n interpreter( one ) - interpreter( other );\n \n case AlgebraDsl.Multiplication( var one, var other ) -> \n interpreter( one ) * interpreter( other );\n \n case AlgebraDsl.Negative( var other ) ->\n -1 * interpreter( other );\n };\n }\n \n}"
},
{
"identifier": "AlgebraDeserializer",
"path": "src/main/java/com/logicaalternativa/algebraictypes/dsl/json/AlgebraDeserializer.java",
"snippet": "public class AlgebraDeserializer implements JsonDeserializer<AlgebraDsl> {\n @Override\n public AlgebraDsl deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) {\n\n final var jsonObject = json.getAsJsonObject();\n\n final var class_ = jsonObject.get(\"class\").getAsString();\n\n return switch (class_) {\n\n case \"Number\" ->\n new AlgebraDsl.Number(\n jsonObject.get(\"value\").getAsInt());\n\n case \"Multiplication\" ->\n new AlgebraDsl.Multiplication(\n context.deserialize(jsonObject.get(\"one\"), AlgebraDsl.class),\n context.deserialize(jsonObject.get(\"other\"), AlgebraDsl.class));\n\n case \"Addition\" ->\n new AlgebraDsl.Addition(\n context.deserialize(jsonObject.get(\"one\"), AlgebraDsl.class),\n context.deserialize(jsonObject.get(\"other\"), AlgebraDsl.class));\n\n case \"Subtraction\" ->\n new AlgebraDsl.Subtraction(\n context.deserialize(jsonObject.get(\"one\"), AlgebraDsl.class),\n context.deserialize(jsonObject.get(\"other\"), AlgebraDsl.class));\n\n case \"Negative\" ->\n new AlgebraDsl.Negative(\n context.deserialize(jsonObject.get(\"alg\"), AlgebraDsl.class));\n\n default ->\n throw new IllegalArgumentException();\n\n };\n\n }\n}"
},
{
"identifier": "AlgebraExample",
"path": "src/test/java/com/logicaalternativa/algebraictypes/examples/mother/AlgebraExample.java",
"snippet": "public class AlgebraExample {\n\n public static final AlgebraDsl EXAMPLE_PROGRAM = new AlgebraDsl.Negative(\n new AlgebraDsl.Multiplication(\n new AlgebraDsl.Addition(\n new AlgebraDsl.Number(5),\n new AlgebraDsl.Number(10)\n ),\n new AlgebraDsl.Subtraction( \n new AlgebraDsl.Number(8),\n new AlgebraDsl.Number(5)\n )\n )\n );\n\n private AlgebraExample() {\n }\n\n}"
}
] | import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.logicaalternativa.algebraictypes.dsl.AlgebraDsl;
import com.logicaalternativa.algebraictypes.dsl.interpreter.AlgebraSerializer;
import com.logicaalternativa.algebraictypes.dsl.interpreter.InterpreterInt;
import com.logicaalternativa.algebraictypes.dsl.json.AlgebraDeserializer;
import com.logicaalternativa.algebraictypes.examples.mother.AlgebraExample; | 1,733 | package com.logicaalternativa.algebraictypes.examples;
public class ExampleSerializerDeserializerTest {
private final Gson gson = initGson();
@Test
@DisplayName("Example of serializer/deserializer data")
void test() {
final Queue<String> messageBroker = new ConcurrentLinkedQueue<>();
simulatePublisher(messageBroker);
final var res = simulateSubscriber(messageBroker);
assertEquals(-45, res);
}
private void simulatePublisher(Queue<String> messageBroker) {
final var myProgramSerialized = AlgebraSerializer.interpreterJson( | package com.logicaalternativa.algebraictypes.examples;
public class ExampleSerializerDeserializerTest {
private final Gson gson = initGson();
@Test
@DisplayName("Example of serializer/deserializer data")
void test() {
final Queue<String> messageBroker = new ConcurrentLinkedQueue<>();
simulatePublisher(messageBroker);
final var res = simulateSubscriber(messageBroker);
assertEquals(-45, res);
}
private void simulatePublisher(Queue<String> messageBroker) {
final var myProgramSerialized = AlgebraSerializer.interpreterJson( | AlgebraExample.EXAMPLE_PROGRAM); | 4 | 2023-10-21 20:03:49+00:00 | 4k |
Radekyspec/TasksMaster | src/main/java/view/schedule/AddNewEventView.java | [
{
"identifier": "ViewManagerModel",
"path": "src/main/java/interface_adapter/ViewManagerModel.java",
"snippet": "public class ViewManagerModel {\n private final PropertyChangeSupport support = new PropertyChangeSupport(this);\n private String activeViewName;\n\n public String getActiveView() {\n return activeViewName;\n }\n\n public void setActiveView(String activeView) {\n this.activeViewName = activeView;\n }\n\n public void firePropertyChanged() {\n support.firePropertyChange(\"view\", null, this.activeViewName);\n }\n\n public void addPropertyChangeListener(PropertyChangeListener listener) {\n support.addPropertyChangeListener(listener);\n }\n}"
},
{
"identifier": "ScheduleViewModel",
"path": "src/main/java/interface_adapter/schedule/ScheduleViewModel.java",
"snippet": "public class ScheduleViewModel extends ViewModel {\n public static final String SCHEDULE_TITLE_LABEL = \"Project Schedule\";\n public static final String SCHEDULE_ADD_NEW_EVENT = \"Add new event\";\n public static final String SCHEDULE_SET_EVENT = \"Set event\";\n public static final String SCHEDULE_NO_EVENT = \"There is no event now\";\n\n private final ScheduleState scheduleState = new ScheduleState();\n\n private final PropertyChangeSupport support = new PropertyChangeSupport(this);\n\n public ScheduleViewModel() {\n super(\"Schedule\");\n }\n\n @Override\n public void firePropertyChanged() {\n support.firePropertyChange(\"new event\", null, scheduleState);\n }\n\n public void firePropertyChanged(String scheduleSetEvent) {\n support.firePropertyChange(scheduleSetEvent, null, scheduleState);\n }\n\n @Override\n public void addPropertyChangeListener(PropertyChangeListener listener) {\n support.addPropertyChangeListener(listener);\n }\n\n public ScheduleState getScheduleState() {\n return scheduleState;\n }\n\n public void setProjectID(long projectID) {\n scheduleState.setProjectId(projectID);\n }\n}"
},
{
"identifier": "AddEventController",
"path": "src/main/java/interface_adapter/schedule/event/AddEventController.java",
"snippet": "public class AddEventController {\n final AddNewEventInputBoundary addNewEventInteractor;\n\n public AddEventController(AddNewEventInputBoundary addNewEventInteractor) {\n this.addNewEventInteractor = addNewEventInteractor;\n }\n\n public void postEvent(long projectId, long scheduleId, String eventName, String notes, Date startAt, Date endAt, boolean isAllDay, List<String> userwith) {\n AddNewEventInputData addNewEventInputData = new AddNewEventInputData(projectId, scheduleId, eventName, notes, startAt, endAt, isAllDay, userwith);\n addNewEventInteractor.postEvent(addNewEventInputData);\n }\n}"
},
{
"identifier": "AddEventState",
"path": "src/main/java/interface_adapter/schedule/event/AddEventState.java",
"snippet": "public class AddEventState {\n private long projectId;\n private long scheduleId;\n private String eventName;\n private String notes;\n private Date startAt;\n private Date endAt;\n private boolean isAllDay;\n private List<String> userwith;\n\n public long getProjectId() {\n return projectId;\n }\n\n public void setProjectId(long projectId) {\n this.projectId = projectId;\n }\n\n public long getScheduleId() {\n return scheduleId;\n }\n\n public void setScheduleId(long scheduleId) {\n this.scheduleId = scheduleId;\n }\n\n public String getEventName() {\n return eventName;\n }\n\n public void setEventName(String eventName) {\n this.eventName = eventName;\n }\n\n public String getNotes() {\n return notes;\n }\n\n public void setNotes(String notes) {\n this.notes = notes;\n }\n\n public Date getStartAt() {\n return startAt;\n }\n\n public void setStartAt(Date startAt) {\n this.startAt = startAt;\n }\n\n public Date getEndAt() {\n return endAt;\n }\n\n public void setEndAt(Date endAt) {\n this.endAt = endAt;\n }\n\n public boolean isAllDay() {\n return isAllDay;\n }\n\n public void setAllDay(boolean allDay) {\n isAllDay = allDay;\n }\n\n public List<String> getUserwith() {\n return userwith;\n }\n\n public void setUserwith(List<String> userwith) {\n this.userwith = userwith;\n }\n}"
},
{
"identifier": "AddEventViewModel",
"path": "src/main/java/interface_adapter/schedule/event/AddEventViewModel.java",
"snippet": "public class AddEventViewModel extends ViewModel {\n public static final String EVENT_NAME = \"Event Title\";\n public static final String EVENT_NOTES = \"Event Notes\";\n public static final String EVENT_STARTDATE = \"Start at (dd-MM-yyyy)\";\n public static final String EVENT_ENDDATE = \"End at (dd-MM-yyyy)\";\n public static final String EVENT_ISALLDAY = \"Is all day? Type 'Y' or 'N'\";\n public static final String EVENT_USERWITH = \"User with? Separate user by using ',' (No space) \";\n public static final String EVENT_POST = \"Post this event\";\n public static final String EVENT_POST_FAIL = \"Fail to post this event\";\n\n private final AddEventState addEventState = new AddEventState();\n private final PropertyChangeSupport propertyChangeSupport = new PropertyChangeSupport(this);\n\n public AddEventViewModel() {\n super(\"Add a new event\");\n }\n\n public void setProjectId(long projectId) {\n addEventState.setProjectId(projectId);\n }\n\n public void setScheduleId(long scheduleId) {\n addEventState.setScheduleId(scheduleId);\n }\n\n public void setEventName(String eventName) {\n addEventState.setEventName(eventName);\n }\n\n public void setNotes(String notes) {\n addEventState.setNotes(notes);\n }\n\n public void setStartAt(Date startAt) {\n addEventState.setStartAt(startAt);\n }\n\n public void setEndAt(Date endAt) {\n addEventState.setEndAt(endAt);\n }\n\n public void setIsAllDay(boolean isAllDay) {\n addEventState.setAllDay(isAllDay);\n }\n\n public void setUserWith(List<String> userWith) {\n addEventState.setUserwith(userWith);\n }\n\n public AddEventState getAddEventState() {\n return addEventState;\n }\n\n @Override\n public void firePropertyChanged() {\n\n }\n\n @Override\n public void addPropertyChangeListener(PropertyChangeListener listener) {\n\n }\n}"
},
{
"identifier": "JButtonWithFont",
"path": "src/main/java/view/JButtonWithFont.java",
"snippet": "public class JButtonWithFont extends JButton {\n private final int defaultSize = 26;\n\n public JButtonWithFont() {\n super();\n setFont(new Font(\"Times New Roman\", Font.PLAIN, defaultSize));\n }\n\n public JButtonWithFont(String text) {\n super(text);\n setBounds(50, 100, 150, 50);\n setFont(new Font(\"Times New Roman\", Font.PLAIN, defaultSize));\n }\n\n public JButtonWithFont(String text, int size) {\n super(text);\n setFont(new Font(\"Times New Roman\", Font.PLAIN, size));\n }\n\n public JButtonWithFont(String text, int style, int size) {\n super(text);\n setFont(new Font(\"Times New Roman\", style, size));\n }\n\n public JButtonWithFont(String text, String name, int style, int size) {\n super(text);\n setFont(new Font(name, style, size));\n }\n\n\n}"
},
{
"identifier": "JLabelWithFont",
"path": "src/main/java/view/JLabelWithFont.java",
"snippet": "public class JLabelWithFont extends JLabel {\n private final int defaultSize = 26;\n\n public JLabelWithFont() {\n super();\n setFont(new Font(\"Times New Roman\", Font.PLAIN, defaultSize));\n }\n\n public JLabelWithFont(int style, int size) {\n super();\n setFont(new Font(\"Times New Roman\", style, size));\n }\n\n public JLabelWithFont(String text) {\n super(text);\n setFont(new Font(\"Times New Roman\", Font.PLAIN, defaultSize));\n }\n\n public JLabelWithFont(String text, int size) {\n super(text);\n setFont(new Font(\"Times New Roman\", Font.PLAIN, size));\n }\n\n public JLabelWithFont(String text, int style, int size) {\n super(text);\n setFont(new Font(\"Times New Roman\", style, size));\n }\n\n public JLabelWithFont(String text, String name, int style, int size) {\n super(text);\n setFont(new Font(name, style, size));\n }\n}"
}
] | import interface_adapter.ViewManagerModel;
import interface_adapter.schedule.ScheduleViewModel;
import interface_adapter.schedule.event.AddEventController;
import interface_adapter.schedule.event.AddEventState;
import interface_adapter.schedule.event.AddEventViewModel;
import view.JButtonWithFont;
import view.JLabelWithFont;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Objects; | 2,623 | package view.schedule;
public class AddNewEventView extends JPanel implements ActionListener, PropertyChangeListener {
private final ViewManagerModel viewManagerModel;
private final AddEventViewModel addEventViewModel;
private final AddEventController addEventController;
private final ScheduleViewModel scheduleViewModel;
private final JPanel eventNameInfo = new JPanel();
private final JPanel eventNoteInfo = new JPanel();
private final JPanel eventStartInfo = new JPanel();
private final JPanel eventEndInfo = new JPanel();
private final JPanel eventAllDayInfo = new JPanel();
private final JPanel eventUserWithInfo = new JPanel();
private final JTextField eventNameInputField = new JTextField(30);
private final JTextField eventNoteInputField = new JTextField(30);
private final JTextField eventStartInputField = new JTextField(30);
private final JTextField eventEndInputField = new JTextField(30);
private final JTextField eventAllDayInputField = new JTextField(30);
private final JTextField eventUserWithInputField = new JTextField(30);
private final JButton postButton;
public AddNewEventView(ViewManagerModel viewManagerModel, AddEventViewModel addEventViewModel, ScheduleViewModel scheduleViewModel, AddEventController addEventController) {
this.viewManagerModel = viewManagerModel;
this.addEventViewModel = addEventViewModel;
this.addEventController = addEventController;
this.scheduleViewModel = scheduleViewModel;
addEventViewModel.addPropertyChangeListener(this);
eventNameInputField.setFont(new Font("Times New Roman", Font.PLAIN, 26));
eventNoteInputField.setFont(new Font("Times New Roman", Font.PLAIN, 26));
;
eventStartInputField.setFont(new Font("Times New Roman", Font.PLAIN, 26));
eventEndInputField.setFont(new Font("Times New Roman", Font.PLAIN, 26));
eventAllDayInputField.setFont(new Font("Times New Roman", Font.PLAIN, 26));
// eventUserWithInputField.setFont(new Font("Times New Roman", Font.PLAIN, 26));
| package view.schedule;
public class AddNewEventView extends JPanel implements ActionListener, PropertyChangeListener {
private final ViewManagerModel viewManagerModel;
private final AddEventViewModel addEventViewModel;
private final AddEventController addEventController;
private final ScheduleViewModel scheduleViewModel;
private final JPanel eventNameInfo = new JPanel();
private final JPanel eventNoteInfo = new JPanel();
private final JPanel eventStartInfo = new JPanel();
private final JPanel eventEndInfo = new JPanel();
private final JPanel eventAllDayInfo = new JPanel();
private final JPanel eventUserWithInfo = new JPanel();
private final JTextField eventNameInputField = new JTextField(30);
private final JTextField eventNoteInputField = new JTextField(30);
private final JTextField eventStartInputField = new JTextField(30);
private final JTextField eventEndInputField = new JTextField(30);
private final JTextField eventAllDayInputField = new JTextField(30);
private final JTextField eventUserWithInputField = new JTextField(30);
private final JButton postButton;
public AddNewEventView(ViewManagerModel viewManagerModel, AddEventViewModel addEventViewModel, ScheduleViewModel scheduleViewModel, AddEventController addEventController) {
this.viewManagerModel = viewManagerModel;
this.addEventViewModel = addEventViewModel;
this.addEventController = addEventController;
this.scheduleViewModel = scheduleViewModel;
addEventViewModel.addPropertyChangeListener(this);
eventNameInputField.setFont(new Font("Times New Roman", Font.PLAIN, 26));
eventNoteInputField.setFont(new Font("Times New Roman", Font.PLAIN, 26));
;
eventStartInputField.setFont(new Font("Times New Roman", Font.PLAIN, 26));
eventEndInputField.setFont(new Font("Times New Roman", Font.PLAIN, 26));
eventAllDayInputField.setFont(new Font("Times New Roman", Font.PLAIN, 26));
// eventUserWithInputField.setFont(new Font("Times New Roman", Font.PLAIN, 26));
| eventNameInfo.add(new JLabelWithFont(AddEventViewModel.EVENT_NAME)); | 6 | 2023-10-23 15:17:21+00:00 | 4k |
denis-vp/toy-language-interpreter | src/main/java/repository/Repository.java | [
{
"identifier": "IDictionary",
"path": "src/main/java/adt/IDictionary.java",
"snippet": "public interface IDictionary<K, V> {\n void add(K key, V value);\n\n void remove(K key);\n\n V get(K key);\n\n void update(K key, V value);\n\n boolean search(K key);\n\n int size();\n\n boolean isEmpty();\n\n Collection<Map.Entry<K, V>> entrySet();\n\n Set<K> keys();\n\n Collection<V> values();\n\n IDictionary<K, V> deepCopy();\n}"
},
{
"identifier": "IHeap",
"path": "src/main/java/adt/IHeap.java",
"snippet": "public interface IHeap {\n int add(Value value);\n\n void remove(Integer key);\n\n Value get(Integer key);\n\n void update(Integer key, Value value);\n\n boolean search(Integer key);\n\n int size();\n\n boolean isEmpty();\n\n Map<Integer, Value> getContent();\n\n void setContent(Map<Integer, Value> heap);\n\n Set<Integer> keys();\n\n Collection<Value> values();\n}"
},
{
"identifier": "ADTException",
"path": "src/main/java/exception/ADTException.java",
"snippet": "public class ADTException extends InterpreterException {\n public ADTException(String message) {\n super(message);\n }\n}"
},
{
"identifier": "RepositoryException",
"path": "src/main/java/exception/RepositoryException.java",
"snippet": "public class RepositoryException extends InterpreterException {\n public RepositoryException(String message) {\n super(message);\n }\n}"
},
{
"identifier": "ProgramState",
"path": "src/main/java/model/ProgramState.java",
"snippet": "public class ProgramState {\n private final Statement originalProgram;\n private final IStack<Statement> executionStack;\n private final IDictionary<String, Value> symbolTable;\n private final IHeap heap;\n private final IDictionary<String, BufferedReader> fileTable;\n private final IList<Value> output;\n private final int id;\n private static final Set<Integer> ids = new HashSet<>();\n\n public ProgramState(Statement originalProgram,\n IStack<Statement> executionStack, IDictionary<String, Value> symbolTable,\n IHeap heap, IDictionary<String, BufferedReader> fileTable,\n IList<Value> output) {\n\n this.originalProgram = originalProgram.deepCopy();\n this.executionStack = executionStack;\n this.symbolTable = symbolTable;\n this.heap = heap;\n this.fileTable = fileTable;\n this.output = output;\n\n this.id = ProgramState.generateNewId();\n executionStack.push(originalProgram);\n }\n\n private static int generateNewId() {\n Random random = new Random();\n int id;\n synchronized (ProgramState.ids) {\n do {\n id = random.nextInt();\n } while (ProgramState.ids.contains(id));\n ProgramState.ids.add(id);\n }\n return id;\n }\n\n public int getId() {\n return this.id;\n }\n\n public Statement getOriginalProgram() {\n return this.originalProgram;\n }\n\n public IStack<Statement> getExecutionStack() {\n return this.executionStack;\n }\n\n public IDictionary<String, Value> getSymbolTable() {\n return this.symbolTable;\n }\n\n public IHeap getHeap() {\n return this.heap;\n }\n\n public IDictionary<String, BufferedReader> getFileTable() {\n return this.fileTable;\n }\n\n public IList<Value> getOutput() {\n return this.output;\n }\n\n public boolean isNotCompleted() {\n return !this.executionStack.isEmpty();\n }\n\n public ProgramState oneStep() throws ProgramStateException {\n if (this.executionStack.isEmpty()) {\n throw new ProgramStateException(\"Execution stack is empty!\");\n }\n\n try {\n Statement currentStatement = this.executionStack.pop();\n return currentStatement.execute(this);\n } catch (StatementException | ADTException e) {\n throw new ProgramStateException(e.getMessage());\n }\n }\n\n public String toString() {\n StringBuilder stringBuilder = new StringBuilder();\n\n stringBuilder.append(\"Program State: \").append(this.id).append(\"\\n\");\n stringBuilder.append(\"Execution Stack:\\n\");\n if (this.executionStack.isEmpty()) {\n stringBuilder.append(\"----------Empty----------\\n\");\n } else {\n stringBuilder.append(this.executionStack);\n }\n stringBuilder.append(\"-------------------------------------------\\n\");\n stringBuilder.append(\"Symbol Table:\\n\");\n if (this.symbolTable.isEmpty()) {\n stringBuilder.append(\"----------Empty----------\\n\");\n } else {\n stringBuilder.append(this.symbolTable);\n }\n stringBuilder.append(\"-------------------------------------------\\n\");\n stringBuilder.append(\"Heap:\\n\");\n if (this.heap.isEmpty()) {\n stringBuilder.append(\"----------Empty----------\\n\");\n } else {\n stringBuilder.append(this.heap);\n }\n stringBuilder.append(\"-------------------------------------------\\n\");\n stringBuilder.append(\"File Table:\\n\");\n if (this.fileTable.isEmpty()) {\n stringBuilder.append(\"----------Empty----------\\n\");\n } else {\n stringBuilder.append(this.fileTable);\n }\n stringBuilder.append(\"-------------------------------------------\\n\");\n stringBuilder.append(\"Output:\\n\");\n if (this.output.isEmpty()) {\n stringBuilder.append(\"----------Empty----------\\n\");\n } else {\n stringBuilder.append(this.output);\n }\n stringBuilder.append(\"-------------------------------------------\\n\");\n\n return stringBuilder.toString();\n }\n}"
},
{
"identifier": "CompoundStatement",
"path": "src/main/java/model/statement/CompoundStatement.java",
"snippet": "public class CompoundStatement implements Statement {\n private final Statement first;\n private final Statement second;\n\n public CompoundStatement(Statement first, Statement second) {\n this.first = first;\n this.second = second;\n }\n\n @Override\n public ProgramState execute(ProgramState state) {\n IStack<Statement> stack = state.getExecutionStack();\n\n stack.push(this.second);\n stack.push(this.first);\n\n return null;\n }\n\n @Override\n public IDictionary<String, Type> typeCheck(IDictionary<String, Type> typeEnvironment) throws StatementException {\n return this.second.typeCheck(this.first.typeCheck(typeEnvironment));\n }\n\n @Override\n public Statement deepCopy() {\n return new CompoundStatement(this.first.deepCopy(), this.second.deepCopy());\n }\n\n public String toString() {\n return \"(\" + this.first + \"; \" + this.second + \")\";\n }\n}"
},
{
"identifier": "Value",
"path": "src/main/java/model/value/Value.java",
"snippet": "public interface Value {\n Type getType();\n\n Value deepCopy();\n}"
}
] | import adt.IDictionary;
import adt.IHeap;
import exception.ADTException;
import exception.RepositoryException;
import model.ProgramState;
import model.statement.CompoundStatement;
import model.value.Value;
import java.io.*;
import java.util.ArrayList;
import java.util.List; | 1,733 | package repository;
public class Repository implements IRepository {
private final List<ProgramState> programStateList = new ArrayList<ProgramState>();
private final String logFilePath;
public Repository(ProgramState initialProgram, String logFilePath) {
this.programStateList.add(initialProgram);
this.logFilePath = logFilePath;
}
@Override
public List<ProgramState> getProgramStateList() {
return List.copyOf(this.programStateList);
}
@Override
public void setProgramStateList(List<ProgramState> programStateList) {
this.programStateList.clear();
this.programStateList.addAll(programStateList);
}
@Override
public IHeap getHeap() {
return this.programStateList.get(0).getHeap();
}
@Override | package repository;
public class Repository implements IRepository {
private final List<ProgramState> programStateList = new ArrayList<ProgramState>();
private final String logFilePath;
public Repository(ProgramState initialProgram, String logFilePath) {
this.programStateList.add(initialProgram);
this.logFilePath = logFilePath;
}
@Override
public List<ProgramState> getProgramStateList() {
return List.copyOf(this.programStateList);
}
@Override
public void setProgramStateList(List<ProgramState> programStateList) {
this.programStateList.clear();
this.programStateList.addAll(programStateList);
}
@Override
public IHeap getHeap() {
return this.programStateList.get(0).getHeap();
}
@Override | public IDictionary<String, Value> getSymbolTable() { | 6 | 2023-10-21 18:08:59+00:00 | 4k |
PrzemyslawMusial242473/GreenGame | src/main/java/org/io/GreenGame/user/service/implementation/AuthServiceImplementation.java | [
{
"identifier": "SecurityConfig",
"path": "src/main/java/org/io/GreenGame/config/SecurityConfig.java",
"snippet": "@Configuration\n@EnableWebSecurity\npublic class SecurityConfig {\n\n @Autowired\n private UserDetailsService userDetailsService;\n\n @Bean\n public static PasswordEncoder passwordEncoder() {\n return new BCryptPasswordEncoder();\n }\n\n @Bean\n public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {\n http.userDetailsService(userDetailsService)\n .csrf(AbstractHttpConfigurer::disable)\n .cors(AbstractHttpConfigurer::disable)\n .authorizeHttpRequests(request -> {\n request.requestMatchers(\"/\").permitAll();\n request.requestMatchers(\"/register\").permitAll();\n request.requestMatchers(\"/login\").permitAll();\n request.requestMatchers(\"/deleteUser\").permitAll();\n request.requestMatchers(\"/secured/**\")\n .authenticated();\n request.requestMatchers(\"/secured/**\")\n .hasRole(\"USER\");\n }).formLogin(form -> form\n .loginPage(\"/login\")\n .loginProcessingUrl(\"/login\")\n .permitAll().defaultSuccessUrl(\"/secured/hello\", true).failureUrl(\"/login\"))\n .logout(logout -> logout\n .logoutRequestMatcher(new AntPathRequestMatcher(\"/logout\"))\n .permitAll()\n );\n return http.build();\n }\n\n @Autowired\n public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {\n auth\n .userDetailsService(userDetailsService)\n .passwordEncoder(passwordEncoder());\n }\n}"
},
{
"identifier": "GreenGameUser",
"path": "src/main/java/org/io/GreenGame/user/model/GreenGameUser.java",
"snippet": "@Entity\n@Getter\n@Setter\n@NoArgsConstructor\n@AllArgsConstructor\n@Table(name=\"Users\")\npublic class GreenGameUser {\n\n @Id\n @GeneratedValue\n private Long id;\n\n private String Username;\n\n private String Email;\n\n private LocalDateTime CreationDate;\n\n private LocalDateTime ChangeDate;\n\n @ManyToMany(fetch = FetchType.EAGER, cascade=CascadeType.ALL)\n @JoinTable(\n name=\"users_roles\",\n joinColumns={@JoinColumn(name=\"USER_ID\", referencedColumnName=\"ID\")},\n inverseJoinColumns={@JoinColumn(name=\"ROLE_ID\", referencedColumnName=\"ID\")})\n private List<Role> roles = new ArrayList<>();\n @Embedded\n private Security SecurityData;\n\n\n @Override\n public String toString() {\n return \"GreenGameUser{\" +\n \"id=\" + id +\n \", Username='\" + Username + '\\'' +\n \", Email='\" + Email + '\\'' +\n \", CreationDate=\" + CreationDate +\n \", ChangeDate=\" + ChangeDate +\n \", roles=\" + roles +\n \", SecurityData=\" + SecurityData +\n \", passwdhash=\" + SecurityData.getPasswordHash() +\n '}';\n }\n}"
},
{
"identifier": "Role",
"path": "src/main/java/org/io/GreenGame/user/model/Role.java",
"snippet": "@Setter\n@Getter\n@NoArgsConstructor\n@AllArgsConstructor\n@Entity\n@Table(name=\"roles\")\npublic class Role\n{\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private Long id;\n\n @Column(nullable=false, unique=true)\n private String name;\n\n @ManyToMany(mappedBy=\"roles\")\n private List<GreenGameUser> users;\n}"
},
{
"identifier": "Security",
"path": "src/main/java/org/io/GreenGame/user/model/Security.java",
"snippet": "@Setter\n@Getter\n@NoArgsConstructor\n@AllArgsConstructor\n@Embeddable\npublic class Security {\n\n private LocalDateTime SecurityChangeDate;\n\n private LocalDateTime SecurityLastLoginDate;\n\n private String PasswordHash;\n\n}"
},
{
"identifier": "UserRegisterForm",
"path": "src/main/java/org/io/GreenGame/user/model/UserRegisterForm.java",
"snippet": "@Getter\n@Setter\n@NoArgsConstructor\n@AllArgsConstructor\npublic class UserRegisterForm {\n\n String username;\n String email;\n String password;\n String repeatedPassword;\n}"
},
{
"identifier": "RoleRepository",
"path": "src/main/java/org/io/GreenGame/user/repository/RoleRepository.java",
"snippet": "@Repository\npublic interface RoleRepository extends JpaRepository<Role, Long> {\n Role findByName(String name);\n}"
},
{
"identifier": "UserRepository",
"path": "src/main/java/org/io/GreenGame/user/repository/UserRepository.java",
"snippet": "@Repository\npublic interface UserRepository extends JpaRepository<GreenGameUser, Long> {\n\n @Query(\"SELECT COUNT(user.id) FROM GreenGameUser user WHERE user.id = :id\")\n Long checkIfIdIsInDatabase(Long id);\n\n @Query(\"SELECT COUNT(user.Username) FROM GreenGameUser user WHERE user.Username = :username\")\n Long checkIfUsernameIsInDatabase(String username);\n\n @Query(\"SELECT COUNT(user.Email) FROM GreenGameUser user WHERE user.Email = :email\")\n Long checkIfEmailIsInDatabase(String email);\n\n @Query(\"SELECT user FROM GreenGameUser user WHERE user.Email = :email\")\n GreenGameUser findUserByEmail(String email);\n}"
},
{
"identifier": "AuthService",
"path": "src/main/java/org/io/GreenGame/user/service/AuthService.java",
"snippet": "public interface AuthService {\n Boolean registerUser(UserRegisterForm userRegisterForm);\n Boolean deleteUser(GreenGameUser greenGameUser);\n Boolean changePassword(GreenGameUser greenGameUser, String oldPassword, String newPassword);\n GreenGameUser getUserFromSession();\n}"
}
] | import org.io.GreenGame.config.SecurityConfig;
import org.io.GreenGame.user.model.GreenGameUser;
import org.io.GreenGame.user.model.Role;
import org.io.GreenGame.user.model.Security;
import org.io.GreenGame.user.model.UserRegisterForm;
import org.io.GreenGame.user.repository.RoleRepository;
import org.io.GreenGame.user.repository.UserRepository;
import org.io.GreenGame.user.service.AuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.Objects;
import java.util.Random; | 1,612 | package org.io.GreenGame.user.service.implementation;
@Service
@ComponentScan
public class AuthServiceImplementation implements AuthService {
@Autowired
UserRepository userRepository;
@Autowired
RoleRepository roleRepository;
@Override
public Boolean registerUser(UserRegisterForm userRegisterForm) {
Long id = new Random().nextLong();
LocalDateTime creationDate = LocalDateTime.now();
while (userRepository.checkIfIdIsInDatabase(id) != 0) {
id = new Random().nextLong();
}
Boolean doPasswordsMatch = Objects.equals(userRegisterForm.getPassword(), userRegisterForm.getRepeatedPassword());
Long isUsernameInDatabase = userRepository.checkIfUsernameIsInDatabase(userRegisterForm.getUsername());
Long isEmailInDatabase = userRepository.checkIfEmailIsInDatabase(userRegisterForm.getEmail());
if (isUsernameInDatabase != 0 || isEmailInDatabase != 0 || !doPasswordsMatch) {
return false;
} else {
String hashPw = SecurityConfig.passwordEncoder().encode(userRegisterForm.getPassword());
Security security = new Security(creationDate, null, hashPw);
Role role = roleRepository.findByName("ROLE_USER");
if (role == null) {
role = addUserRole();
} | package org.io.GreenGame.user.service.implementation;
@Service
@ComponentScan
public class AuthServiceImplementation implements AuthService {
@Autowired
UserRepository userRepository;
@Autowired
RoleRepository roleRepository;
@Override
public Boolean registerUser(UserRegisterForm userRegisterForm) {
Long id = new Random().nextLong();
LocalDateTime creationDate = LocalDateTime.now();
while (userRepository.checkIfIdIsInDatabase(id) != 0) {
id = new Random().nextLong();
}
Boolean doPasswordsMatch = Objects.equals(userRegisterForm.getPassword(), userRegisterForm.getRepeatedPassword());
Long isUsernameInDatabase = userRepository.checkIfUsernameIsInDatabase(userRegisterForm.getUsername());
Long isEmailInDatabase = userRepository.checkIfEmailIsInDatabase(userRegisterForm.getEmail());
if (isUsernameInDatabase != 0 || isEmailInDatabase != 0 || !doPasswordsMatch) {
return false;
} else {
String hashPw = SecurityConfig.passwordEncoder().encode(userRegisterForm.getPassword());
Security security = new Security(creationDate, null, hashPw);
Role role = roleRepository.findByName("ROLE_USER");
if (role == null) {
role = addUserRole();
} | GreenGameUser greenGameUser = new GreenGameUser(id, userRegisterForm.getUsername(), userRegisterForm.getEmail(), creationDate, creationDate, Collections.singletonList(role), security); | 1 | 2023-10-23 09:21:30+00:00 | 4k |
NewStudyGround/NewStudyGround | server/src/main/java/com/codestates/server/global/security/oauth2/service/KakaoOAuthService.java | [
{
"identifier": "Member",
"path": "server/src/main/java/com/codestates/server/domain/member/entity/Member.java",
"snippet": "@Getter\n@Setter\n@RequiredArgsConstructor\n@Entity\npublic class Member {\n\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private Long memberId;\n\n private String email;\n\n private String name; // 닉네임\n\n private String phone;\n\n private String password;\n\n private String profileImage;\n\n // 멤버 당 하나의 권한을 가지기 때문에 즉시 로딩 괜찮음 (즉시로딩 N : 1은 괜찮으나 1:N은 안됨)\n // 사용자 등록 시 사용자의 권한 등록을 위해 권한 테이블 생성\n @ElementCollection(fetch = FetchType.EAGER)\n private List<String> roles = new ArrayList<>();\n\n @JsonIgnore\n @OneToMany(mappedBy = \"member\", cascade = CascadeType.ALL)\n private List<Board> boards;\n\n @JsonIgnore\n @OneToMany(mappedBy = \"member\", cascade = CascadeType.ALL)\n private List<Answer> answers;\n\n @JsonIgnore\n @OneToMany(mappedBy = \"member\", cascade = CascadeType.ALL)\n private List<Comment> comments;\n\n @JsonIgnore\n @OneToMany(mappedBy = \"member\", cascade = CascadeType.ALL)\n private List<Bookmark> Bookmarks;\n\n}"
},
{
"identifier": "MemberRepository",
"path": "server/src/main/java/com/codestates/server/domain/member/repository/MemberRepository.java",
"snippet": "public interface MemberRepository extends JpaRepository<Member, Long> {\n Optional<Member> findByEmail(String email);\n\n}"
},
{
"identifier": "BusinessLogicException",
"path": "server/src/main/java/com/codestates/server/global/exception/BusinessLogicException.java",
"snippet": "public class BusinessLogicException extends RuntimeException {\n @Getter\n private ExceptionCode exceptionCode;\n\n public BusinessLogicException(ExceptionCode exceptionCode) {\n super(exceptionCode.getMessage());\n this.exceptionCode = exceptionCode;\n }\n}"
},
{
"identifier": "ExceptionCode",
"path": "server/src/main/java/com/codestates/server/global/exception/ExceptionCode.java",
"snippet": "public enum ExceptionCode {\n //User not in database\n USER_NOT_FOUND(404, \"User not found\"),\n //User exists\n USER_EXISTS(409, \"User exists\"),\n //Unauthorized user\n UNAUTHORIZED_USER(401, \"Unauthorized user\"),\n // answer not in database\n ANSWER_NOT_FOUND(404, \"Answer not found\"),\n // comment not in database\n COMMENT_NOT_FOUND(404, \"Comment not found\"),\n // Board not in database\n BOARD_NOT_FOUND(404, \"Board not found\"),\n //Bookmark exists\n BOOKMARK_EXISTS(409, \"bookmark exists\"),\n //Bookmark Not in database\n BOOKMARK_NOT_FOUND(404,\"Bookmark not found\"),\n //LicenseInfo Not in database\n LICENSE_NOT_FOUND(404,\"License not found\"),\n // kakako 로부터 유효한 정보 받지 못함\n UNAUTHORIZED_KAKAO(401, \"카카오로부터 유효한 사용자 정보를 받지 못했습니다.\"),\n // 이메일이 없는 사용자는 가입할 수 없습니다.\n UNAUTHORIZED_EMAIL_KAKAO(401, \"이메일이 없는 사용자는 가입할 수 없습니다.\");\n\n\n @Getter\n private int status;\n\n @Getter\n private String message;\n\n ExceptionCode(int code, String message) {\n this.status = code;\n this.message = message;\n }\n}"
},
{
"identifier": "JwtTokenizer",
"path": "server/src/main/java/com/codestates/server/global/security/auth/jwt/JwtTokenizer.java",
"snippet": "@Component\npublic class JwtTokenizer {\n\n @Getter\n @Value(\"${jwt.key}\")\n private String secretKey;\n\n @Value(\"${jwt.access-token-expiration-minutes}\")\n private int originMinutes;\n\n @Getter\n private int accessTokenExpirationMinutes;\n\n @PostConstruct\n public void init() {\n this.accessTokenExpirationMinutes = this.originMinutes * 6;\n }\n\n @Getter\n @Value(\"${jwt.refresh-token-expiration-minutes}\")\n private int refreshTokenExpirationMinutes;\n\n public String encodeBase64SecretKey(String secretKey) {\n return Encoders.BASE64.encode(secretKey.getBytes(StandardCharsets.UTF_8));\n }\n\n /**\n * AccessToken 생성 메서드\n *\n * @param claims\n * @param subject\n * @param expiration\n * @param base64EncodedSecretKey\n * @return\n */\n public String generateAccessToken(Map<String, Object> claims,\n String subject,\n Date expiration,\n String base64EncodedSecretKey) {\n\n Key key = getKeyFromBase64EncodedKey(base64EncodedSecretKey);\n\n return Jwts.builder()\n .setClaims(claims)\n .setSubject(subject)\n .setIssuedAt(Calendar.getInstance().getTime())\n .setExpiration(expiration)\n .signWith(key)\n .compact();\n }\n\n /**\n * RefreshToken 생성 메서드\n *\n * @param subject\n * @param expiration\n * @param base64EncodedSecretKey\n * @return\n */\n public String generateRefreshToken(String subject,\n Date expiration,\n String base64EncodedSecretKey) {\n\n Key key = getKeyFromBase64EncodedKey(base64EncodedSecretKey);\n\n return Jwts.builder()\n .setSubject(subject)\n .setIssuedAt(Calendar.getInstance().getTime())\n .setExpiration(expiration)\n .signWith(key)\n .compact();\n }\n\n /**\n * JWS에서 클래임 추출\n */\n public Jws<Claims> getClaims(String jws, String base64EncodedSecretKey) {\n Key key = getKeyFromBase64EncodedKey(base64EncodedSecretKey);\n\n Jws<Claims> claims = // JWT에 저장된 정보\n Jwts.parserBuilder() // JWT를 파싱하기 위한 파서(Decoder)를 생성하는 메서드 -> 디코딩시 사용되는 파서 생성\n .setSigningKey(key) // 서명 검증을 위해 사용되는 key를 설정 (JWT 생성 시 사용된 키와 일치하면 검증 성공)\n .build()\n .parseClaimsJws(jws); // 실제 문자열을 파싱하고 JWT의 서명 검증 -> 검증되는 클레임 정보 추출, Jws<Claims>에 저장\n\n return claims;\n }\n\n /**\n * JWS 서명 검증\n * 그냥 검증하는 용도로만 작성\n */\n public void verifySignature(String jws, String base64EncodedSecretKey) {\n Key key = getKeyFromBase64EncodedKey(base64EncodedSecretKey);\n\n Jwts.parserBuilder()\n .setSigningKey(key) // 서명 검증에 사용될 Key 설정\n .build()\n .parseClaimsJws(jws); // jws 파싱, 서명 검증 -> 일치하지 않으면 예외발생\n }\n\n /**\n * 토큰 만료 시간 계산 후 반환\n *\n * @param expriationMinutes\n * @return\n */\n\n public Date getTokenExpiration(int expriationMinutes) {\n Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone(\"GMT\"));\n calendar.add(Calendar.MINUTE, expriationMinutes); // 현재 시간에 토큰 만료 시간 더하기\n\n Date expiration = calendar.getTime(); // 캘린더 객체(expiration)를 Date 객체로 바꿔서 만료시간 얻기\n\n return expiration; // 만료시간 반환\n }\n\n\n /**\n * 인코딩 된 시크릿 키로부터 Key 객체 생성\n *\n * @param base64EncodedSecretKey\n * @return\n */\n private Key getKeyFromBase64EncodedKey(String base64EncodedSecretKey) {\n byte[] keyBytes = Decoders.BASE64.decode(base64EncodedSecretKey); // 인코딩 된 key를 디코딩\n Key key = Keys.hmacShaKeyFor(keyBytes); // 디코딩 된 키를 HMAC-SHA 키 생성\n\n return key; // 키 반환 -> 서명 검증\n }\n}"
},
{
"identifier": "CustomAuthorityUtils",
"path": "server/src/main/java/com/codestates/server/global/security/auth/utils/CustomAuthorityUtils.java",
"snippet": "@Component\npublic class CustomAuthorityUtils {\n\n // 관리자 권한 가질 수 있는 메일 주소\n // -> appication.yml 에서 환경변수로 주기\n @Value(\"${mail.address.admin}\")\n private String admin;\n\n // GrantedAuthority : 권한 관련 작업 수행 -> 권한 목록 생성, 객체 배열 전환 ..\n // 관리자 권한 및 사용자 권한 목록 설정\n private final List<GrantedAuthority> ADMIN_ROLES = AuthorityUtils.createAuthorityList(\"ROLE_ADMIN\", \"ROLE_USER\");\n private final List<GrantedAuthority> USER_ROLES = AuthorityUtils.createAuthorityList(\"ROLE_USER\");\n\n // 관리자 권한 및 사용자 권한 -> 문자형태로 정의\n private final List<String> ADMIN_ROLES_STRING = List.of(\"ADMIN\", \"USER\");\n private final List<String> USER_ROLES_STRING = List.of(\"USER\");\n\n /**\n * 사용자 이메일 기준으로 권한 정보 생성\n * 이메일이 관리자 이메일이랑 일치하면 관리자 권한 반환\n * 일치하지 않으면 일반 사용자 권한 반환\n * @param email\n * @return\n */\n public List<GrantedAuthority> createAuthorities(String email) {\n if(email.equals(admin)) {\n return ADMIN_ROLES;\n } return USER_ROLES;\n }\n\n /**\n * DB에 저장된 역할 정보로 권한 정보 생성\n * @param roles\n * @return\n */\n public List<GrantedAuthority> createAuthorities(List<String> roles) {\n List<GrantedAuthority> grantedAuthorities = roles.stream()\n .map(role -> new SimpleGrantedAuthority(\"ROLE_\" + role))\n .collect(Collectors.toList());\n return grantedAuthorities;\n }\n\n /**\n * DB에 저장할 역할 정보 생성\n * 사용자 이메일이 admin 이메일과 같으면 관리자 역할 반환,\n * 다르면 사용자 권한 반환\n * @param email\n * @return\n */\n// public List<String> createRoles(String email) {\n// if(email.equals(adminMailAddress)) {\n// return ADMIN_ROLES_STRING;\n// }\n// return USER_ROLES_STRING;\n// }\n public List<String> createRoles(String email) {\n List<String> roles = new ArrayList<>();\n\n // 이메일이 관리자 이메일과 일치하면 \"ADMIN\" 역할을 추가\n if (email.equals(admin)) {\n roles.add(\"ADMIN\");\n }\n\n // 모든 사용자에게 \"USER\" 역할을 추가\n roles.add(\"USER\");\n\n return roles;\n }\n\n\n}"
},
{
"identifier": "KakaoOAuthConfig",
"path": "server/src/main/java/com/codestates/server/global/security/oauth2/config/KakaoOAuthConfig.java",
"snippet": "@Setter\n@Getter\n@Configuration\n@ConfigurationProperties(prefix = \"spring.security.oauth2.client.registration.kakao\")\npublic class KakaoOAuthConfig {\n\n private String clientId;\n private String clientSecret;\n private String redirectUri;\n private String authorizationGrantType;\n private List<String> scope;\n\n}"
},
{
"identifier": "KakaoMemberInfoDto",
"path": "server/src/main/java/com/codestates/server/global/security/oauth2/dto/KakaoMemberInfoDto.java",
"snippet": "@Getter\n@Setter\n@Data\npublic class KakaoMemberInfoDto {\n\n private Long id;\n\n private String connected_at;\n\n private Properties properties;\n\n @JsonProperty(\"kakao_account\")\n private KakaoAccount kakao_account;\n\n @Data\n public static class Properties {\n private String nickname;\n private String profile_image;\n private String thumbnail_image;\n }\n\n @Data\n public static class KakaoAccount {\n private String email;\n private Boolean profile_nickname_needs_agreement;\n private Boolean profile_image_needs_aggreement;\n private profile profile;\n }\n\n @Data\n public static class profile {\n private String nickname;\n private String thumbnail_image_url;\n private String profile_imgae_url;\n private Boolean is_default_image;\n }\n}"
}
] | import com.codestates.server.domain.member.entity.Member;
import com.codestates.server.domain.member.repository.MemberRepository;
import com.codestates.server.global.exception.BusinessLogicException;
import com.codestates.server.global.exception.ExceptionCode;
import com.codestates.server.global.security.auth.jwt.JwtTokenizer;
import com.codestates.server.global.security.auth.utils.CustomAuthorityUtils;
import com.codestates.server.global.security.oauth2.config.KakaoOAuthConfig;
import com.codestates.server.global.security.oauth2.dto.KakaoMemberInfoDto;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.*;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.reactive.function.client.WebClient;
import java.util.*; | 3,420 | package com.codestates.server.global.security.oauth2.service;
@AllArgsConstructor
@Service
@Transactional
@Slf4j
public class KakaoOAuthService {
private final KakaoOAuthConfig kakaoOAuthConfig; | package com.codestates.server.global.security.oauth2.service;
@AllArgsConstructor
@Service
@Transactional
@Slf4j
public class KakaoOAuthService {
private final KakaoOAuthConfig kakaoOAuthConfig; | private final MemberRepository memberRepository; | 1 | 2023-10-23 09:41:00+00:00 | 4k |
metacosm/quarkus-power | runtime/src/main/java/io/quarkiverse/power/runtime/sensors/PowerSensorProducer.java | [
{
"identifier": "SensorMeasure",
"path": "runtime/src/main/java/io/quarkiverse/power/runtime/SensorMeasure.java",
"snippet": "public interface SensorMeasure {\n\n double total();\n\n SensorMetadata metadata();\n}"
},
{
"identifier": "IntelRAPLSensor",
"path": "runtime/src/main/java/io/quarkiverse/power/runtime/sensors/linux/rapl/IntelRAPLSensor.java",
"snippet": "public class IntelRAPLSensor implements PowerSensor<IntelRAPLMeasure> {\n private final RAPLFile[] raplFiles;\n private final SensorMetadata metadata;\n private final double[] lastMeasuredSensorValues;\n private long frequency;\n\n public IntelRAPLSensor() {\n // if we total system energy is not available, read package and DRAM if possible\n // todo: check Intel doc\n final var files = new TreeMap<String, RAPLFile>();\n if (!addFileIfReadable(\"/sys/class/powercap/intel-rapl/intel-rapl:1/energy_uj\", files)) {\n addFileIfReadable(\"/sys/class/powercap/intel-rapl/intel-rapl:0/energy_uj\", files);\n addFileIfReadable(\"/sys/class/powercap/intel-rapl/intel-rapl:0/intel-rapl:0:2/energy_uj\", files);\n }\n\n if (files.isEmpty()) {\n throw new RuntimeException(\"Failed to get RAPL energy readings, probably due to lack of read access \");\n }\n\n raplFiles = files.values().toArray(new RAPLFile[0]);\n final var metadata = new HashMap<String, Integer>(files.size());\n int fileNb = 0;\n for (String name : files.keySet()) {\n metadata.put(name, fileNb++);\n }\n this.metadata = new SensorMetadata() {\n @Override\n public int indexFor(String component) {\n final var index = metadata.get(component);\n if (index == null) {\n throw new IllegalArgumentException(\"Unknow component: \" + component);\n }\n return index;\n }\n\n @Override\n public int componentCardinality() {\n return metadata.size();\n }\n };\n lastMeasuredSensorValues = new double[raplFiles.length];\n }\n\n private boolean addFileIfReadable(String raplFileAsString, SortedMap<String, RAPLFile> files) {\n final var raplFile = Path.of(raplFileAsString);\n if (isReadable(raplFile)) {\n // get metric name\n final var nameFile = raplFile.resolveSibling(\"name\");\n if (!isReadable(nameFile)) {\n throw new IllegalStateException(\"No name associated with \" + raplFileAsString);\n }\n\n try {\n final var name = Files.readString(nameFile).trim();\n files.put(name, RAPLFile.createFrom(raplFile));\n } catch (IOException e) {\n e.printStackTrace();\n return false;\n }\n return true;\n }\n return false;\n }\n\n private static boolean isReadable(Path file) {\n return Files.exists(file) && Files.isReadable(file);\n }\n\n @Override\n public OngoingPowerMeasure start(long duration, long frequency) throws Exception {\n this.frequency = frequency;\n\n // perform an initial measure to prime the data\n final var ongoingMeasure = new OngoingPowerMeasure(metadata, duration, frequency);\n update(ongoingMeasure);\n return ongoingMeasure;\n }\n\n private double computeNewComponentValue(int componentIndex, long sensorValue, double cpuShare) {\n return (sensorValue - lastMeasuredSensorValues[componentIndex]) * cpuShare / frequency / 1000;\n }\n\n @Override\n public void update(OngoingPowerMeasure ongoingMeasure) {\n ongoingMeasure.startNewMeasure();\n double cpuShare = PowerMeasurer.instance().cpuShareOfJVMProcess();\n for (int i = 0; i < raplFiles.length; i++) {\n final var value = raplFiles[i].extractPowerMeasure();\n final var newComponentValue = computeNewComponentValue(i, value, cpuShare);\n ongoingMeasure.setComponent(i, newComponentValue);\n lastMeasuredSensorValues[i] = newComponentValue;\n }\n ongoingMeasure.stopMeasure();\n }\n\n @Override\n public IntelRAPLMeasure measureFor(double[] measureComponents) {\n return new IntelRAPLMeasure(metadata, measureComponents);\n }\n}"
},
{
"identifier": "MacOSPowermetricsSensor",
"path": "runtime/src/main/java/io/quarkiverse/power/runtime/sensors/macos/powermetrics/MacOSPowermetricsSensor.java",
"snippet": "public class MacOSPowermetricsSensor implements PowerSensor<AppleSiliconMeasure> {\n private Process powermetrics;\n private final static String pid = \" \" + ProcessHandle.current().pid() + \" \";\n private double accumulatedCPUShareDiff = 0.0;\n private final int cpu;\n private final int gpu;\n private final int ane;\n\n public MacOSPowermetricsSensor() {\n ane = AppleSiliconMeasure.METADATA.indexFor(AppleSiliconMeasure.ANE);\n cpu = AppleSiliconMeasure.METADATA.indexFor(AppleSiliconMeasure.CPU);\n gpu = AppleSiliconMeasure.METADATA.indexFor(AppleSiliconMeasure.GPU);\n }\n\n private static class ProcessRecord {\n final double cpu;\n final double gpu;\n\n public ProcessRecord(String line) {\n //Name ID CPU ms/s samp ms/s User% Deadlines (<2 ms, 2-5 ms) Wakeups (Intr, Pkg idle) GPU ms/s\n //iTerm2 1008 46.66 46.91 83.94 0.00 0.00 30.46 0.00 0.00\n final var processData = line.split(\"\\\\s+\");\n cpu = Double.parseDouble(processData[3]);\n gpu = Double.parseDouble(processData[9]);\n }\n }\n\n @Override\n public void update(OngoingPowerMeasure ongoingMeasure) {\n extractPowerMeasure(ongoingMeasure, powermetrics.getInputStream(), pid, false);\n }\n\n AppleSiliconMeasure extractPowerMeasure(InputStream powerMeasureInput, long pid) {\n // one measure only\n return extractPowerMeasure(new OngoingPowerMeasure(AppleSiliconMeasure.METADATA, 1, 1), powerMeasureInput,\n \" \" + pid + \" \",\n true);\n }\n\n AppleSiliconMeasure extractPowerMeasure(OngoingPowerMeasure ongoingMeasure, InputStream powerMeasureInput,\n String paddedPIDAsString, boolean returnCurrent) {\n try {\n // Should not be closed since it closes the process\n BufferedReader input = new BufferedReader(new InputStreamReader(powerMeasureInput));\n String line;\n double cpuShare = -1, gpuShare = -1;\n boolean totalDone = false;\n boolean cpuDone = false;\n // start measure\n ongoingMeasure.startNewMeasure();\n while ((line = input.readLine()) != null) {\n if (line.isEmpty() || line.startsWith(\"*\")) {\n continue;\n }\n\n // first, look for process line detailing share\n if (cpuShare < 0) {\n if (line.contains(paddedPIDAsString)) {\n final var procInfo = new ProcessRecord(line);\n cpuShare = procInfo.cpu;\n gpuShare = procInfo.gpu;\n }\n continue;\n }\n\n if (!totalDone) {\n // then skip all lines until we get the totals\n if (line.startsWith(\"ALL_TASKS\")) {\n final var totals = new ProcessRecord(line);\n // compute ratio\n cpuShare = cpuShare / totals.cpu;\n gpuShare = totals.gpu > 0 ? gpuShare / totals.gpu : 0;\n totalDone = true;\n }\n continue;\n }\n\n if (!cpuDone) {\n // look for line that contains CPU power measure\n if (line.startsWith(\"CPU Power\")) {\n final var jmxCpuShare = PowerMeasurer.instance().cpuShareOfJVMProcess();\n ongoingMeasure.setComponent(cpu, extractAttributedMeasure(line, cpuShare));\n accumulatedCPUShareDiff += (cpuShare - jmxCpuShare);\n cpuDone = true;\n }\n continue;\n }\n\n if (line.startsWith(\"GPU Power\")) {\n ongoingMeasure.setComponent(gpu, extractAttributedMeasure(line, gpuShare));\n continue;\n }\n\n if (line.startsWith(\"ANE Power\")) {\n ongoingMeasure.setComponent(ane, extractAttributedMeasure(line, 1));\n break;\n }\n }\n\n final var measure = ongoingMeasure.stopMeasure();\n return returnCurrent ? new AppleSiliconMeasure(measure) : null;\n } catch (Exception exception) {\n throw new RuntimeException(exception);\n }\n }\n\n private static double extractAttributedMeasure(String line, double attributionRatio) {\n final var powerValue = line.split(\":\")[1];\n final var powerInMilliwatts = powerValue.split(\"m\")[0];\n return Double.parseDouble(powerInMilliwatts) * attributionRatio;\n }\n\n @Override\n public OngoingPowerMeasure start(long duration, long frequency) throws Exception {\n // it takes some time for the external process in addition to the sampling time so adjust the sampling frequency to account for this so that at most one measure occurs during the sampling time window\n final var freq = Long.toString(frequency - 50);\n powermetrics = Runtime.getRuntime()\n .exec(\"sudo powermetrics --samplers cpu_power,tasks --show-process-samp-norm --show-process-gpu -i \" + freq);\n accumulatedCPUShareDiff = 0.0;\n return new OngoingPowerMeasure(AppleSiliconMeasure.METADATA, duration, frequency);\n }\n\n @Override\n public void stop() {\n powermetrics.destroy();\n }\n\n @Override\n public Optional<String> additionalInfo(PowerMeasure measure) {\n return Optional.of(\"Powermetrics vs JMX CPU share accumulated difference: \" + accumulatedCPUShareDiff);\n }\n\n @Override\n public AppleSiliconMeasure measureFor(double[] measureComponents) {\n return new AppleSiliconMeasure(measureComponents);\n }\n}"
}
] | import jakarta.enterprise.inject.Produces;
import jakarta.inject.Singleton;
import io.quarkiverse.power.runtime.SensorMeasure;
import io.quarkiverse.power.runtime.sensors.linux.rapl.IntelRAPLSensor;
import io.quarkiverse.power.runtime.sensors.macos.powermetrics.MacOSPowermetricsSensor; | 2,492 | package io.quarkiverse.power.runtime.sensors;
@Singleton
public class PowerSensorProducer {
@Produces
public PowerSensor<?> sensor() {
return determinePowerSensor();
}
| package io.quarkiverse.power.runtime.sensors;
@Singleton
public class PowerSensorProducer {
@Produces
public PowerSensor<?> sensor() {
return determinePowerSensor();
}
| public static PowerSensor<? extends SensorMeasure> determinePowerSensor() { | 0 | 2023-10-23 16:44:57+00:00 | 4k |
LeGhast/Miniaturise | src/main/java/de/leghast/miniaturise/command/DeleteCommand.java | [
{
"identifier": "Miniaturise",
"path": "src/main/java/de/leghast/miniaturise/Miniaturise.java",
"snippet": "public final class Miniaturise extends JavaPlugin {\n\n private MiniatureManager miniatureManager;\n private RegionManager regionManager;\n private SettingsManager settingsManager;\n\n @Override\n public void onEnable() {\n ConfigManager.setupConfig(this);\n initialiseManagers();\n registerListeners();\n setCommands();\n setTabCompleters();\n }\n\n @Override\n public void onDisable() {\n saveConfig();\n }\n\n private void initialiseManagers(){\n miniatureManager = new MiniatureManager(this);\n regionManager = new RegionManager(this);\n settingsManager = new SettingsManager(this);\n }\n\n private void registerListeners(){\n Bukkit.getPluginManager().registerEvents(new PlayerInteractListener(this), this);\n Bukkit.getPluginManager().registerEvents(new PlayerQuitListener(this), this);\n Bukkit.getPluginManager().registerEvents(new InventoryClickListener(this), this);\n }\n\n private void setCommands(){\n getCommand(\"select\").setExecutor(new SelectCommand(this));\n getCommand(\"scale\").setExecutor(new ScaleCommand(this));\n getCommand(\"cut\").setExecutor(new CutCommand(this));\n getCommand(\"tools\").setExecutor(new ToolsCommand(this));\n getCommand(\"paste\").setExecutor(new PasteCommand(this));\n getCommand(\"tool\").setExecutor(new ToolCommand(this));\n getCommand(\"delete\").setExecutor(new DeleteCommand(this));\n getCommand(\"copy\").setExecutor(new CopyCommand(this));\n getCommand(\"position\").setExecutor(new PositionCommand(this));\n getCommand(\"clear\").setExecutor(new ClearCommand(this));\n getCommand(\"adjust\").setExecutor(new AdjustCommand(this));\n getCommand(\"rotate\").setExecutor(new RotateCommand(this));\n }\n\n public void setTabCompleters(){\n getCommand(\"position\").setTabCompleter(new PositionTabCompleter());\n getCommand(\"scale\").setTabCompleter(new ScaleTabCompleter());\n getCommand(\"tool\").setTabCompleter(new ToolTabCompleter());\n getCommand(\"rotate\").setTabCompleter(new RotateTabCompleter());\n }\n\n /**\n * @return The MiniatureManager instance\n */\n public MiniatureManager getMiniatureManager(){\n return miniatureManager;\n }\n\n /**\n * @return The RegionManager instance\n */\n public RegionManager getRegionManager(){\n return regionManager;\n }\n\n public SettingsManager getSettingsManager(){\n return settingsManager;\n }\n\n}"
},
{
"identifier": "PlacedMiniature",
"path": "src/main/java/de/leghast/miniaturise/instance/miniature/PlacedMiniature.java",
"snippet": "public class PlacedMiniature {\n\n private List<BlockDisplay> blockDisplays;\n private double blockSize;\n\n public PlacedMiniature(List<MiniatureBlock> blocks, Location origin) throws InvalidParameterException {\n if(!blocks.isEmpty()){\n blockDisplays = new ArrayList<>();\n blockSize = blocks.get(0).getSize();\n\n for(MiniatureBlock mb : blocks) {\n BlockDisplay bd;\n bd = (BlockDisplay) origin.getWorld().spawnEntity(new Location(\n origin.getWorld(),\n mb.getX() + ceil(origin.getX()),\n mb.getY() + ceil(origin.getY()),\n mb.getZ() + ceil(origin.getZ())),\n EntityType.BLOCK_DISPLAY);\n bd.setBlock(mb.getBlockData());\n Transformation transformation = bd.getTransformation();\n transformation.getScale().set(mb.getSize());\n bd.setTransformation(transformation);\n blockDisplays.add(bd);\n }\n }else{\n throw new InvalidParameterException(\"The miniature block list is empty\");\n }\n }\n\n public PlacedMiniature(List<BlockDisplay> blockDisplays) throws InvalidParameterException{\n this.blockDisplays = blockDisplays;\n if(!blockDisplays.isEmpty()){\n blockSize = blockDisplays.get(0).getTransformation().getScale().x;\n }else{\n throw new InvalidParameterException(\"The block display list is empty\");\n }\n }\n\n public void remove(){\n for(BlockDisplay bd : blockDisplays){\n bd.remove();\n }\n }\n\n public void scaleUp(double scale){\n Bukkit.getScheduler().runTaskAsynchronously(getMain(), () -> {\n Location origin = blockDisplays.get(0).getLocation();\n Miniature miniature = new Miniature(this, origin, blockSize);\n miniature.scaleUp(scale);\n rearrange(origin, miniature);\n blockSize *= scale;\n });\n }\n\n public void scaleDown(double scale){\n Bukkit.getScheduler().runTaskAsynchronously(getMain(), () -> {\n Location origin = blockDisplays.get(0).getLocation();\n Miniature miniature = new Miniature(this, origin, blockSize);\n miniature.scaleDown(scale);\n rearrange(origin, miniature);\n blockSize /= scale;\n });\n }\n\n private void rearrange(Location origin, Miniature miniature) {\n Bukkit.getScheduler().runTaskAsynchronously(getMain(), () -> {\n for(int i = 0; i < getBlockCount(); i++){\n BlockDisplay bd = blockDisplays.get(i);\n MiniatureBlock mb = miniature.getBlocks().get(i);\n Bukkit.getScheduler().scheduleSyncDelayedTask(getMain(), () -> {\n bd.teleport(new Location( bd.getWorld(),\n mb.getX() + origin.getX(),\n mb.getY() + origin.getY(),\n mb.getZ() + origin.getZ()));\n Transformation transformation = bd.getTransformation();\n transformation.getScale().set(mb.getSize());\n bd.setTransformation(transformation);\n });\n }\n });\n }\n\n public void rotate(Axis axis, float angle){\n Location origin = blockDisplays.get(0).getLocation();\n float finalAngle = (float) Math.toRadians(angle);\n Bukkit.getScheduler().runTaskAsynchronously(getMain(), () -> {\n\n for(BlockDisplay bd : blockDisplays){\n\n Transformation transformation = bd.getTransformation();\n\n switch (axis){\n case X -> transformation.getLeftRotation().rotateX(finalAngle);\n case Y -> transformation.getLeftRotation().rotateY(finalAngle);\n case Z -> transformation.getLeftRotation().rotateZ(finalAngle);\n }\n\n Vector3f newPositionVector = getRotatedPosition(\n bd.getLocation().toVector().toVector3f(),\n origin.toVector().toVector3f(),\n axis,\n finalAngle\n );\n\n Location newLocation = new Location(\n bd.getLocation().getWorld(),\n newPositionVector.x,\n newPositionVector.y,\n newPositionVector.z\n );\n Bukkit.getScheduler().scheduleSyncDelayedTask(getMain(), () -> {\n bd.setTransformation(transformation);\n bd.teleport(newLocation);\n });\n\n }\n });\n\n\n\n }\n\n private Vector3f getRotatedPosition(Vector3f pointToRotate, Vector3f origin, Axis axis, float angle){\n pointToRotate.sub(origin);\n Matrix3f rotationMatrix = new Matrix3f();\n\n switch (axis){\n case X -> rotationMatrix.rotationX(angle);\n case Y -> rotationMatrix.rotationY(angle);\n case Z -> rotationMatrix.rotationZ(angle);\n }\n\n rotationMatrix.transform(pointToRotate);\n\n pointToRotate.add(origin);\n\n return pointToRotate;\n }\n\n public void move(Vector addition){\n Bukkit.getScheduler().scheduleSyncDelayedTask(getMain(), () -> {\n for(BlockDisplay bd : blockDisplays){\n bd.teleport(bd.getLocation().add(addition));\n }\n });\n }\n\n public void move(Axis axis, double addition){\n switch (axis){\n case X -> move(new Vector(addition, 0, 0));\n case Y -> move(new Vector(0, addition, 0));\n case Z -> move(new Vector(0, 0, addition));\n }\n }\n\n public double getBlockSize() {\n return blockSize;\n }\n\n public int getBlockCount(){\n return blockDisplays.size();\n }\n\n public List<BlockDisplay> getBlockDisplays(){\n return blockDisplays;\n }\n\n private Miniaturise getMain(){\n return (Miniaturise) Bukkit.getPluginManager().getPlugin(\"Miniaturise\");\n }\n\n}"
},
{
"identifier": "Util",
"path": "src/main/java/de/leghast/miniaturise/util/Util.java",
"snippet": "public class Util {\n\n public static final String PREFIX = \"§7[§eMiniaturise§7] \";\n\n public static String getDimensionName(String string){\n switch (string){\n case \"NORMAL\" -> {\n return \"minecraft:overworld\";\n }\n case \"NETHER\" -> {\n return \"minecraft:the_nether\";\n }\n case \"THE_END\" -> {\n return \"minecraft:the_end\";\n }\n default -> {\n return \"Invalid dimension\";\n }\n }\n }\n\n public static List<BlockDisplay> getBlockDisplaysFromRegion(Player player, Region region){\n List<BlockDisplay> blockDisplays = new ArrayList<>();\n for(Chunk chunk : player.getWorld().getLoadedChunks()){\n for(Entity entity : chunk.getEntities()){\n if(entity instanceof BlockDisplay && region.contains(entity.getLocation())){\n blockDisplays.add((BlockDisplay) entity);\n }\n }\n }\n return blockDisplays;\n }\n\n public static void setCustomNumberInput(Miniaturise main, Player player, Page page){\n ItemStack output = new ItemStack(Material.PAPER);\n ItemMeta meta = output.getItemMeta();\n meta.setDisplayName(\"§eSet custom factor\");\n output.setItemMeta(meta);\n PageUtil.addGlint(output);\n\n new AnvilGUI.Builder()\n .title(\"§eEnter custom factor\")\n .text(\"1\")\n .onClick((slot, stateSnapshot) -> {\n if(slot == AnvilGUI.Slot.OUTPUT){\n AdjusterSettings settings = main.getSettingsManager().getAdjusterSettings(player.getUniqueId());\n switch (page){\n case POSITION -> settings.getPositionSettings().setFactor(stateSnapshot.getText());\n case SIZE -> settings.getSizeSettings().setFactor(stateSnapshot.getText());\n case ROTATION -> settings.getRotationSettings().setFactor(stateSnapshot.getText());\n }\n return Arrays.asList(AnvilGUI.ResponseAction.close());\n }\n return Arrays.asList(AnvilGUI.ResponseAction.updateTitle(\"§eEnter custom factor\", false));\n })\n .preventClose()\n .itemOutput(output)\n .plugin(main)\n .open(player);\n\n }\n\n}"
}
] | import de.leghast.miniaturise.Miniaturise;
import de.leghast.miniaturise.instance.miniature.PlacedMiniature;
import de.leghast.miniaturise.util.Util;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull; | 2,748 | package de.leghast.miniaturise.command;
public class DeleteCommand implements CommandExecutor {
private Miniaturise main;
public DeleteCommand(Miniaturise main){
this.main = main;
}
@Override
public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String s, @NotNull String[] args) {
if(sender instanceof Player player){
if(player.hasPermission("miniaturise.use")) {
if (main.getMiniatureManager().hasMiniature(player.getUniqueId())) {
PlacedMiniature placedMiniature;
placedMiniature = main.getMiniatureManager().getPlacedMiniature(player.getUniqueId());
int deletedEntities = 0;
if (placedMiniature != null) {
deletedEntities = placedMiniature.getBlockCount();
placedMiniature.remove();
main.getMiniatureManager().getPlacedMiniatures().replace(player.getUniqueId(), null); | package de.leghast.miniaturise.command;
public class DeleteCommand implements CommandExecutor {
private Miniaturise main;
public DeleteCommand(Miniaturise main){
this.main = main;
}
@Override
public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String s, @NotNull String[] args) {
if(sender instanceof Player player){
if(player.hasPermission("miniaturise.use")) {
if (main.getMiniatureManager().hasMiniature(player.getUniqueId())) {
PlacedMiniature placedMiniature;
placedMiniature = main.getMiniatureManager().getPlacedMiniature(player.getUniqueId());
int deletedEntities = 0;
if (placedMiniature != null) {
deletedEntities = placedMiniature.getBlockCount();
placedMiniature.remove();
main.getMiniatureManager().getPlacedMiniatures().replace(player.getUniqueId(), null); | player.sendMessage(Util.PREFIX + "§aThe placed miniature was deleted §e(" + deletedEntities + | 2 | 2023-10-15 09:08:33+00:00 | 4k |
HenryAWE/tcreate | src/main/java/henryawe/tcreate/create/fans/processing/SkySlimeType.java | [
{
"identifier": "TCreate",
"path": "src/main/java/henryawe/tcreate/TCreate.java",
"snippet": "@Mod(\"tcreate\")\npublic final class TCreate {\n /**\n * The mod id.\n */\n public static final String MODID = \"tcreate\";\n\n /**\n * Logger of this class.\n */\n private static final Logger LOGGER = LogUtils.getLogger();\n\n public TCreate() {\n final IEventBus bus = FMLJavaModLoadingContext.get().getModEventBus();\n\n LOGGER.info(\"Registering Tinkers' Create\");\n TCreateItems.register(bus);\n TCreateFluids.register(bus);\n TCreateRecipeTypes.clinit(bus);\n ProcessingTypes.clinit();\n TCreateEffects.clinit(bus);\n TCreatePotatoCannonProjectileTypes.clinit();\n\n MinecraftForge.EVENT_BUS.register(this);\n LOGGER.info(\"Finish Register TCreate.\");\n }\n\n public static boolean getBoolean(@NotNull LivingEntity le, String tag) {\n return le.getPersistentData().getBoolean(tag);\n }\n\n public static void putBoolean(@NotNull LivingEntity le, String tag) {\n le.getPersistentData().getBoolean(tag);\n }\n}"
},
{
"identifier": "TCreateTasks",
"path": "src/main/java/henryawe/tcreate/TCreateTasks.java",
"snippet": "public final class TCreateTasks {\n private TCreateTasks () {\n }\n\n public static <T extends Mob> void mobConvertTask (\n int conversionTime,\n @NotNull Mob entity,\n @NotNull EntityType<T> targetType,\n boolean copyData,\n Consumer<@NotNull T> afterConversion\n ) {\n if (entity.getPersistentData().getBoolean(\"TCreateConvertTask\"))\n return;\n entity.getPersistentData().putBoolean(\"TCreateConvertTask\", true);\n final var worldIn = entity.level;\n if (worldIn.isClientSide)\n return;\n THREAD_POOL.schedule(new SyncTickTask(worldIn.getGameTime(), conversionTime, worldIn::getGameTime) {\n @Override\n void whenSync () {\n }\n\n @Override\n void whenEnd () {\n final var target = entity.convertTo(targetType, copyData);\n if (target != null)\n afterConversion.accept(target);\n }\n }, 0, TimeUnit.MILLISECONDS);\n }\n\n private static abstract class SyncTickTask implements Runnable {\n private final long beginTick;\n private final long durationTicks;\n private long passedTicks = 0;\n private final Supplier<Long> tickTimeProvider;\n\n protected SyncTickTask (long beginTick, long durationTicks, Supplier<Long> tickTimeProvider) {\n this.beginTick = beginTick;\n this.durationTicks = durationTicks;\n this.tickTimeProvider = tickTimeProvider;\n }\n\n abstract void whenSync ();\n\n abstract void whenEnd ();\n\n @Override\n public void run () {\n while (true) {\n final long currentTick = tickTimeProvider.get();\n final long runTicks = currentTick - beginTick;\n if (runTicks == durationTicks) {\n whenEnd();\n break;\n }\n if (passedTicks != runTicks) {\n passedTicks = runTicks;\n whenSync();\n }\n }\n\n LOGGER.debug(\"Finish task, duration ticks: {}, passed ticks: {}\", durationTicks, passedTicks);\n }\n\n private static final Logger LOGGER = LogUtils.getLogger();\n }\n\n private static final ScheduledThreadPoolExecutor THREAD_POOL = new ScheduledThreadPoolExecutor(\n Runtime.getRuntime().availableProcessors(),\n DefaultThreadFactory.INSTANCE\n );\n\n private static final class DefaultThreadFactory implements ThreadFactory {\n private DefaultThreadFactory () {\n }\n\n @Override\n @NotNull\n public Thread newThread (@NotNull Runnable r) {\n return new Thread(\n Thread.currentThread().getThreadGroup(),\n r,\n \"TCreateTasks-[\" + CREATED_THREAD_COUNT.getAndIncrement() + ']'\n );\n }\n\n private static final AtomicInteger CREATED_THREAD_COUNT = new AtomicInteger(0);\n\n static final DefaultThreadFactory INSTANCE = new DefaultThreadFactory();\n }\n}"
},
{
"identifier": "PatternMatcher",
"path": "src/main/java/henryawe/tcreate/pattern/PatternMatcher.java",
"snippet": "public interface PatternMatcher<MatchType> {\n @NotNull\n Stream<? extends TCreatePattern<MatchType>> patterns ();\n\n @NotNull\n PatternMatcher<MatchType> register (@NotNull TCreatePattern<MatchType> pattern);\n\n default boolean matches (MatchType any) {\n return patterns().anyMatch((it) -> it.matches(any));\n }\n}"
},
{
"identifier": "TCreatePattern",
"path": "src/main/java/henryawe/tcreate/pattern/TCreatePattern.java",
"snippet": "@FunctionalInterface\npublic interface TCreatePattern<MatchType> {\n boolean matches(MatchType o);\n}"
},
{
"identifier": "TCreateRecipeTypes",
"path": "src/main/java/henryawe/tcreate/register/TCreateRecipeTypes.java",
"snippet": "public enum TCreateRecipeTypes implements IRecipeTypeInfo {\n SKYSLIME_PROCESSING(SkySlimeRecipe::new);\n\n TCreateRecipeTypes (Supplier<RecipeSerializer<?>> serializerObject) {\n String name = name().toLowerCase(Locale.ROOT);\n id = asResource(name);\n this.serializerObject = Registers.SERIALIZER_REGISTER.register(name, serializerObject);\n typeObject = Registers.TYPE_REGISTER.register(name, () -> new RecipeType<>() {\n @Override\n public String toString () {\n return id.toString();\n }\n });\n this.type = typeObject;\n }\n\n TCreateRecipeTypes (ProcessingRecipeBuilder.ProcessingRecipeFactory<?> processingFactory) {\n this(() -> new ProcessingRecipeSerializer<>(processingFactory));\n }\n\n private static final Logger LOGGER = LogUtils.getLogger();\n\n private final ResourceLocation id;\n private final RegistryObject<RecipeSerializer<?>> serializerObject;\n @Nullable\n private final RegistryObject<RecipeType<?>> typeObject;\n private final Supplier<RecipeType<?>> type;\n\n @Override\n public ResourceLocation getId () {\n return id;\n }\n\n @Override\n @SuppressWarnings(\"unchecked\")\n public <T extends RecipeSerializer<?>> T getSerializer () {\n return (T) serializerObject.get();\n }\n\n @Override\n @SuppressWarnings(\"unchecked\")\n public <T extends RecipeType<?>> T getType () {\n return (T) type.get();\n }\n\n public <C extends Container, T extends Recipe<C>> Optional<T> filiter (C inv, Level worldIn) {\n return worldIn.getRecipeManager()\n .getRecipeFor(getType(), inv, worldIn);\n }\n\n public static void clinit (IEventBus bus) {\n Registers.SERIALIZER_REGISTER.register(bus);\n Registers.TYPE_REGISTER.register(bus);\n // debug\n LOGGER.debug(\"Test type registration state: {}\", SKYSLIME_PROCESSING.typeObject);\n }\n\n static class Registers {\n private static final DeferredRegister<RecipeSerializer<?>> SERIALIZER_REGISTER\n = DeferredRegister.create(ForgeRegistries.RECIPE_SERIALIZERS, MODID);\n\n private static final DeferredRegister<RecipeType<?>> TYPE_REGISTER\n = DeferredRegister.create(Registry.RECIPE_TYPE_REGISTRY, MODID);\n }\n}"
},
{
"identifier": "SkySlimeRecipe",
"path": "src/main/java/henryawe/tcreate/create/fans/recipes/SkySlimeRecipe.java",
"snippet": "public class SkySlimeRecipe extends ProcessingRecipe<SkySlimeRecipe.Wrapper> {\n\n public SkySlimeRecipe (ProcessingRecipeBuilder.ProcessingRecipeParams params) {\n super(TCreateRecipeTypes.SKYSLIME_PROCESSING, params);\n }\n\n @Override\n protected int getMaxInputCount () {\n return 1;\n }\n\n @Override\n protected int getMaxOutputCount () {\n return 9;\n }\n\n @Override\n public boolean matches (@NotNull Wrapper inv, @NotNull Level worldIn) {\n if (inv.isEmpty()) {\n return false;\n }\n return ingredients.get(0)\n .test(inv.getItem(0));\n }\n\n public static class Wrapper extends RecipeWrapper {\n public Wrapper() {\n super(new ItemStackHandler(1));\n }\n }\n}"
}
] | import com.simibubi.create.content.kinetics.fan.processing.FanProcessingType;
import com.simibubi.create.foundation.recipe.RecipeApplier;
import henryawe.tcreate.TCreate;
import henryawe.tcreate.TCreateTasks;
import henryawe.tcreate.pattern.PatternMatcher;
import henryawe.tcreate.pattern.TCreatePattern;
import henryawe.tcreate.register.TCreateRecipeTypes;
import henryawe.tcreate.create.fans.recipes.SkySlimeRecipe;
import net.minecraft.core.BlockPos;
import net.minecraft.core.particles.ParticleTypes;
import net.minecraft.world.effect.MobEffectInstance;
import net.minecraft.world.effect.MobEffects;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.monster.Skeleton;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.material.FluidState;
import net.minecraft.world.phys.Vec3;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayDeque;
import java.util.Collection;
import java.util.List;
import java.util.Random;
import java.util.stream.Stream;
import static net.minecraft.world.entity.EntityType.STRAY;
import static slimeknights.tconstruct.fluids.TinkerFluids.skySlime; | 2,276 | package henryawe.tcreate.create.fans.processing;
public class SkySlimeType implements FanProcessingType, PatternMatcher<FluidState> {
static final SkySlimeRecipe.Wrapper WRAPPER = new SkySlimeRecipe.Wrapper();
public static final String CONVERT_FROM_SKYSLIME_TAG = "TCreate_from_skyslime_type";
| package henryawe.tcreate.create.fans.processing;
public class SkySlimeType implements FanProcessingType, PatternMatcher<FluidState> {
static final SkySlimeRecipe.Wrapper WRAPPER = new SkySlimeRecipe.Wrapper();
public static final String CONVERT_FROM_SKYSLIME_TAG = "TCreate_from_skyslime_type";
| private final Collection<TCreatePattern<FluidState>> patterns = new ArrayDeque<>(); | 3 | 2023-10-16 14:42:49+00:00 | 4k |
RacoonDog/Simple-Chat-Emojis | src/main/java/io/github/racoondog/emoji/simplechatemojis/mixin/DrawContextMixin.java | [
{
"identifier": "Emoji",
"path": "src/main/java/io/github/racoondog/emoji/simplechatemojis/Emoji.java",
"snippet": "public class Emoji {\n private static final Emoji MISSING = new Emoji(\n MissingSprite.getMissingSpriteId(),\n MissingSprite.getMissingSpriteId().getPath(),\n MissingSprite.getMissingSpriteTexture().getImage().getHeight(),\n MissingSprite.getMissingSpriteTexture().getImage().getWidth()\n );\n\n public final Identifier id;\n public final String name;\n private final int texWidth;\n private final int texHeight;\n\n private Emoji(Identifier identifier, String name, int texWidth, int texHeight) {\n this.id = identifier;\n this.name = name;\n this.texHeight = texHeight;\n this.texWidth = texWidth;\n }\n\n public static Emoji fromResource(Identifier identifier, Resource texture) {\n try (var inputStream = texture.getInputStream()) {\n ByteBuffer buffer = TextureUtil.readResource(inputStream).rewind();\n int[] x = new int[1];\n int[] y = new int[1];\n STBImage.stbi_info_from_memory(buffer, x, y, new int[1]);\n return new Emoji(identifier, identifier.getPath(), x[0], y[0]);\n } catch (IOException e) {\n e.printStackTrace();\n return MISSING;\n }\n }\n\n public void render(DrawContext context, int x, int y, int fontHeight, int color) {\n int ratio = Math.max(texHeight, texWidth) / fontHeight;\n\n int height = texHeight / ratio;\n int width = texWidth / ratio;\n\n drawTexture(context, id, x, y - 1, width, height, 0, 0, texWidth, texHeight, texWidth, texHeight, color);\n }\n\n public void drawTexture(DrawContext context, Identifier texture, int x, int y, int width, int height, float u, float v, int regionWidth, int regionHeight, int textureWidth, int textureHeight, int color) {\n RenderSystem.enableBlend();\n int alpha = (color >> 24) & 0xFF;\n if (alpha == 0) alpha = 0xFF; // Chat box has alpha set to 0\n RenderSystem.setShaderColor(1, 1, 1, alpha / 255f);\n\n context.drawTexture(texture, x, y, width, height, u, v, regionWidth, regionHeight, textureWidth, textureHeight);\n\n RenderSystem.setShaderColor(1, 1, 1, 1);\n RenderSystem.disableBlend();\n }\n}"
},
{
"identifier": "SimpleChatEmojis",
"path": "src/main/java/io/github/racoondog/emoji/simplechatemojis/SimpleChatEmojis.java",
"snippet": "@Environment(EnvType.CLIENT)\npublic class SimpleChatEmojis implements ClientModInitializer {\n public static final String MOD_ID = \"simple-chat-emojis\";\n public static final Pattern EMOJI_REGEX = Pattern.compile(\"(:[a-z0-9._-]+:)\");\n public static final Map<String, Emoji> REGISTRY = new HashMap<>();\n public static final Logger LOG = LogUtils.getLogger();\n\n @Override\n public void onInitializeClient() {\n FabricLoader.getInstance().getModContainer(MOD_ID).ifPresent(container -> {\n ResourceManagerHelper.registerBuiltinResourcePack(new Identifier(MOD_ID, \"developers-guild-emoji-pack\"), container, Text.literal(\"Developer's Guild Emoji Pack\"), ResourcePackActivationType.NORMAL);\n ResourceManagerHelper.registerBuiltinResourcePack(new Identifier(MOD_ID, \"twemoji-emoji-pack\"), container, Text.literal(\"Twemoji Emoji Pack\"), ResourcePackActivationType.DEFAULT_ENABLED);\n });\n\n ResourceManagerHelper.get(ResourceType.CLIENT_RESOURCES).registerReloadListener(new SimpleSynchronousResourceReloadListener() {\n @Override\n public Identifier getFabricId() {\n return new Identifier(MOD_ID, \"chat_emojis_resources\");\n }\n\n @Override\n public void reload(ResourceManager manager) {\n REGISTRY.clear();\n\n for (var resourcePair : manager.findResources(\"textures/simple-chat-emojis\", path -> path.getPath().endsWith(\".png\")).entrySet()) {\n String emojiName = Utils.nameFromIdentifier(resourcePair.getKey());\n\n register(emojiName, Emoji.fromResource(resourcePair.getKey(), resourcePair.getValue()));\n }\n }\n });\n }\n\n public static void register(String emojiName, Emoji emoji) {\n Emoji old = REGISTRY.put(emojiName, emoji);\n if (old != null) {\n LOG.warn(\"Duplicate emojis registered under the same name! '%s' & '%s'\".formatted(old.id, emoji.id));\n }\n }\n}"
},
{
"identifier": "Utils",
"path": "src/main/java/io/github/racoondog/emoji/simplechatemojis/Utils.java",
"snippet": "public class Utils {\n public static List<Pair<String, Style>> dissect(OrderedText orderedText) {\n List<Pair<String, Style>> list = new ArrayList<>();\n\n orderedText.accept((index, style, codePoint) -> {\n if (list.isEmpty() || !list.get(list.size() - 1).right().equals(style)) {\n list.add(new ObjectObjectMutablePair<>(Character.toString(codePoint), style));\n } else {\n Pair<String, Style> last = list.get(list.size() - 1);\n last.left(last.left() + Character.toString(codePoint));\n }\n\n return true;\n });\n\n return list;\n }\n\n public static OrderedText toOrderedText(String text, Style style) {\n return Text.literal(text).setStyle(style).asOrderedText();\n }\n\n public static String nameFromIdentifier(Identifier id) {\n StringBuilder sb = new StringBuilder(\":\");\n int slashIdx = id.getPath().lastIndexOf('/');\n int periodIdx = id.getPath().indexOf('.', slashIdx);\n sb.append(id.getPath(), slashIdx == -1 ? 0 : slashIdx + 1, periodIdx == -1 ? id.getPath().length() - 4 : periodIdx);\n sb.append(':');\n return sb.toString();\n }\n}"
}
] | import io.github.racoondog.emoji.simplechatemojis.Emoji;
import io.github.racoondog.emoji.simplechatemojis.SimpleChatEmojis;
import io.github.racoondog.emoji.simplechatemojis.Utils;
import it.unimi.dsi.fastutil.Pair;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.minecraft.client.font.TextRenderer;
import net.minecraft.client.gui.DrawContext;
import net.minecraft.text.OrderedText;
import net.minecraft.text.Style;
import org.jetbrains.annotations.Nullable;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.Unique;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
import java.util.List;
import java.util.regex.Matcher; | 1,740 | package io.github.racoondog.emoji.simplechatemojis.mixin;
@Environment(EnvType.CLIENT)
@Mixin(DrawContext.class)
public abstract class DrawContextMixin {
@Shadow public abstract int drawText(TextRenderer textRenderer, OrderedText text, int x, int y, int color, boolean shadow);
@Inject(method = "drawTextWithShadow(Lnet/minecraft/client/font/TextRenderer;Lnet/minecraft/text/OrderedText;III)I", at = @At("HEAD"), cancellable = true)
private void injectDrawWithShadow(TextRenderer renderer, OrderedText text, int x, int y, int color, CallbackInfoReturnable<Integer> cir) { | package io.github.racoondog.emoji.simplechatemojis.mixin;
@Environment(EnvType.CLIENT)
@Mixin(DrawContext.class)
public abstract class DrawContextMixin {
@Shadow public abstract int drawText(TextRenderer textRenderer, OrderedText text, int x, int y, int color, boolean shadow);
@Inject(method = "drawTextWithShadow(Lnet/minecraft/client/font/TextRenderer;Lnet/minecraft/text/OrderedText;III)I", at = @At("HEAD"), cancellable = true)
private void injectDrawWithShadow(TextRenderer renderer, OrderedText text, int x, int y, int color, CallbackInfoReturnable<Integer> cir) { | List<Pair<String, Style>> dissected = Utils.dissect(text); | 2 | 2023-10-17 03:03:32+00:00 | 4k |
zendo-games/zenlib | src/main/java/zendo/games/zenlib/screens/transitions/Transition.java | [
{
"identifier": "ZenConfig",
"path": "src/main/java/zendo/games/zenlib/ZenConfig.java",
"snippet": "public class ZenConfig {\n\n public final Window window;\n public final UI ui;\n\n public ZenConfig() {\n this(\"zenlib\", 1280, 720, null);\n }\n\n public ZenConfig(String title, int width, int height) {\n this(title, width, height, null);\n }\n\n public ZenConfig(String title, int width, int height, String uiSkinPath) {\n this.window = new Window(title, width, height);\n this.ui = new UI(uiSkinPath);\n }\n\n public static class Window {\n public final String title;\n public final int width;\n public final int height;\n\n public Window(String title, int width, int height) {\n this.title = title;\n this.width = width;\n this.height = height;\n }\n }\n\n public static class UI {\n public final String skinPath;\n\n public UI() {\n this(null);\n }\n\n public UI(String skinPath) {\n this.skinPath = skinPath;\n }\n }\n}"
},
{
"identifier": "ZenMain",
"path": "src/main/java/zendo/games/zenlib/ZenMain.java",
"snippet": "public abstract class ZenMain<AssetsType extends ZenAssets> extends ApplicationAdapter {\n\n /**\n * Debug flags, toggle these values as needed, or override in project's ZenMain subclass\n */\n public static class Debug {\n public static boolean general = false;\n public static boolean shaders = false;\n public static boolean ui = false;\n }\n\n @SuppressWarnings(\"rawtypes\")\n public static ZenMain instance;\n\n public ZenConfig config;\n public AssetsType assets;\n public TweenManager tween;\n public FrameBuffer frameBuffer;\n public TextureRegion frameBufferRegion;\n public OrthographicCamera windowCamera;\n\n private Transition transition;\n\n public ZenMain(ZenConfig config) {\n ZenMain.instance = this;\n this.config = config;\n }\n\n /**\n * Override to create project-specific ZenAssets subclass instance\n */\n public abstract AssetsType createAssets();\n\n /**\n * Override to create project-specific ZenScreen subclass instance that will be used as the starting screen\n */\n public abstract ZenScreen createStartScreen();\n\n @Override\n public void create() {\n Time.init();\n\n // TODO - consider moving to ZenAssets\n tween = new TweenManager();\n Tween.setWaypointsLimit(4);\n Tween.setCombinedAttributesLimit(4);\n Tween.registerAccessor(Color.class, new ColorAccessor());\n Tween.registerAccessor(Rectangle.class, new RectangleAccessor());\n Tween.registerAccessor(Vector2.class, new Vector2Accessor());\n Tween.registerAccessor(Vector3.class, new Vector3Accessor());\n Tween.registerAccessor(OrthographicCamera.class, new CameraAccessor());\n\n frameBuffer = new FrameBuffer(Pixmap.Format.RGBA8888, config.window.width, config.window.height, true);\n var texture = frameBuffer.getColorBufferTexture();\n texture.setFilter(Texture.TextureFilter.Linear, Texture.TextureFilter.Linear);\n frameBufferRegion = new TextureRegion(texture);\n frameBufferRegion.flip(false, true);\n\n windowCamera = new OrthographicCamera();\n windowCamera.setToOrtho(false, config.window.width, config.window.height);\n windowCamera.update();\n\n assets = createAssets();\n\n transition = new Transition(config);\n setScreen(createStartScreen());\n }\n\n @Override\n public void dispose() {\n frameBuffer.dispose();\n transition.dispose();\n assets.dispose();\n }\n\n @Override\n public void resize(int width, int height) {\n var screen = currentScreen();\n if (screen != null) {\n screen.resize(width, height);\n }\n }\n\n public ZenScreen currentScreen() {\n return transition.screens.current;\n }\n\n public void update() {\n // handle global input\n // TODO - might not want to keep these in library code\n {\n if (Gdx.input.isKeyJustPressed(Input.Keys.ESCAPE)) {\n Gdx.app.exit();\n }\n if (Gdx.input.isKeyJustPressed(Input.Keys.F1)) {\n Debug.general = !Debug.general;\n Debug.ui = !Debug.ui;\n }\n }\n\n // update things that must update every tick\n {\n Time.update();\n tween.update(Time.delta);\n transition.alwaysUpdate(Time.delta);\n }\n\n // handle a pause\n if (Time.pause_timer > 0) {\n Time.pause_timer -= Time.delta;\n if (Time.pause_timer <= -0.0001f) {\n Time.delta = -Time.pause_timer;\n } else {\n // skip updates if we're paused\n return;\n }\n }\n Time.millis += (long) Time.delta;\n Time.previous_elapsed = Time.elapsed_millis();\n\n // update normally (if not paused)\n transition.update(Time.delta);\n }\n\n @Override\n public void render() {\n update();\n var batch = assets.batch;\n var screens = transition.screens;\n\n screens.current.renderFrameBuffers(batch);\n if (screens.next == null) {\n screens.current.render(batch);\n } else {\n transition.render(batch, windowCamera);\n }\n }\n\n public void setScreen(ZenScreen currentScreen) {\n setScreen(currentScreen, null, Transition.DEFAULT_SPEED);\n }\n\n public void setScreen(final ZenScreen newScreen, ZenTransition type, float transitionSpeed) {\n // only one transition at a time\n if (transition.active) return;\n if (transition.screens.next != null) return;\n\n var screens = transition.screens;\n if (screens.current == null) {\n // no current screen set, go ahead and set it\n screens.current = newScreen;\n } else {\n // current screen is set, so trigger transition to new screen\n transition.startTransition(newScreen, type, transitionSpeed);\n }\n }\n}"
},
{
"identifier": "ZenTransition",
"path": "src/main/java/zendo/games/zenlib/assets/ZenTransition.java",
"snippet": "public enum ZenTransition {\n // spotless:off\n blinds\n , circle_crop\n , crosshatch\n , cube\n , dissolve\n , doom_drip\n , dreamy\n , heart\n , pixelize\n , radial\n , ripple\n , simple_zoom\n , stereo\n ;\n // spotless:on\n\n public ShaderProgram shader;\n public static boolean initialized = false;\n\n ZenTransition() {\n this.shader = null;\n }\n\n public static void init() {\n var vertSrcPath = \"shaders/transitions/default.vert\";\n for (var value : values()) {\n var fragSrcPath = \"shaders/transitions/\" + value.name() + \".frag\";\n value.shader = loadShader(vertSrcPath, fragSrcPath);\n }\n initialized = true;\n }\n\n public static ShaderProgram random() {\n if (!initialized) {\n throw new GdxRuntimeException(\n \"Failed to get random screen transition shader, ScreenTransitions is not initialized\");\n }\n\n var random = (int) (Math.random() * values().length);\n return values()[random].shader;\n }\n\n public static ShaderProgram loadShader(String vertSourcePath, String fragSourcePath) {\n ShaderProgram.pedantic = false;\n var shaderProgram = new ShaderProgram(\n Gdx.files.classpath(\"zendo/games/zenlib/assets/\" + vertSourcePath),\n Gdx.files.classpath(\"zendo/games/zenlib/assets/\" + fragSourcePath));\n var log = shaderProgram.getLog();\n\n if (!shaderProgram.isCompiled()) {\n throw new GdxRuntimeException(\"LoadShader: compilation failed for \" + \"'\" + vertSourcePath + \"' and '\"\n + fragSourcePath + \"':\\n\" + log);\n } else if (ZenMain.Debug.shaders) {\n Gdx.app.debug(\"LoadShader\", \"ShaderProgram compilation log: \" + log);\n }\n\n return shaderProgram;\n }\n}"
},
{
"identifier": "ZenScreen",
"path": "src/main/java/zendo/games/zenlib/screens/ZenScreen.java",
"snippet": "public abstract class ZenScreen implements Disposable {\n\n public final SpriteBatch batch;\n public final TweenManager tween;\n public final OrthographicCamera windowCamera;\n public final Vector3 pointerPos;\n\n protected OrthographicCamera worldCamera;\n protected Viewport viewport;\n protected Stage uiStage;\n protected Skin skin;\n protected boolean exitingScreen;\n\n public ZenScreen() {\n var main = ZenMain.instance;\n\n this.batch = main.assets.batch;\n this.tween = main.tween;\n this.windowCamera = main.windowCamera;\n this.pointerPos = new Vector3();\n this.worldCamera = new OrthographicCamera();\n this.viewport = new ScreenViewport(worldCamera);\n this.viewport.update(main.config.window.width, main.config.window.height, true);\n this.exitingScreen = false;\n\n initializeUI();\n }\n\n @Override\n public void dispose() {}\n\n public void resize(int width, int height) {\n viewport.update(width, height, true);\n }\n\n /**\n * Update something in the screen even when\n * {@code Time.pause_for()} is being processed\n * @param dt the time in seconds since the last frame\n */\n public void alwaysUpdate(float dt) {}\n\n public void update(float dt) {\n windowCamera.update();\n worldCamera.update();\n uiStage.act(dt);\n }\n\n public void renderFrameBuffers(SpriteBatch batch) {}\n\n public abstract void render(SpriteBatch batch);\n\n protected void initializeUI() {\n skin = VisUI.getSkin();\n\n var viewport = new ScreenViewport(windowCamera);\n uiStage = new Stage(viewport, batch);\n\n // extend and setup any per-screen ui widgets in here...\n }\n}"
},
{
"identifier": "Time",
"path": "src/main/java/zendo/games/zenlib/utils/Time.java",
"snippet": "public class Time {\n\n private static class CallbackInfo {\n private final Callback callback;\n private final Object[] params;\n private float timer;\n\n public float timeout = 0;\n public float interval = 0;\n\n CallbackInfo(Callback callback, Object... params) {\n this.callback = callback;\n this.params = params;\n this.timer = 0;\n }\n\n boolean isInterval() {\n return (interval > 0);\n }\n\n boolean isTimeout() {\n return (timeout > 0);\n }\n\n boolean update(float dt) {\n boolean called = false;\n\n timer += dt;\n\n if (interval > 0) {\n if (timer >= interval) {\n timer -= interval;\n if (callback != null) {\n callback.run(params);\n called = true;\n }\n }\n } else {\n if (timer >= timeout) {\n if (callback != null) {\n callback.run(params);\n called = true;\n }\n }\n }\n\n return called;\n }\n }\n\n private static long start_millis = 0;\n\n public static long millis = 0;\n public static long previous_elapsed = 0;\n public static float delta = 0;\n public static float pause_timer = 0;\n\n private static Array<CallbackInfo> callbacks;\n\n public static void init() {\n start_millis = TimeUtils.millis();\n callbacks = new Array<>();\n }\n\n public static void update() {\n Time.delta = Calc.min(1 / 30f, Gdx.graphics.getDeltaTime());\n\n for (int i = callbacks.size - 1; i >= 0; i--) {\n CallbackInfo info = callbacks.get(i);\n boolean wasCalled = info.update(Time.delta);\n if (wasCalled && info.isTimeout()) {\n callbacks.removeIndex(i);\n }\n }\n }\n\n public static void do_after_delay(float seconds, Callback callback) {\n CallbackInfo info = new CallbackInfo(callback);\n info.timeout = seconds;\n callbacks.add(info);\n }\n\n public static void do_at_interval(float seconds, Callback callback) {\n CallbackInfo info = new CallbackInfo(callback);\n info.interval = seconds;\n callbacks.add(info);\n }\n\n public static long elapsed_millis() {\n return TimeUtils.timeSinceMillis(start_millis);\n }\n\n public static void pause_for(float time) {\n if (time >= pause_timer) {\n pause_timer = time;\n }\n }\n\n public static boolean on_time(float time, float timestamp) {\n return (time >= timestamp) && ((time - Time.delta) < timestamp);\n }\n\n public static boolean on_interval(float time, float delta, float interval, float offset) {\n return Calc.floor((time - offset - delta) / interval) < Calc.floor((time - offset) / interval);\n }\n\n public static boolean on_interval(float delta, float interval, float offset) {\n return Time.on_interval(Time.elapsed_millis(), delta, interval, offset);\n }\n\n public static boolean on_interval(float interval, float offset) {\n return Time.on_interval(Time.elapsed_millis(), Time.delta, interval, offset);\n }\n\n public static boolean on_interval(float interval) {\n return Time.on_interval(interval, 0);\n }\n\n public static boolean between_interval(float time, float interval, float offset) {\n return Calc.modf(time - offset, interval * 2) >= interval;\n }\n\n public static boolean between_interval(float interval, float offset) {\n return Time.between_interval(Time.elapsed_millis(), interval, offset);\n }\n\n public static boolean between_interval(float interval) {\n return Time.between_interval(interval, 0);\n }\n}"
}
] | import aurelienribon.tweenengine.Timeline;
import aurelienribon.tweenengine.Tween;
import aurelienribon.tweenengine.primitives.MutableFloat;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.*;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.glutils.FrameBuffer;
import com.badlogic.gdx.graphics.glutils.ShaderProgram;
import com.badlogic.gdx.utils.Disposable;
import zendo.games.zenlib.ZenConfig;
import zendo.games.zenlib.ZenMain;
import zendo.games.zenlib.assets.ZenTransition;
import zendo.games.zenlib.screens.ZenScreen;
import zendo.games.zenlib.utils.Time; | 3,580 | package zendo.games.zenlib.screens.transitions;
public class Transition implements Disposable {
public static final float DEFAULT_SPEED = 0.66f;
public boolean active;
public MutableFloat percent;
public ShaderProgram shader;
public final Screens screens = new Screens();
public final FrameBuffers fbo = new FrameBuffers();
public final Textures tex = new Textures();
| package zendo.games.zenlib.screens.transitions;
public class Transition implements Disposable {
public static final float DEFAULT_SPEED = 0.66f;
public boolean active;
public MutableFloat percent;
public ShaderProgram shader;
public final Screens screens = new Screens();
public final FrameBuffers fbo = new FrameBuffers();
public final Textures tex = new Textures();
| private final ZenConfig config; | 0 | 2023-10-21 19:36:50+00:00 | 4k |
tuna-pizza/GraphXings | src/GraphXings/Game/GameInstance/PlanarGameInstanceFactory.java | [
{
"identifier": "IntegerMaths",
"path": "src/GraphXings/Algorithms/IntegerMaths.java",
"snippet": "public class IntegerMaths\n{\n\t/**\n\t * Computes the power of an int.\n\t * @param base An integer base.\n\t * @param exp An integer exponent.\n\t * @return The integer power.\n\t */\n\tpublic static int pow (int base, int exp)\n\t{\n\t\tint res = 1;\n\t\tfor (int i = 0; i < exp; i++)\n\t\t{\n\t\t\tres *= base;\n\t\t}\n\t\treturn res;\n\t}\n}"
},
{
"identifier": "Edge",
"path": "src/GraphXings/Data/Edge.java",
"snippet": "public class Edge\r\n{\r\n /**\r\n * The first vertex.\r\n */\r\n private Vertex s;\r\n /**\r\n * The second vertex.\r\n */\r\n private Vertex t;\r\n\r\n /**\r\n * Creates an Edge between Vertices s and t.\r\n * @param s A vertex of the graph.\r\n * @param t A vertex of the graph.\r\n */\r\n public Edge(Vertex s, Vertex t)\r\n {\r\n this.s = s;\r\n this.t = t;\r\n }\r\n\r\n /**\r\n * Checks if this and other are the same undirected edge.\r\n * @param other Another Edge object.\r\n * @return True if both Edge objects connect the same two vertices, false otherwise.\r\n */\r\n public boolean equals(Edge other)\r\n {\r\n if (other == null)\r\n {\r\n return false;\r\n }\r\n return ((s.equals(other.getS())&&t.equals(other.getT())) || (t.equals(other.getS())&&s.equals(other.getT())));\r\n }\r\n\r\n /**\r\n * Returns the first endvertex.\r\n * @return The first endvertex.\r\n */\r\n public Vertex getS()\r\n {\r\n return s;\r\n }\r\n\r\n /**\r\n * Returns the second endvertex.\r\n * @return The second endvertex.\r\n */\r\n public Vertex getT()\r\n {\r\n return t;\r\n }\r\n\r\n /**\r\n * Decides if this and other share an endvertex.\r\n * @param other Another Edge object.\r\n * @return True, if both Edge objects share an endvertex, false otherwise.\r\n */\r\n public boolean isAdjacent(Edge other)\r\n {\r\n return (this.s.equals(other.getS()) || this.s.equals(other.getT()) || this.t.equals(other.getS()) || this.t.equals(other.getT()));\r\n }\r\n}\r"
},
{
"identifier": "Graph",
"path": "src/GraphXings/Data/Graph.java",
"snippet": "public class Graph\r\n{\r\n /**\r\n * The vertex set.\r\n */\r\n private HashSet<Vertex> vertices;\r\n /**\r\n * The edge set.\r\n */\r\n private HashSet<Edge> edges;\r\n /**\r\n * The adjacency list representation.\r\n */\r\n private HashMap<Vertex,HashSet<Edge>> adjacentEdges;\r\n /**\r\n * The number of vertices.\r\n */\r\n private int n;\r\n /**\r\n * The number of edges.\r\n */\r\n private int m;\r\n\r\n /**\r\n * Initializes an empty graph.\r\n */\r\n public Graph()\r\n {\r\n vertices = new HashSet<>();\r\n edges = new HashSet<>();\r\n adjacentEdges = new HashMap<>();\r\n n = 0;\r\n m = 0;\r\n }\r\n\r\n /**\r\n * Adds a vertex to the graph.\r\n * @param v The vertex to be added.\r\n */\r\n public void addVertex(Vertex v)\r\n {\r\n if (!vertices.contains(v))\r\n {\r\n vertices.add(v);\r\n adjacentEdges.put(v,new HashSet<>());\r\n n++;\r\n }\r\n }\r\n\r\n /**\r\n * Add an edge to the graph.\r\n * @param e The edge to be added.\r\n * @return True, if the edge was successfully added, false otherwise.\r\n */\r\n public boolean addEdge(Edge e)\r\n {\r\n if (vertices.contains(e.getS())&&vertices.contains(e.getT()))\r\n {\r\n if (!adjacentEdges.get(e.getS()).contains(e))\r\n {\r\n adjacentEdges.get(e.getS()).add(e);\r\n adjacentEdges.get(e.getT()).add(e);\r\n edges.add(e);\r\n m++;\r\n return true;\r\n }\r\n }\r\n return false;\r\n }\r\n\r\n /**\r\n * Gets the vertex set.\r\n * @return An Iterable over the vertex set.\r\n */\r\n public Iterable<Vertex> getVertices()\r\n {\r\n return vertices;\r\n }\r\n\r\n /**\r\n * Returns the edges incident to a specified vertex.\r\n * @param v The vertex whose adjacent edges are queried.\r\n * @return An Iterable over the edges incident to Vertex v.\r\n */\r\n public Iterable<Edge> getIncidentEdges(Vertex v)\r\n {\r\n if (!vertices.contains(v))\r\n {\r\n return null;\r\n }\r\n return adjacentEdges.get(v);\r\n }\r\n\r\n /**\r\n * Returns the edges of the graph.\r\n * @return An Iterable over the edge set.\r\n */\r\n public Iterable<Edge> getEdges()\r\n {\r\n return edges;\r\n }\r\n\r\n /**\r\n * Get the number of vertices.\r\n * @return The number of vertices.\r\n */\r\n public int getN()\r\n {\r\n return n;\r\n }\r\n\r\n /**\r\n * Gets the number of edges.\r\n * @return The number of edges.\r\n */\r\n public int getM()\r\n {\r\n return m;\r\n }\r\n\r\n /**\r\n * Creates a functionally equivalent copy of the graph that uses different references.\r\n * @return A Graph object containing a copy of the graph.\r\n */\r\n public Graph copy()\r\n {\r\n Graph copy = new Graph();\r\n for (Vertex v : vertices)\r\n {\r\n copy.addVertex(v);\r\n }\r\n for (Edge e : edges)\r\n {\r\n copy.addEdge(e);\r\n }\r\n return copy;\r\n }\r\n\r\n /**\r\n * Shuffles the order of vertices in the vertex set.\r\n */\r\n public void shuffleIndices()\r\n {\r\n List<Vertex> toBeShuffled = new ArrayList<>(vertices);\r\n Collections.shuffle(toBeShuffled);\r\n vertices = new HashSet<>(toBeShuffled);\r\n }\r\n\r\n /**\r\n * Provides the adjacency list representation of the graph.\r\n * @return The adjacency list representation.\r\n */\r\n @Override\r\n public String toString()\r\n {\r\n String out = \"\";\r\n for (Vertex v : vertices)\r\n {\r\n out += v.getId() + \": [\";\r\n for (Edge e: adjacentEdges.get(v))\r\n {\r\n out += \"(\" + e.getS().getId() +\",\" + e.getT().getId() +\"),\";\r\n }\r\n out += \"]\\n\";\r\n }\r\n return out;\r\n }\r\n}\r"
},
{
"identifier": "Vertex",
"path": "src/GraphXings/Data/Vertex.java",
"snippet": "public class Vertex\r\n{\r\n /**\r\n * The ID of the vertex.\r\n */\r\n private String id;\r\n\r\n /**\r\n * Creates a vertex with a given ID.\r\n * @param id The provided ID.\r\n */\r\n public Vertex(String id)\r\n {\r\n this.id = id;\r\n }\r\n\r\n /**\r\n * Gets the ID of the vertex.\r\n * @return The ID of the vertex.\r\n */\r\n public String getId()\r\n {\r\n return id;\r\n }\r\n}\r"
}
] | import GraphXings.Algorithms.IntegerMaths;
import GraphXings.Data.Edge;
import GraphXings.Data.Graph;
import GraphXings.Data.Vertex;
import java.util.LinkedList;
import java.util.Random; | 2,564 | package GraphXings.Game.GameInstance;
/**
* A GameInstance factory creating random planar graphs.
* Each graph is one of:
* mode 0 - a planar triangulation
* mode 1 - the dual of a planar triangulation (i.e., a triconnected cubic planar graph)
* mode 2 - a random subgraph of mode 0, where each edge is selected with a probability prob
*/
public class PlanarGameInstanceFactory implements GameInstanceFactory
{
/**
* Random number generator for random sampling.
*/
Random r;
/**
* Probability for choosing an edge. Default: 0.8.
*/
double prob;
/**
* Constructs a PlanarGameInstanceFactory.
* @param seed Seed for the random number generator.
*/
public PlanarGameInstanceFactory(long seed)
{
r = new Random(seed);
prob = 0.8;
}
@Override
public GameInstance getGameInstance()
{
int n_exp = r.nextInt(3) + 2;
int n = r.nextInt(IntegerMaths.pow(10,n_exp-1)*9)+IntegerMaths.pow(10,n_exp-1);
boolean dual;
boolean randomEdge;
int mode = r.nextInt(4);
switch (mode)
{
case 0:
{
dual = false;
randomEdge = false;
break;
}
case 1:
{
dual = true;
randomEdge = false;
break;
}
default:
{
dual = false;
randomEdge = true;
break;
}
}
Graph g = createPlanarGraph(n,dual,randomEdge);
if (dual)
{
n = 2*n-4;
}
int width = 0;
int height = 0;
while (width*height < 10*n)
{
int w_exp = r.nextInt(4) + 1;
int h_exp;
boolean roughlySquare = r.nextBoolean();
if (roughlySquare)
{
h_exp = w_exp;
}
else
{
h_exp = r.nextInt(4) + 1;
}
width = r.nextInt(IntegerMaths.pow(10,w_exp-1)*9)+IntegerMaths.pow(10,w_exp-1);
height = r.nextInt(IntegerMaths.pow(10,h_exp-1)*9)+IntegerMaths.pow(10,h_exp-1);
}
return new GameInstance(g,width,height);
}
/**
* Sets the probability for choosing each edge in mode 2.
* @param prob The probability for choosing an edge. Must be in range (0,1).
*/
public void setEdgeProbability (double prob)
{
if (prob > 0 || prob < 1)
{
this.prob = prob;
}
}
/**
* Constructs a random planar graph.
* @param n The desired number of vertices. If dual is true, the output will have 2n-4 vertices.
* @param dual If true, provides the dual graph of a triangulation on n vertices instead.
* @param randomEdge If true, each edge of the primal graph is added with probability prob.
* @return A random planar graph according to the specification.
*/
private Graph createPlanarGraph(int n, boolean dual, boolean randomEdge)
{
Graph g = new Graph();
Graph d = new Graph(); | package GraphXings.Game.GameInstance;
/**
* A GameInstance factory creating random planar graphs.
* Each graph is one of:
* mode 0 - a planar triangulation
* mode 1 - the dual of a planar triangulation (i.e., a triconnected cubic planar graph)
* mode 2 - a random subgraph of mode 0, where each edge is selected with a probability prob
*/
public class PlanarGameInstanceFactory implements GameInstanceFactory
{
/**
* Random number generator for random sampling.
*/
Random r;
/**
* Probability for choosing an edge. Default: 0.8.
*/
double prob;
/**
* Constructs a PlanarGameInstanceFactory.
* @param seed Seed for the random number generator.
*/
public PlanarGameInstanceFactory(long seed)
{
r = new Random(seed);
prob = 0.8;
}
@Override
public GameInstance getGameInstance()
{
int n_exp = r.nextInt(3) + 2;
int n = r.nextInt(IntegerMaths.pow(10,n_exp-1)*9)+IntegerMaths.pow(10,n_exp-1);
boolean dual;
boolean randomEdge;
int mode = r.nextInt(4);
switch (mode)
{
case 0:
{
dual = false;
randomEdge = false;
break;
}
case 1:
{
dual = true;
randomEdge = false;
break;
}
default:
{
dual = false;
randomEdge = true;
break;
}
}
Graph g = createPlanarGraph(n,dual,randomEdge);
if (dual)
{
n = 2*n-4;
}
int width = 0;
int height = 0;
while (width*height < 10*n)
{
int w_exp = r.nextInt(4) + 1;
int h_exp;
boolean roughlySquare = r.nextBoolean();
if (roughlySquare)
{
h_exp = w_exp;
}
else
{
h_exp = r.nextInt(4) + 1;
}
width = r.nextInt(IntegerMaths.pow(10,w_exp-1)*9)+IntegerMaths.pow(10,w_exp-1);
height = r.nextInt(IntegerMaths.pow(10,h_exp-1)*9)+IntegerMaths.pow(10,h_exp-1);
}
return new GameInstance(g,width,height);
}
/**
* Sets the probability for choosing each edge in mode 2.
* @param prob The probability for choosing an edge. Must be in range (0,1).
*/
public void setEdgeProbability (double prob)
{
if (prob > 0 || prob < 1)
{
this.prob = prob;
}
}
/**
* Constructs a random planar graph.
* @param n The desired number of vertices. If dual is true, the output will have 2n-4 vertices.
* @param dual If true, provides the dual graph of a triangulation on n vertices instead.
* @param randomEdge If true, each edge of the primal graph is added with probability prob.
* @return A random planar graph according to the specification.
*/
private Graph createPlanarGraph(int n, boolean dual, boolean randomEdge)
{
Graph g = new Graph();
Graph d = new Graph(); | LinkedList<Vertex> outerface = new LinkedList<>(); | 3 | 2023-10-18 12:11:38+00:00 | 4k |
instrumental-id/iiq-common-public | src/com/identityworksllc/iiq/common/AggregationOutcome.java | [
{
"identifier": "Outcome",
"path": "src/com/identityworksllc/iiq/common/vo/Outcome.java",
"snippet": "@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY)\npublic class Outcome implements AutoCloseable, Serializable {\n\n /**\n * Create and start a new Outcome object. This is intended to be used\n * in conjunction with the try-with-resources and AutoClosable function\n * to start/stop your Outcome along with its operation.\n * @return A started outcome\n */\n public static Outcome start() {\n Outcome outcome = new Outcome();\n outcome.startTimeMillis = outcome.created;\n return outcome;\n }\n\n /**\n * The name of an application associated with this outcome\n */\n private String applicationName;\n\n /**\n * The name of an attribute associated with this outcome\n */\n private String attribute;\n\n /**\n * The millisecond timestamp at which this object was created\n */\n private final long created;\n\n /**\n * The name of an identity associated with this outcome\n */\n private String identityName;\n\n /**\n * The list of timestampped messages logged for this outcome\n */\n private final List<StampedMessage> messages;\n\n /**\n * A native identity associated with this outcome\n */\n private String nativeIdentity;\n\n /**\n * An arbitrary object ID associated with this outcome\n */\n private String objectId;\n\n /**\n * An arbitrary object name associated with this outcome\n */\n private String objectName;\n\n /**\n * The type of the object ID or name above\n */\n private String objectType;\n\n /**\n * The provisioning transaction associated with this outcome\n */\n private String provisioningTransaction;\n\n /**\n * An indicator that something has been refreshed\n */\n private Boolean refreshed;\n\n /**\n * A response code, intended when this is used for reporting an HTTP response\n */\n @JsonInclude(JsonInclude.Include.NON_DEFAULT)\n private Integer responseCode;\n\n /**\n * The start time in milliseconds\n */\n @JsonInclude(JsonInclude.Include.NON_DEFAULT)\n private long startTimeMillis;\n\n /**\n * The status of this operation\n */\n private OutcomeType status;\n\n /**\n * The stop time in milliseconds\n */\n @JsonInclude(JsonInclude.Include.NON_DEFAULT)\n private long stopTimeMillis;\n\n /**\n * Arbitrary text associated with this operation\n */\n private String text;\n\n /**\n * A flag indicating that something was updated\n */\n private Boolean updated;\n\n /**\n * Arbitrary value associated with this operation (presumably of the named attribute)\n */\n private String value;\n\n /**\n * Basic constructor, also used by Jackson to figure out what the 'default' for each\n * item in the class is.\n */\n public Outcome() {\n this.created = System.currentTimeMillis();\n this.stopTimeMillis = -1L;\n this.startTimeMillis = -1L;\n this.messages = new ArrayList<>();\n }\n\n /**\n * Adds a timestamped error to this outcome\n * @param input A string message to use with the error\n * @param err The error itself\n */\n public void addError(String input, Throwable err) {\n this.messages.add(new StampedMessage(input, err));\n }\n\n /**\n * Adds a timestamped IIQ message to this outcome\n * @param input The IIQ outcome\n */\n public void addMessage(Message input) {\n this.messages.add(new StampedMessage(input));\n }\n\n /**\n * Adds a timestamped log message of INFO level to this outcome\n * @param input The log message\n */\n public void addMessage(String input) {\n this.messages.add(new StampedMessage(input));\n }\n\n /**\n * If the outcome has not yet had its stop timestamp set, sets it to the current time\n */\n @Override\n public void close() {\n if (this.stopTimeMillis < 0) {\n this.stopTimeMillis = System.currentTimeMillis();\n }\n }\n\n public String getApplicationName() {\n return applicationName;\n }\n\n public String getAttribute() {\n return attribute;\n }\n\n public long getCreated() {\n return created;\n }\n\n public String getIdentityName() {\n return identityName;\n }\n\n public List<StampedMessage> getMessages() {\n return messages;\n }\n\n public String getNativeIdentity() {\n return nativeIdentity;\n }\n\n public String getObjectId() {\n return objectId;\n }\n\n public String getObjectName() {\n return objectName;\n }\n\n public String getObjectType() {\n return objectType;\n }\n\n public String getProvisioningTransaction() {\n return provisioningTransaction;\n }\n\n public int getResponseCode() {\n return responseCode != null ? responseCode : 0;\n }\n\n public long getStartTimeMillis() {\n return startTimeMillis;\n }\n\n /**\n * Gets the status, or calculates it based on other fields.\n *\n * If there is no status explicitly set and the stop time is not set, returns null.\n *\n * @return The status, or null if the outcome is not yet stopped\n */\n public OutcomeType getStatus() {\n if (status != null) {\n return status;\n } else if (this.stopTimeMillis < 0) {\n return null;\n } else {\n boolean hasError = this.messages.stream().anyMatch(msg -> msg.getLevel() == LogLevel.ERROR);\n if (hasError) {\n return OutcomeType.Failure;\n }\n boolean hasWarning = this.messages.stream().anyMatch(msg -> msg.getLevel() == LogLevel.WARN);\n if (hasWarning) {\n return OutcomeType.Warning;\n }\n return OutcomeType.Success;\n }\n }\n\n public long getStopTimeMillis() {\n return stopTimeMillis;\n }\n\n public String getText() {\n return text;\n }\n\n public String getValue() {\n return value;\n }\n\n public boolean isRefreshed() {\n return refreshed != null && refreshed;\n }\n\n public boolean isUpdated() {\n return updated != null && updated;\n }\n\n public void setApplicationName(String applicationName) {\n this.applicationName = applicationName;\n }\n\n public void setAttribute(String attribute) {\n this.attribute = attribute;\n }\n\n public void setIdentityName(String identityName) {\n this.identityName = identityName;\n }\n\n public void setNativeIdentity(String nativeIdentity) {\n this.nativeIdentity = nativeIdentity;\n }\n\n public void setObjectId(String objectId) {\n this.objectId = objectId;\n }\n\n public void setObjectName(String objectName) {\n this.objectName = objectName;\n }\n\n public void setObjectType(String objectType) {\n this.objectType = objectType;\n }\n\n public void setProvisioningTransaction(String provisioningTransaction) {\n this.provisioningTransaction = provisioningTransaction;\n }\n\n public void setRefreshed(Boolean refreshed) {\n this.refreshed = refreshed;\n }\n\n public void setResponseCode(Integer responseCode) {\n this.responseCode = responseCode;\n }\n\n public void setStartTimeMillis(long startTimeMillis) {\n this.startTimeMillis = startTimeMillis;\n }\n\n public void setStatus(OutcomeType status) {\n this.status = status;\n }\n\n public void setStopTimeMillis(long stopTimeMillis) {\n this.stopTimeMillis = stopTimeMillis;\n }\n\n public void setText(String text) {\n this.text = text;\n }\n\n public void setUpdated(Boolean updated) {\n this.updated = updated;\n }\n\n public void setValue(String value) {\n this.value = value;\n }\n\n /**\n * Sets the status to Terminated and the stop time to the current timestamp\n */\n public void terminate() {\n this.status = OutcomeType.Terminated;\n this.stopTimeMillis = System.currentTimeMillis();\n }\n\n @Override\n public String toString() {\n StringJoiner joiner = new StringJoiner(\", \", Outcome.class.getSimpleName() + \"[\", \"]\");\n if ((applicationName) != null) {\n joiner.add(\"applicationName='\" + applicationName + \"'\");\n }\n if ((attribute) != null) {\n joiner.add(\"attribute='\" + attribute + \"'\");\n }\n joiner.add(\"created=\" + created);\n if ((identityName) != null) {\n joiner.add(\"identityName='\" + identityName + \"'\");\n }\n if ((messages) != null) {\n joiner.add(\"messages=\" + messages);\n }\n if ((nativeIdentity) != null) {\n joiner.add(\"nativeIdentity='\" + nativeIdentity + \"'\");\n }\n if ((objectId) != null) {\n joiner.add(\"objectId='\" + objectId + \"'\");\n }\n if ((objectName) != null) {\n joiner.add(\"objectName='\" + objectName + \"'\");\n }\n if ((objectType) != null) {\n joiner.add(\"objectType='\" + objectType + \"'\");\n }\n if ((provisioningTransaction) != null) {\n joiner.add(\"provisioningTransaction='\" + provisioningTransaction + \"'\");\n }\n joiner.add(\"refreshed=\" + refreshed);\n if (responseCode != null && responseCode > 0) {\n joiner.add(\"responseCode=\" + responseCode);\n }\n joiner.add(\"startTimeMillis=\" + startTimeMillis);\n if ((status) != null) {\n joiner.add(\"status=\" + status);\n }\n joiner.add(\"stopTimeMillis=\" + stopTimeMillis);\n if ((text) != null) {\n joiner.add(\"text='\" + text + \"'\");\n }\n joiner.add(\"updated=\" + updated);\n if ((value) != null) {\n joiner.add(\"value='\" + value + \"'\");\n }\n return joiner.toString();\n }\n}"
},
{
"identifier": "OutcomeType",
"path": "src/com/identityworksllc/iiq/common/vo/OutcomeType.java",
"snippet": "public enum OutcomeType {\n Pending,\n Running,\n Success,\n Failure,\n Warning,\n Terminated,\n Skipped,\n Multiple;\n}"
}
] | import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.identityworksllc.iiq.common.vo.Outcome;
import com.identityworksllc.iiq.common.vo.OutcomeType;
import sailpoint.api.SailPointContext;
import sailpoint.object.TaskResult;
import sailpoint.tools.GeneralException;
import sailpoint.tools.Message;
import sailpoint.tools.Util;
import sailpoint.tools.xml.AbstractXmlObject;
import java.util.StringJoiner; | 2,866 | package com.identityworksllc.iiq.common;
/**
* A data class for returning the outcome of the aggregation event
*/
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY)
public class AggregationOutcome extends Outcome {
/**
* An optional error message (can be null);
*/
private String errorMessage;
/**
* Aggregator TaskResults outputs
*/
@JsonIgnore
private String serializedTaskResult;
/**
* Default construct, to be used by Jackson to determine field defaults
*/
@Deprecated
public AggregationOutcome() {
this(null, null);
}
/**
* @param appl The application
* @param ni The native Identity
*/
public AggregationOutcome(String appl, String ni) {
this(appl, ni, null, null);
}
/**
* @param appl The application
* @param ni The native Identity
* @param o The aggregation outcome
*/ | package com.identityworksllc.iiq.common;
/**
* A data class for returning the outcome of the aggregation event
*/
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY)
public class AggregationOutcome extends Outcome {
/**
* An optional error message (can be null);
*/
private String errorMessage;
/**
* Aggregator TaskResults outputs
*/
@JsonIgnore
private String serializedTaskResult;
/**
* Default construct, to be used by Jackson to determine field defaults
*/
@Deprecated
public AggregationOutcome() {
this(null, null);
}
/**
* @param appl The application
* @param ni The native Identity
*/
public AggregationOutcome(String appl, String ni) {
this(appl, ni, null, null);
}
/**
* @param appl The application
* @param ni The native Identity
* @param o The aggregation outcome
*/ | public AggregationOutcome(String appl, String ni, OutcomeType o) { | 1 | 2023-10-20 15:20:16+00:00 | 4k |
mosaic-addons/traffic-state-estimation | src/main/java/com/dcaiti/mosaic/app/fxd/FxdTransmitterApp.java | [
{
"identifier": "CFxdTransmitterApp",
"path": "src/main/java/com/dcaiti/mosaic/app/fxd/config/CFxdTransmitterApp.java",
"snippet": "public class CFxdTransmitterApp {\n\n /**\n * The id of the unit that shall receive the packages.\n */\n public String receiverId = \"server_0\";\n\n /**\n * The interval in which data shall be collected. [ns]\n */\n @JsonAdapter(TimeFieldAdapter.NanoSeconds.class)\n public Long collectionInterval = TIME.SECOND;\n\n /**\n * The interval in which data packages shall be transmitted. [ns]\n */\n @JsonAdapter(TimeFieldAdapter.NanoSeconds.class)\n public Long transmissionInterval = 30 * TIME.SECOND;\n\n @Override\n public String toString() {\n return new ToStringBuilder(this, SHORT_PREFIX_STYLE)\n .append(\"receiverId\", receiverId)\n .append(\"collectionInterval\", collectionInterval)\n .append(\"transmissionInterval\", transmissionInterval)\n .toString();\n }\n}"
},
{
"identifier": "AbstractRecordBuilder",
"path": "src/main/java/com/dcaiti/mosaic/app/fxd/data/AbstractRecordBuilder.java",
"snippet": "public abstract class AbstractRecordBuilder<BuilderT extends FxdRecord.RecordBuilder<BuilderT, RecordT>, RecordT extends FxdRecord>\n implements FxdRecord.RecordBuilder<BuilderT, RecordT> {\n\n protected long timeStamp;\n protected GeoPoint position;\n protected String connectionId;\n protected double speed;\n protected double offset;\n protected double heading;\n\n /**\n * Constructor for the {@link AbstractRecordBuilder} with minimal required parameters.\n */\n public AbstractRecordBuilder(long timeStamp, GeoPoint position, String connectionId) {\n this.timeStamp = timeStamp;\n this.position = position;\n this.connectionId = connectionId;\n }\n\n /**\n * Constructor for the {@link AbstractRecordBuilder} when copying for a different {@link RecordT Record}.\n *\n * @param record the record to copy from\n */\n public AbstractRecordBuilder(RecordT record) {\n timeStamp = record.timeStamp;\n position = record.position;\n connectionId = record.connectionId;\n speed = record.speed;\n offset = record.offset;\n heading = record.heading;\n }\n\n @Override\n public BuilderT withOffset(double offset) {\n this.offset = offset;\n return getThis();\n }\n\n @Override\n public BuilderT withSpeed(double speed) {\n this.speed = speed;\n return getThis();\n }\n\n @Override\n public BuilderT withHeading(double heading) {\n this.heading = heading;\n return getThis();\n }\n\n protected abstract BuilderT getThis();\n\n protected abstract RecordT internalBuild();\n\n public RecordT build() {\n return internalBuild();\n }\n}"
},
{
"identifier": "FxdRecord",
"path": "src/main/java/com/dcaiti/mosaic/app/fxd/data/FxdRecord.java",
"snippet": "public abstract class FxdRecord implements Serializable {\n\n /**\n * Time at record creation. [ns]\n */\n protected final long timeStamp;\n /**\n * Position at record creation.\n */\n protected final GeoPoint position;\n /**\n * Connection at record creation.\n */\n protected final String connectionId;\n /**\n * Speed at record creation. [m/s]\n */\n protected final double speed;\n /**\n * Distance driven on current connection. [m]\n */\n protected final double offset;\n /**\n * Heading of the unit. [°]\n */\n protected final double heading;\n\n /**\n * A {@link FxdRecord} represents a snapshot of a units current spatio-temporal data, including time, position, and connection id.\n * Based on a collection of these records, different traffic state estimation (TSE) algorithms can be applied\n */\n protected FxdRecord(long timeStamp, GeoPoint position, String connectionId, double speed, double offset, double heading) {\n this.timeStamp = timeStamp;\n this.position = position;\n this.connectionId = connectionId;\n this.speed = speed;\n this.offset = offset;\n this.heading = heading;\n }\n\n public long getTimeStamp() {\n return timeStamp;\n }\n\n public GeoPoint getPosition() {\n return position;\n }\n\n public String getConnectionId() {\n return connectionId;\n }\n\n public double getSpeed() {\n return speed;\n }\n\n public double getOffset() {\n return offset;\n }\n\n public double getHeading() {\n return heading;\n }\n\n @Override\n public String toString() {\n return new ToStringBuilder(this, SHORT_PREFIX_STYLE)\n .appendSuper(super.toString())\n .append(\"timestamp\", timeStamp)\n .append(\"position\", position)\n .append(\"connectionId\", connectionId)\n .append(\"speed\", speed)\n .append(\"offset\", offset)\n .append(\"heading\", heading)\n .toString();\n }\n\n /**\n * Method that estimates the size in Bytes for an {@link FxdRecord}.\n */\n public long calculateRecordSize() {\n return 4L // time stamp\n + 8L * 3L // position (three doubles: lat, lon, ele)\n + 10L // average connection id 10 chars, 1 byte per char\n + 8L // speed\n + 8L // offset\n + 8L; // heading\n }\n\n /**\n * Interface for the record builder class. Concrete implementations will extend the {@link AbstractRecordBuilder}-class.\n *\n * @param <BuilderT> concrete type of the builder\n * @param <RecordT> concrete type of the record\n */\n public interface RecordBuilder<BuilderT extends RecordBuilder<BuilderT, RecordT>, RecordT extends FxdRecord> {\n\n BuilderT withOffset(double offset);\n\n BuilderT withSpeed(double speed);\n\n BuilderT withHeading(double heading);\n }\n}"
},
{
"identifier": "AbstractUpdateMessageBuilder",
"path": "src/main/java/com/dcaiti/mosaic/app/fxd/messages/AbstractUpdateMessageBuilder.java",
"snippet": "public abstract class AbstractUpdateMessageBuilder<\n BuilderT extends FxdUpdateMessage.FxdUpdateMessageBuilder<BuilderT, RecordT, UpdateT>,\n RecordT extends FxdRecord,\n UpdateT extends FxdUpdateMessage<RecordT>\n >\n implements FxdUpdateMessage.FxdUpdateMessageBuilder<BuilderT, RecordT, UpdateT> {\n protected final MessageRouting messageRouting;\n protected final long timestamp;\n protected final SortedMap<Long, RecordT> records = new TreeMap<>();\n protected boolean isFinal = false;\n\n public AbstractUpdateMessageBuilder(MessageRouting messageRouting, long timestamp) {\n this.messageRouting = messageRouting;\n this.timestamp = timestamp;\n }\n\n @Override\n public BuilderT addRecords(SortedMap<Long, RecordT> records) {\n this.records.putAll(records);\n return getThis();\n }\n\n @Override\n public BuilderT isFinal() {\n isFinal = true;\n return getThis();\n }\n\n protected abstract BuilderT getThis();\n\n protected abstract UpdateT internalBuild();\n\n public UpdateT build() {\n return internalBuild();\n }\n\n}"
},
{
"identifier": "FxdUpdateMessage",
"path": "src/main/java/com/dcaiti/mosaic/app/fxd/messages/FxdUpdateMessage.java",
"snippet": "public abstract class FxdUpdateMessage<RecordT extends FxdRecord> extends V2xMessage {\n\n private final long timeStamp;\n private final SortedMap<Long, RecordT> records;\n private final boolean isFinal;\n\n protected FxdUpdateMessage(MessageRouting messageRouting, long timeStamp, SortedMap<Long, RecordT> records, boolean isFinal) {\n super(messageRouting);\n this.timeStamp = timeStamp;\n this.records = records;\n this.isFinal = isFinal;\n }\n\n public long getTimeStamp() {\n return timeStamp;\n }\n\n public final SortedMap<Long, RecordT> getRecords() {\n // always return copy of records, in case list is processed by multiple processors\n return Maps.newTreeMap(records);\n }\n\n public boolean isFinal() {\n return isFinal;\n }\n\n @Nonnull\n @Override\n public EncodedPayload getPayLoad() {\n return new EncodedPayload(calculateMessageLength());\n }\n\n /**\n * Method that estimates the length of an average {@link FxdUpdateMessage UpdateMessage} adding the baseline length of required fields with\n * the length of the specialized {@link FxdUpdateMessage FxdUpdateMessages}.\n */\n public long calculateMessageLength() {\n return 10 // \"header size\"\n + 8 // for time stamp\n + 1 // for isFinal flag\n + getRecords().values().stream().mapToLong(FxdRecord::calculateRecordSize).sum(); // size for each record\n }\n\n /**\n * Interface for the builder of {@link FxdUpdateMessage FxdUpdateMessages}.\n *\n * @param <BuilderT> concrete type of the builder\n * @param <RecordT> concrete type of the records\n * @param <UpdateT> concrete type of the updates being built\n */\n interface FxdUpdateMessageBuilder<\n BuilderT extends FxdUpdateMessageBuilder<BuilderT, RecordT, UpdateT>,\n RecordT extends FxdRecord,\n UpdateT extends FxdUpdateMessage<RecordT>> {\n\n BuilderT addRecords(SortedMap<Long, RecordT> records);\n\n BuilderT isFinal();\n }\n\n}"
}
] | import com.dcaiti.mosaic.app.fxd.config.CFxdTransmitterApp;
import com.dcaiti.mosaic.app.fxd.data.AbstractRecordBuilder;
import com.dcaiti.mosaic.app.fxd.data.FxdRecord;
import com.dcaiti.mosaic.app.fxd.messages.AbstractUpdateMessageBuilder;
import com.dcaiti.mosaic.app.fxd.messages.FxdUpdateMessage;
import org.eclipse.mosaic.fed.application.ambassador.simulation.communication.CamBuilder;
import org.eclipse.mosaic.fed.application.ambassador.simulation.communication.ReceivedAcknowledgement;
import org.eclipse.mosaic.fed.application.ambassador.simulation.communication.ReceivedV2xMessage;
import org.eclipse.mosaic.fed.application.app.ConfigurableApplication;
import org.eclipse.mosaic.fed.application.app.api.CommunicationApplication;
import org.eclipse.mosaic.fed.application.app.api.VehicleApplication;
import org.eclipse.mosaic.fed.application.app.api.os.VehicleOperatingSystem;
import org.eclipse.mosaic.interactions.communication.V2xMessageTransmission;
import org.eclipse.mosaic.lib.geo.GeoUtils;
import org.eclipse.mosaic.lib.objects.road.IConnection;
import org.eclipse.mosaic.lib.objects.v2x.MessageRouting;
import org.eclipse.mosaic.lib.objects.vehicle.VehicleData;
import org.eclipse.mosaic.lib.util.scheduling.Event;
import org.apache.commons.lang3.StringUtils;
import java.util.SortedMap;
import java.util.TreeMap;
import javax.annotation.Nonnull;
import javax.annotation.Nullable; | 2,779 | /*
* Copyright (c) 2023 Fraunhofer FOKUS and others. All rights reserved.
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*
* Contact: [email protected]
*/
package com.dcaiti.mosaic.app.fxd;
public abstract class FxdTransmitterApp<
ConfigT extends CFxdTransmitterApp,
RecordT extends FxdRecord,
RecordBuilderT extends AbstractRecordBuilder<RecordBuilderT, RecordT>, | /*
* Copyright (c) 2023 Fraunhofer FOKUS and others. All rights reserved.
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*
* Contact: [email protected]
*/
package com.dcaiti.mosaic.app.fxd;
public abstract class FxdTransmitterApp<
ConfigT extends CFxdTransmitterApp,
RecordT extends FxdRecord,
RecordBuilderT extends AbstractRecordBuilder<RecordBuilderT, RecordT>, | UpdateT extends FxdUpdateMessage<RecordT>, | 4 | 2023-10-23 16:39:40+00:00 | 4k |
dont-doubt/Neodym | src/main/neodym/NeodymVisitor.java | [
{
"identifier": "NeodymBaseListener",
"path": "src/gen/neodym/antlr/NeodymBaseListener.java",
"snippet": "@SuppressWarnings(\"CheckReturnValue\")\npublic class NeodymBaseListener implements NeodymListener {\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation does nothing.</p>\n\t */\n\t@Override public void enterProg(NeodymParser.ProgContext ctx) { }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation does nothing.</p>\n\t */\n\t@Override public void exitProg(NeodymParser.ProgContext ctx) { }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation does nothing.</p>\n\t */\n\t@Override public void enterMember(NeodymParser.MemberContext ctx) { }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation does nothing.</p>\n\t */\n\t@Override public void exitMember(NeodymParser.MemberContext ctx) { }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation does nothing.</p>\n\t */\n\t@Override public void enterFunc(NeodymParser.FuncContext ctx) { }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation does nothing.</p>\n\t */\n\t@Override public void exitFunc(NeodymParser.FuncContext ctx) { }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation does nothing.</p>\n\t */\n\t@Override public void enterMainFunc(NeodymParser.MainFuncContext ctx) { }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation does nothing.</p>\n\t */\n\t@Override public void exitMainFunc(NeodymParser.MainFuncContext ctx) { }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation does nothing.</p>\n\t */\n\t@Override public void enterFuncBody(NeodymParser.FuncBodyContext ctx) { }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation does nothing.</p>\n\t */\n\t@Override public void exitFuncBody(NeodymParser.FuncBodyContext ctx) { }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation does nothing.</p>\n\t */\n\t@Override public void enterParams(NeodymParser.ParamsContext ctx) { }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation does nothing.</p>\n\t */\n\t@Override public void exitParams(NeodymParser.ParamsContext ctx) { }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation does nothing.</p>\n\t */\n\t@Override public void enterParam(NeodymParser.ParamContext ctx) { }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation does nothing.</p>\n\t */\n\t@Override public void exitParam(NeodymParser.ParamContext ctx) { }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation does nothing.</p>\n\t */\n\t@Override public void enterTypedParam(NeodymParser.TypedParamContext ctx) { }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation does nothing.</p>\n\t */\n\t@Override public void exitTypedParam(NeodymParser.TypedParamContext ctx) { }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation does nothing.</p>\n\t */\n\t@Override public void enterExpr(NeodymParser.ExprContext ctx) { }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation does nothing.</p>\n\t */\n\t@Override public void exitExpr(NeodymParser.ExprContext ctx) { }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation does nothing.</p>\n\t */\n\t@Override public void enterExpr1(NeodymParser.Expr1Context ctx) { }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation does nothing.</p>\n\t */\n\t@Override public void exitExpr1(NeodymParser.Expr1Context ctx) { }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation does nothing.</p>\n\t */\n\t@Override public void enterUniform(NeodymParser.UniformContext ctx) { }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation does nothing.</p>\n\t */\n\t@Override public void exitUniform(NeodymParser.UniformContext ctx) { }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation does nothing.</p>\n\t */\n\t@Override public void enterOptSeparator(NeodymParser.OptSeparatorContext ctx) { }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation does nothing.</p>\n\t */\n\t@Override public void exitOptSeparator(NeodymParser.OptSeparatorContext ctx) { }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation does nothing.</p>\n\t */\n\t@Override public void enterType(NeodymParser.TypeContext ctx) { }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation does nothing.</p>\n\t */\n\t@Override public void exitType(NeodymParser.TypeContext ctx) { }\n\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation does nothing.</p>\n\t */\n\t@Override public void enterEveryRule(ParserRuleContext ctx) { }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation does nothing.</p>\n\t */\n\t@Override public void exitEveryRule(ParserRuleContext ctx) { }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation does nothing.</p>\n\t */\n\t@Override public void visitTerminal(TerminalNode node) { }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation does nothing.</p>\n\t */\n\t@Override public void visitErrorNode(ErrorNode node) { }\n}"
},
{
"identifier": "ProgContext",
"path": "src/gen/neodym/antlr/NeodymParser.java",
"snippet": "@SuppressWarnings(\"CheckReturnValue\")\npublic static class ProgContext extends ParserRuleContext {\n\tpublic TerminalNode EOF() { return getToken(NeodymParser.EOF, 0); }\n\tpublic List<TerminalNode> NL() { return getTokens(NeodymParser.NL); }\n\tpublic TerminalNode NL(int i) {\n\t\treturn getToken(NeodymParser.NL, i);\n\t}\n\tpublic List<MemberContext> member() {\n\t\treturn getRuleContexts(MemberContext.class);\n\t}\n\tpublic MemberContext member(int i) {\n\t\treturn getRuleContext(MemberContext.class,i);\n\t}\n\tpublic List<OptSeparatorContext> optSeparator() {\n\t\treturn getRuleContexts(OptSeparatorContext.class);\n\t}\n\tpublic OptSeparatorContext optSeparator(int i) {\n\t\treturn getRuleContext(OptSeparatorContext.class,i);\n\t}\n\tpublic ProgContext(ParserRuleContext parent, int invokingState) {\n\t\tsuper(parent, invokingState);\n\t}\n\t@Override public int getRuleIndex() { return RULE_prog; }\n\t@Override\n\tpublic void enterRule(ParseTreeListener listener) {\n\t\tif ( listener instanceof NeodymListener ) ((NeodymListener)listener).enterProg(this);\n\t}\n\t@Override\n\tpublic void exitRule(ParseTreeListener listener) {\n\t\tif ( listener instanceof NeodymListener ) ((NeodymListener)listener).exitProg(this);\n\t}\n}"
}
] | import neodym.antlr.NeodymBaseListener;
import neodym.antlr.NeodymParser.ProgContext;
import org.antlr.v4.runtime.ParserRuleContext;
import org.antlr.v4.runtime.tree.ErrorNode;
import org.antlr.v4.runtime.tree.TerminalNode; | 1,933 | package neodym;
public class NeodymVisitor extends NeodymBaseListener {
@Override | package neodym;
public class NeodymVisitor extends NeodymBaseListener {
@Override | public void enterProg(ProgContext ctx) { | 1 | 2023-10-17 12:28:25+00:00 | 4k |
Primogem-Craft-Development/Primogem-Craft-Fabric | src/main/java/com/primogemstudio/primogemcraft/mixin/MobEffectInstanceMixin.java | [
{
"identifier": "PrimogemCraftBlocks",
"path": "src/main/java/com/primogemstudio/primogemcraft/blocks/PrimogemCraftBlocks.java",
"snippet": "public class PrimogemCraftBlocks {\n public static final DendroCoreBlock DENDRO_CORE_BLOCK = registerWithItem(\"dendro_core_block\", new DendroCoreBlock());\n public static final PrimogemBlock PRIMOGEM_BLOCK = registerWithItem(\"primogem_block\", new PrimogemBlock());\n public static final PrimogemOre PRIMOGEM_ORE = registerWithItem(\"primogem_ore\", new PrimogemOre());\n public static final Block DEEP_SLATE_PRIMOGEM_ORE = registerWithItem(\"deep_slate_primogem_ore\", new Block(BlockBehaviour.Properties.of().instrument(NoteBlockInstrument.BASEDRUM).sound(SoundType.POLISHED_DEEPSLATE).strength(5f, 10f).lightLevel(s -> 1).requiresCorrectToolForDrops()));\n public static final IntertwinedFateBlock INTERTWINED_FATE_BLOCK = registerWithItem(\"intertwined_fate_block\", new IntertwinedFateBlock());\n public static final MoraBunchBlock MORA_BUNCH_BLOCK = registerWithItem(\"mora_bunch_block\", new MoraBunchBlock());\n public static final MoraBlock MORA_BLOCK = registerWithItem(\"mora_block\", new MoraBlock());\n public static final ExquisiteMoraBlock EXQUISITE_MORA_BLOCK = registerWithItem(\"exquisite_mora_block\", new ExquisiteMoraBlock());\n public static final CheapMoraBlock CHEAP_MORA_BLOCK = registerWithItem(\"cheap_mora_block\", new CheapMoraBlock());\n public static final CheapMoraSlabBlock CHEAP_MORA_SLAB_BLOCK = registerWithItem(\"cheap_mora_slab\", new CheapMoraSlabBlock());\n public static final CheapMoraStairBlock CHEAP_MORA_STAIR_BLOCK = registerWithItem(\"cheap_mora_stair\", new CheapMoraStairBlock());\n public static final CheapMoraWallBlock CHEAP_MORA_WALL_BLOCK = registerWithItem(\"cheap_mora_wall\", new CheapMoraWallBlock());\n public static final TeyvatPlanksBlock TEYVAT_PLANKS_BLOCK = registerWithItem(\"teyvat_planks\", new TeyvatPlanksBlock());\n public static final TeyvatPlankSlabBlock TEYVAT_PLANK_SLAB_BLOCK = registerWithItem(\"teyvat_plank_slab\", new TeyvatPlankSlabBlock());\n public static final TeyvatPlankStairBlock TEYVAT_PLANK_STAIR_BLOCK = registerWithItem(\"teyvat_plank_stair\", new TeyvatPlankStairBlock());\n public static final TeyvatPlankFenceBlock TEYVAT_PLANK_FENCE_BLOCK = registerWithItem(\"teyvat_plank_fence\", new TeyvatPlankFenceBlock());\n public static final TeyvatPlankFenceGateBlock TEYVAT_PLANK_FENCE_GATE_BLOCK = registerWithItem(\"teyvat_plank_fence_gate\", new TeyvatPlankFenceGateBlock());\n public static final BlueTeyvatPlanksBlock BLUE_TEYVAT_PLANKS_BLOCK = registerWithItem(\"blue_teyvat_planks\", new BlueTeyvatPlanksBlock());\n public static final TeyvatPlankSlabBlock BLUE_TEYVAT_PLANK_SLAB_BLOCK = registerWithItem(\"blue_teyvat_plank_slab\", new TeyvatPlankSlabBlock());\n public static final TeyvatPlankStairBlock BLUE_TEYVAT_PLANK_STAIR_BLOCK = registerWithItem(\"blue_teyvat_plank_stair\", new TeyvatPlankStairBlock());\n public static final TeyvatPlankFenceBlock BLUE_TEYVAT_PLANK_FENCE_BLOCK = registerWithItem(\"blue_teyvat_plank_fence\", new TeyvatPlankFenceBlock());\n public static final TeyvatPlankFenceGateBlock BLUE_TEYVAT_PLANK_FENCE_GATE_BLOCK = registerWithItem(\"blue_teyvat_plank_fence_gate\", new TeyvatPlankFenceGateBlock());\n public static final PinkTeyvatPlanksBlock PINK_TEYVAT_PLANKS_BLOCK = registerWithItem(\"pink_teyvat_planks\", new PinkTeyvatPlanksBlock());\n public static final TeyvatPlankSlabBlock PINK_TEYVAT_PLANK_SLAB_BLOCK = registerWithItem(\"pink_teyvat_plank_slab\", new TeyvatPlankSlabBlock());\n public static final TeyvatPlankStairBlock PINK_TEYVAT_PLANK_STAIR_BLOCK = registerWithItem(\"pink_teyvat_plank_stair\", new TeyvatPlankStairBlock());\n public static final TeyvatPlankFenceBlock PINK_TEYVAT_PLANK_FENCE_BLOCK = registerWithItem(\"pink_teyvat_plank_fence\", new TeyvatPlankFenceBlock());\n public static final TeyvatPlankFenceGateBlock PINK_TEYVAT_PLANK_FENCE_GATE_BLOCK = registerWithItem(\"pink_teyvat_plank_fence_gate\", new TeyvatPlankFenceGateBlock());\n public static final CharCoalBlock CHAR_COAL_BLOCK = registerWithItem(\"charcoal_block\", new CharCoalBlock());\n public static final RustedPlankBlock RUSTED_PLANK_BLOCK = registerWithItem(\"rusted_plank\", new RustedPlankBlock());\n public static final RustedPlankStairsBlock RUSTED_PLANK_STAIR_BLOCK = registerWithItem(\"rusted_plank_stairs\", new RustedPlankStairsBlock());\n public static final RustIronBarBlock RUST_IRON_BAR_BLOCK = registerWithItem(\"rust_iron_bar\", new RustIronBarBlock());\n public static final DendroCorePlanksBlock DENDRO_CORE_PLANKS_BLOCK = registerWithItem(\"dendro_core_planks\", new DendroCorePlanksBlock());\n public static final DendroCorePlankSlabBlock DENDRO_CORE_PLANK_SLAB_BLOCK = registerWithItem(\"dendro_core_plank_slab\", new DendroCorePlankSlabBlock());\n public static final DendroCorePlankStairsBlock DENDRO_CORE_PLANK_STAIRS_BLOCK = registerWithItem(\"dendro_core_plank_stairs\", new DendroCorePlankStairsBlock());\n public static final DendroCorePlankPressurePlateBlock DENDRO_CORE_PLANK_PRESSURE_PLATE_BLOCK = registerWithItem(\"dendro_core_plank_pressure_plate\", new DendroCorePlankPressurePlateBlock());\n public static final DendroCodePlankButtonBlock DENDRO_CORE_PLANK_BUTTON_BLOCK = registerWithItem(\"dendro_core_plank_button\", new DendroCodePlankButtonBlock());\n public static final DendroCorePlanksFenceGateBlock DENDRO_CORE_PLANK_FENCE_GATE_BLOCK = registerWithItem(\"dendro_core_plank_fence_gate\", new DendroCorePlanksFenceGateBlock());\n public static final DendroCorePlankFenceBlock DENDRO_CORE_PLANK_FENCE_BLOCK = registerWithItem(\"dendro_core_plank_fence\", new DendroCorePlankFenceBlock());\n public static final VayudaTurquoiseGemstoneOre VAYUDA_TURQUOISE_GEMSTONE_ORE_BLOCK = registerWithItem(\"vayuda_turquoise_gemstone_ore\", new VayudaTurquoiseGemstoneOre());\n public static final VayudaTurquoiseGemstoneBlock VAYUDA_TURQUOISE_GEMSTONE_BLOCK = registerWithItem(\"vayuda_turquoise_gemstone_block\", new VayudaTurquoiseGemstoneBlock());\n public static final VajradaAmethystOre VAJRADA_AMETHYST_ORE_BLOCK = registerWithItem(\"vajrada_amethyst_ore\", new VajradaAmethystOre());\n public static final VajradaAmethystBlock VAJRADA_AMETHYST_BLOCK = registerWithItem(\"vajrada_amethyst_block\", new VajradaAmethystBlock());\n public static final March7thStatueBlock MARCH_7TH_STATUE_BLOCK = registerWithItem(\"march_7th_statue\", new March7thStatueBlock());\n public static final NagadusEmeraldOreBlock NAGADUS_EMERALD_ORE_BLOCK = registerWithItem(\"nagadus_emerald_ore\", new NagadusEmeraldOreBlock());\n public static final NagadusEmeraldBlock NAGADUS_EMERALD_BLOCK = registerWithItem(\"nagadus_emerald_block\", new NagadusEmeraldBlock());\n public static final BlessingOfDendroBlock BLESSING_OF_DENDRO_BLOCK = registerWithItem(\"blessing_of_dendro\", new BlessingOfDendroBlock());\n public static final AgnidusAgateBlock AGNIDUS_AGATE_BLOCK = registerWithItem(\"agnidus_agate_block\", new AgnidusAgateBlock());\n public static final AgnidusAgateOreBlock AGNIDUS_AGATE_ORE_BLOCK = registerWithItem(\"agnidus_agate_ore\", new AgnidusAgateOreBlock());\n public static final NetherrackFarmlandBlock NETHERRACK_FARMLAND_BLOCK = registerWithItem(\"netherrack_farmland\", new NetherrackFarmlandBlock());\n @Environment(EnvType.CLIENT)\n public static void initRenderLayers() {\n BlockRenderLayerMap.INSTANCE.putBlocks(RenderType.cutout(), PrimogemCraftBlocks.MORA_BUNCH_BLOCK, PrimogemCraftBlocks.CHEAP_MORA_WALL_BLOCK, PrimogemCraftBlocks.RUSTED_PLANK_STAIR_BLOCK);\n }\n\n private static <T extends Block> T registerWithItem(String id, T block) {\n var rel = new ResourceLocation(MOD_ID, id);\n Registry.register(BuiltInRegistries.ITEM, rel, new BlockItem(block, new Item.Properties()));\n return Registry.register(BuiltInRegistries.BLOCK, rel, block);\n }\n}"
},
{
"identifier": "ABNORMAL_DISEASE",
"path": "src/main/java/com/primogemstudio/primogemcraft/effects/PrimogemCraftMobEffects.java",
"snippet": "public static final AbnormalDiseaseMobEffect ABNORMAL_DISEASE = register(\"abnormal_disease\", new AbnormalDiseaseMobEffect());"
}
] | import com.primogemstudio.primogemcraft.blocks.PrimogemCraftBlocks;
import net.minecraft.core.BlockPos;
import net.minecraft.sounds.SoundEvents;
import net.minecraft.sounds.SoundSource;
import net.minecraft.world.effect.MobEffect;
import net.minecraft.world.effect.MobEffectInstance;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.level.Level;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.Unique;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import static com.primogemstudio.primogemcraft.effects.PrimogemCraftMobEffects.ABNORMAL_DISEASE; | 2,745 | package com.primogemstudio.primogemcraft.mixin;
@Mixin(MobEffectInstance.class)
public class MobEffectInstanceMixin {
@Unique
private int tick = 0;
@Inject(method = "applyEffect", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/effect/MobEffect;applyEffectTick(Lnet/minecraft/world/entity/LivingEntity;I)V"))
private void applyEffect(LivingEntity entity, CallbackInfo ci) {
if (effect == ABNORMAL_DISEASE) {
var level = entity.level();
if (!level.isClientSide) {
if (tick == 160) {
level.explode(null, entity.getX(), entity.getY(), entity.getZ(), 8.0F, Level.ExplosionInteraction.TNT);
level.playSound(null, BlockPos.containing(entity.getX(), entity.getY(), entity.getZ()), SoundEvents.GLASS_BREAK, SoundSource.NEUTRAL, 10.0F, 0.5F); | package com.primogemstudio.primogemcraft.mixin;
@Mixin(MobEffectInstance.class)
public class MobEffectInstanceMixin {
@Unique
private int tick = 0;
@Inject(method = "applyEffect", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/effect/MobEffect;applyEffectTick(Lnet/minecraft/world/entity/LivingEntity;I)V"))
private void applyEffect(LivingEntity entity, CallbackInfo ci) {
if (effect == ABNORMAL_DISEASE) {
var level = entity.level();
if (!level.isClientSide) {
if (tick == 160) {
level.explode(null, entity.getX(), entity.getY(), entity.getZ(), 8.0F, Level.ExplosionInteraction.TNT);
level.playSound(null, BlockPos.containing(entity.getX(), entity.getY(), entity.getZ()), SoundEvents.GLASS_BREAK, SoundSource.NEUTRAL, 10.0F, 0.5F); | level.setBlock(entity.blockPosition(), PrimogemCraftBlocks.PRIMOGEM_ORE.defaultBlockState(), 3); | 0 | 2023-10-15 08:07:06+00:00 | 4k |
turtleisaac/PokEditor | src/main/java/io/github/turtleisaac/pokeditor/gui/sheets/tables/FormatModel.java | [
{
"identifier": "DataManager",
"path": "src/main/java/io/github/turtleisaac/pokeditor/DataManager.java",
"snippet": "public class DataManager\n{\n public static final String SHEET_STRINGS_PATH = \"pokeditor/sheet_strings\";\n\n public static DefaultSheetPanel<PersonalData, ?> createPersonalSheet(PokeditorManager manager, NintendoDsRom rom)\n {\n List<TextBankData> textData = DataManager.getData(rom, TextBankData.class);\n List<PersonalData> data = DataManager.getData(rom, PersonalData.class);\n return new DefaultSheetPanel<>(manager, new PersonalTable(data, textData));\n }\n\n public static DefaultSheetPanel<PersonalData, ?> createTmCompatibilitySheet(PokeditorManager manager, NintendoDsRom rom)\n {\n List<TextBankData> textData = DataManager.getData(rom, TextBankData.class);\n List<PersonalData> data = DataManager.getData(rom, PersonalData.class);\n DefaultSheetPanel<PersonalData, ?> sheetPanel = new DefaultSheetPanel<>(manager, new TmCompatibilityTable(data, textData));\n// String[] moveNames = textData.get(TextFiles.MOVE_NAMES.getValue()).getStringList().toArray(String[]::new);\n// sheetPanel.thing(new ComboBoxCellEditor(moveNames));\n return sheetPanel;\n }\n\n public static DefaultSheetPanel<EvolutionData, ?> createEvolutionSheet(PokeditorManager manager, NintendoDsRom rom)\n {\n List<TextBankData> textData = DataManager.getData(rom, TextBankData.class);\n List<EvolutionData> data = DataManager.getData(rom, EvolutionData.class);\n return new DefaultSheetPanel<>(manager, new EvolutionsTable(data, textData));\n }\n\n public static DefaultSheetPanel<LearnsetData, ?> createLearnsetSheet(PokeditorManager manager, NintendoDsRom rom)\n {\n List<TextBankData> textData = DataManager.getData(rom, TextBankData.class);\n List<LearnsetData> data = DataManager.getData(rom, LearnsetData.class);\n return new DefaultSheetPanel<>(manager, new LearnsetsTable(data, textData));\n }\n\n public static DefaultSheetPanel<MoveData, ?> createMoveSheet(PokeditorManager manager, NintendoDsRom rom)\n {\n List<TextBankData> textData = DataManager.getData(rom, TextBankData.class);\n List<MoveData> data = DataManager.getData(rom, MoveData.class);\n return new DefaultSheetPanel<>(manager, new MovesTable(data, textData));\n }\n\n public static DefaultDataEditorPanel<PokemonSpriteData, ?> createPokemonSpriteEditor(PokeditorManager manager, NintendoDsRom rom)\n {\n List<TextBankData> textData = DataManager.getData(rom, TextBankData.class);\n List<PokemonSpriteData> data = DataManager.getData(rom, PokemonSpriteData.class);\n return new DefaultDataEditorPanel<>(manager, new PokemonSpriteEditor(data, textData));\n }\n\n public static DefaultDataEditorPanel<GenericScriptData, ?> createFieldScriptEditor(PokeditorManager manager, NintendoDsRom rom)\n {\n List<TextBankData> textData = DataManager.getData(rom, TextBankData.class);\n List<GenericScriptData> data = DataManager.getData(rom, GenericScriptData.class);\n return new DefaultDataEditorPanel<>(manager, new FieldScriptEditor(data, textData));\n }\n\n private static final Injector injector = Guice.createInjector(\n new PersonalModule(),\n new LearnsetsModule(),\n new EvolutionsModule(),\n new TrainersModule(),\n new MovesModule(),\n new SinnohEncountersModule(),\n new JohtoEncountersModule(),\n new ItemsModule(),\n new TextBankModule(),\n new PokemonSpriteModule());\n\n @SuppressWarnings(\"unchecked\")\n public static <E extends GenericFileData> GenericParser<E> getParser(Class<E> eClass)\n {\n if (eClass != GenericScriptData.class) {\n ParameterizedType type = Types.newParameterizedType(GenericParser.class, eClass);\n return (GenericParser<E>) injector.getInstance(Key.get(TypeLiteral.get(type)));\n } else {\n return (GenericParser<E>) new ScriptParser();\n }\n }\n\n private static final Map<Class<? extends GenericFileData>, List<? extends GenericFileData>> dataMap = new HashMap<>();\n private static final Map<GameCodeBinaries, CodeBinary> codeBinaries = new HashMap<>();\n\n @SuppressWarnings(\"unchecked\")\n public static <E extends GenericFileData> List<E> getData(NintendoDsRom rom, Class<E> eClass)\n {\n if (dataMap.containsKey(eClass))\n return (List<E>) dataMap.get(eClass);\n\n GenericParser<E> parser = DataManager.getParser(eClass);\n Map<GameFiles, Narc> input = new HashMap<>();\n for (GameFiles gameFile : parser.getRequirements())\n {\n input.put(gameFile, new Narc(rom.getFileByName(gameFile.getPath())));\n }\n\n List<E> data = parser.generateDataList(input, codeBinaries);\n dataMap.put(eClass, data);\n\n return data;\n }\n\n public static <E extends GenericFileData> void saveData(NintendoDsRom rom, Class<E> eClass)\n {\n if (!dataMap.containsKey(eClass))\n return;\n\n GenericParser<E> parser = DataManager.getParser(eClass);\n Map<GameFiles, Narc> map = parser.processDataList(getData(rom, eClass), codeBinaries);\n for (GameFiles gameFile : map.keySet())\n {\n rom.setFileByName(gameFile.getPath(), map.get(gameFile).save());\n }\n }\n\n @SuppressWarnings(\"unchecked\")\n public static <E extends GenericFileData> void resetData(NintendoDsRom rom, Class<E> eClass)\n {\n if (!dataMap.containsKey(eClass))\n return;\n\n List<E> list = (List<E>) dataMap.get(eClass);\n list.clear();\n dataMap.remove(eClass);\n List<E> newList = getData(rom, eClass);\n dataMap.remove(newList);\n\n list.addAll(newList);\n dataMap.put(eClass, list);\n }\n\n public static void codeBinarySetup(NintendoDsRom rom)\n {\n MainCodeFile arm9 = rom.loadArm9();\n codeBinaries.put(GameCodeBinaries.ARM9, arm9);\n// codeBinaries.put(GameCodeBinaries.ARM7, rom.loadArm7());\n\n MemBuf.MemBufWriter writer = arm9.getPhysicalAddressBuffer().writer();\n int pos = writer.getPosition();\n writer.setPosition(0xBB4); //todo account for DP if I ever add back support\n writer.writeInt(0);\n writer.setPosition(pos);\n }\n\n public static void saveCodeBinaries(NintendoDsRom rom, List<GameCodeBinaries> codeBinaries)\n {\n for (GameCodeBinaries codeBinary : codeBinaries)\n {\n CodeBinary binary = DataManager.codeBinaries.get(codeBinary);\n binary.lock();\n try {\n if(codeBinary == GameCodeBinaries.ARM9)\n {\n rom.setArm9(binary.getData());\n }\n }\n finally {\n binary.unlock();\n }\n }\n }\n\n static class PersonalModule extends AbstractModule\n {\n @Override\n protected void configure()\n {\n bind(new TypeLiteral<GenericParser<PersonalData>>() {})\n .to(PersonalParser.class)\n .in(Scopes.SINGLETON);\n }\n }\n\n static class LearnsetsModule extends AbstractModule {\n @Override\n protected void configure()\n {\n bind(new TypeLiteral<GenericParser<LearnsetData>>() {})\n .to(LearnsetParser.class)\n .in(Scopes.SINGLETON);\n }\n }\n\n static class EvolutionsModule extends AbstractModule {\n @Override\n protected void configure()\n {\n bind(new TypeLiteral<GenericParser<EvolutionData>>() {})\n .to(EvolutionParser.class)\n .in(Scopes.SINGLETON);\n }\n }\n\n static class TrainersModule extends AbstractModule {\n @Override\n protected void configure()\n {\n bind(new TypeLiteral<GenericParser<TrainerData>>() {})\n .to(TrainerParser.class)\n .in(Scopes.SINGLETON);\n }\n }\n\n static class MovesModule extends AbstractModule {\n @Override\n protected void configure()\n {\n bind(new TypeLiteral<GenericParser<MoveData>>() {})\n .to(MoveParser.class)\n .in(Scopes.SINGLETON);\n }\n }\n\n static class SinnohEncountersModule extends AbstractModule {\n @Override\n protected void configure()\n {\n bind(new TypeLiteral<GenericParser<SinnohEncounterData>>() {})\n .to(SinnohEncounterParser.class)\n .in(Scopes.SINGLETON);\n }\n }\n\n static class JohtoEncountersModule extends AbstractModule {\n @Override\n protected void configure()\n {\n bind(new TypeLiteral<GenericParser<JohtoEncounterData>>() {})\n .to(JohtoEncounterParser.class)\n .in(Scopes.SINGLETON);\n }\n }\n\n static class ItemsModule extends AbstractModule {\n @Override\n protected void configure()\n {\n bind(new TypeLiteral<GenericParser<ItemData>>() {})\n .to(ItemParser.class)\n .in(Scopes.SINGLETON);\n }\n }\n\n static class TextBankModule extends AbstractModule {\n @Override\n protected void configure()\n {\n bind(new TypeLiteral<GenericParser<TextBankData>>() {})\n .to(TextBankParser.class)\n .in(Scopes.SINGLETON);\n }\n }\n\n static class PokemonSpriteModule extends AbstractModule {\n @Override\n protected void configure()\n {\n bind(new TypeLiteral<GenericParser<PokemonSpriteData>>() {})\n .to(PokemonSpriteParser.class)\n .in(Scopes.SINGLETON);\n }\n }\n}"
},
{
"identifier": "EditorDataModel",
"path": "src/main/java/io/github/turtleisaac/pokeditor/gui/editors/data/EditorDataModel.java",
"snippet": "public interface EditorDataModel<E extends Enum<E>>\n{\n Object getValueFor(int entryIdx, E property);\n void setValueFor(Object aValue, int entryIdx, E property);\n int getEntryCount();\n String getEntryName(int entryIdx);\n}"
},
{
"identifier": "CellTypes",
"path": "src/main/java/io/github/turtleisaac/pokeditor/gui/sheets/tables/cells/CellTypes.java",
"snippet": "public enum CellTypes\n{\n INTEGER,\n STRING,\n COMBO_BOX,\n COLORED_COMBO_BOX,\n BITFIELD_COMBO_BOX,\n CHECKBOX,\n CUSTOM;\n\n\n public interface CustomCellFunctionSupplier {\n\n TableCellEditor getEditor(String[]... strings);\n TableCellRenderer getRenderer(String[]... strings);\n }\n}"
}
] | import io.github.turtleisaac.pokeditor.DataManager;
import io.github.turtleisaac.pokeditor.formats.GenericFileData;
import io.github.turtleisaac.pokeditor.formats.text.TextBankData;
import io.github.turtleisaac.pokeditor.gui.editors.data.EditorDataModel;
import io.github.turtleisaac.pokeditor.gui.sheets.tables.cells.CellTypes;
import javax.swing.table.AbstractTableModel;
import java.util.List;
import java.util.ResourceBundle; | 3,180 | package io.github.turtleisaac.pokeditor.gui.sheets.tables;
public abstract class FormatModel<G extends GenericFileData, E extends Enum<E>> extends AbstractTableModel implements EditorDataModel<E>
{
private final List<G> data;
private final List<TextBankData> textBankData;
private final String[] columnNames;
private boolean copyPasteModeEnabled;
public FormatModel(List<G> data, List<TextBankData> textBankData)
{
this.data = data;
this.textBankData = textBankData;
this.columnNames = new String[getColumnCount() + getNumFrozenColumns()];
ResourceBundle bundle = ResourceBundle.getBundle(DataManager.SHEET_STRINGS_PATH);
int lastValid = 0;
for (int idx = 0; idx < columnNames.length; idx++)
{
int adjusted = idx-getNumFrozenColumns();
String columnNameKey = getColumnNameKey(adjusted);
if (columnNameKey == null)
{
columnNames[idx] = bundle.getString(getColumnNameKey(adjusted % (lastValid + 1))); // this will cause columns to repeat as much as needed for the sheets which need them
}
else {
columnNames[idx] = bundle.getString(columnNameKey);
lastValid = adjusted;
}
}
copyPasteModeEnabled = false;
}
public int getNumFrozenColumns() {
return 0;
}
public abstract String getColumnNameKey(int columnIndex);
@Override
public String getColumnName(int column)
{
return columnNames[column + getNumFrozenColumns()];
}
public void toggleCopyPasteMode(boolean state)
{
copyPasteModeEnabled = state;
}
@Override
public boolean isCellEditable(int rowIndex, int columnIndex)
{
return !copyPasteModeEnabled;
}
@Override
public int getRowCount()
{
return getEntryCount();
}
@Override
public int getEntryCount()
{
return data.size();
}
@Override
public String getEntryName(int entryIdx)
{
return "" + entryIdx;
}
public List<G> getData()
{
return data;
}
public List<TextBankData> getTextBankData()
{
return textBankData;
}
| package io.github.turtleisaac.pokeditor.gui.sheets.tables;
public abstract class FormatModel<G extends GenericFileData, E extends Enum<E>> extends AbstractTableModel implements EditorDataModel<E>
{
private final List<G> data;
private final List<TextBankData> textBankData;
private final String[] columnNames;
private boolean copyPasteModeEnabled;
public FormatModel(List<G> data, List<TextBankData> textBankData)
{
this.data = data;
this.textBankData = textBankData;
this.columnNames = new String[getColumnCount() + getNumFrozenColumns()];
ResourceBundle bundle = ResourceBundle.getBundle(DataManager.SHEET_STRINGS_PATH);
int lastValid = 0;
for (int idx = 0; idx < columnNames.length; idx++)
{
int adjusted = idx-getNumFrozenColumns();
String columnNameKey = getColumnNameKey(adjusted);
if (columnNameKey == null)
{
columnNames[idx] = bundle.getString(getColumnNameKey(adjusted % (lastValid + 1))); // this will cause columns to repeat as much as needed for the sheets which need them
}
else {
columnNames[idx] = bundle.getString(columnNameKey);
lastValid = adjusted;
}
}
copyPasteModeEnabled = false;
}
public int getNumFrozenColumns() {
return 0;
}
public abstract String getColumnNameKey(int columnIndex);
@Override
public String getColumnName(int column)
{
return columnNames[column + getNumFrozenColumns()];
}
public void toggleCopyPasteMode(boolean state)
{
copyPasteModeEnabled = state;
}
@Override
public boolean isCellEditable(int rowIndex, int columnIndex)
{
return !copyPasteModeEnabled;
}
@Override
public int getRowCount()
{
return getEntryCount();
}
@Override
public int getEntryCount()
{
return data.size();
}
@Override
public String getEntryName(int entryIdx)
{
return "" + entryIdx;
}
public List<G> getData()
{
return data;
}
public List<TextBankData> getTextBankData()
{
return textBankData;
}
| protected CellTypes getCellType(int columnIndex) | 2 | 2023-10-15 05:00:57+00:00 | 4k |
dashorst/funwithflags | src/main/java/fwf/web/FunWithFlagsWebSocket.java | [
{
"identifier": "ApplicationStatus",
"path": "src/main/java/fwf/ApplicationStatus.java",
"snippet": "public interface ApplicationStatus {\n\n int numberOfGames();\n}"
},
{
"identifier": "FunWithFlagsGame",
"path": "src/main/java/fwf/FunWithFlagsGame.java",
"snippet": "@TemplateGlobal\npublic interface FunWithFlagsGame {\n public void registerPlayer(Session session, String name);\n\n public void unregisterPlayer(Session session);\n\n public void guess(Player player, int turnNumber, Country country);\n\n public void destroyGame(Game game);\n\n public void tick();\n}"
},
{
"identifier": "Game",
"path": "src/main/java/fwf/game/Game.java",
"snippet": "@Dependent\npublic class Game {\n @Inject\n Instance<Turn> turnFactory;\n\n @Inject\n Event<GameFinished> gameFinished;\n\n @Inject\n Event<TurnStarted> turnStarted;\n\n @Inject\n Event<TurnSwitched> turnSwitched;\n\n @Inject\n Event<TurnFinished> turnFinished;\n\n @Inject\n CountryRepository countryRepository;\n\n private List<Player> players = Collections.emptyList();\n private List<Turn> turns = new ArrayList<>();\n\n private String playerNames;\n \n private int secondsPerResult;\n\n private boolean gameOver = false;\n\n private Turn currentTurn = null;\n\n public Game() {\n }\n\n public void init(List<Player> playersInLobby, int numberOfTurns, int secondsPerTurn, int secondsPerResult) {\n this.players = playersInLobby;\n this.playerNames = players.stream().map(Player::name).toList().toString();\n this.secondsPerResult = secondsPerResult;\n\n var countries = new ArrayList<>(countryRepository.countries());\n Collections.shuffle(countries);\n\n for (int i = 0; i < numberOfTurns; i++) {\n var turn = turnFactory.get();\n\n turn.init(this, i + 1, countries.get(i), secondsPerTurn, secondsPerResult);\n turns.add(turn);\n }\n currentTurn = turns.get(0);\n turnStarted.fire(new TurnStarted(this, currentTurn));\n }\n\n public List<Turn> turns() {\n return turns;\n }\n\n public boolean isGameOver() {\n return gameOver;\n }\n\n public int numberOfTurns() {\n return turns.size();\n }\n\n public int turnNumber() {\n if (currentTurn == null)\n return numberOfTurns();\n return turns.indexOf(currentTurn) + 1;\n }\n\n public Collection<Player> players() {\n return Collections.unmodifiableCollection(players);\n }\n\n public List<Score> scores() {\n var scores = new ArrayList<Score>();\n for (Player player : players) {\n int score = 0;\n for (Turn turn : turns) {\n score += turn.scoreForPlayer(player);\n }\n scores.add(new Score(this, player, score));\n }\n Collections.sort(scores, Comparator.comparing(Score::score, Comparator.reverseOrder()));\n return scores;\n }\n\n public Optional<Turn> currentTurn() {\n return Optional.ofNullable(currentTurn);\n }\n\n // todo observe ClockTick event\n public void onTick() {\n if (gameOver)\n return;\n\n if (currentTurn == null)\n return;\n\n if (currentTurn.isDone()) {\n if (!currentTurn.isResultDone()) {\n // fire turn finished only once\n if (currentTurn.resultsSecondsLeft() == secondsPerResult)\n turnFinished.fire(new TurnFinished(this, currentTurn));\n\n currentTurn.tick();\n Log.debugf(\"Game ticked: %s, turn: #%d, results left: %ds\",\n players().stream().map(Player::name).toList(), turnNumber(), currentTurn.resultsSecondsLeft());\n } else {\n var previousTurn = currentTurn;\n var nextTurn = turns.stream().filter(t -> !t.isDone()).findFirst();\n if (nextTurn.isPresent()) {\n currentTurn = nextTurn.get();\n turnSwitched.fire(new TurnSwitched(this, previousTurn, currentTurn));\n turnStarted.fire(new TurnStarted(this, currentTurn));\n } else {\n gameOver = true;\n gameFinished.fire(new GameFinished(this, \"Game over\"));\n }\n }\n } else {\n Log.debugf(\"Game ticked: %s, turn: #%d, seconds left: %ds\", players().stream().map(Player::name).toList(),\n turnNumber(), currentTurn.secondsLeft());\n currentTurn.tick();\n }\n }\n\n void onPlayerUnregistered(@Observes PlayerUnregistered event) {\n var playerToRemove = event.player();\n if (players.remove(playerToRemove)) {\n if (players.size() <= 1) {\n gameOver = true;\n // fire game over\n gameFinished.fire(new GameFinished(this, \"Last player standing\"));\n }\n }\n }\n\n void onGameDestroyed(@Observes GameDestroyed event) {\n for (Turn turn : event.game().turns) {\n turnFactory.destroy(turn);\n }\n event.game().turns.clear();\n }\n\n @Override\n public String toString() {\n return playerNames + \", turn \" + turnNumber();\n }\n}"
},
{
"identifier": "Lobby",
"path": "src/main/java/fwf/lobby/Lobby.java",
"snippet": "@ApplicationScoped\npublic class Lobby {\n @Inject\n Event<LobbyFilled> lobbyFilledEvent;\n\n @Inject\n Configuration configuration;\n\n private BlockingQueue<Player> waitingPlayers = new LinkedBlockingDeque<>();\n\n public List<Player> waitingPlayers() {\n return new ArrayList<>(waitingPlayers);\n }\n\n void clear() {\n waitingPlayers.clear();\n }\n\n void registerPlayer(@Observes PlayerRegistered playerRegistered) {\n Log.infof(\"Player '%s' registered in lobby\", playerRegistered.player().name());\n waitingPlayers.offer(playerRegistered.player());\n }\n\n void unregisterPlayer(@Observes PlayerUnregistered playerUnregistered) {\n Log.infof(\"Player '%s' unregistered in lobby\", playerUnregistered.player().name());\n waitingPlayers.remove(playerUnregistered.player());\n }\n\n @Scheduled(every = \"1s\")\n void checkLobbyFilled() {\n int numberOfPlayersPerGame = configuration.numberOfPlayersPerGame();\n if (waitingPlayers.size() < numberOfPlayersPerGame)\n return;\n\n var gamePlayers = new ArrayList<Player>();\n int added = waitingPlayers.drainTo(gamePlayers, numberOfPlayersPerGame);\n if (added < numberOfPlayersPerGame) {\n // re-add the picked players to the waiting list\n waitingPlayers.addAll(gamePlayers);\n return;\n }\n lobbyFilledEvent.fire(new LobbyFilled(gamePlayers));\n }\n}"
},
{
"identifier": "Player",
"path": "src/main/java/fwf/player/Player.java",
"snippet": "@Dependent\npublic class Player {\n private String id;\n private Session session;\n private String name;\n\n public void init(Session session, String name) {\n this.session = session;\n this.name = name;\n this.id = session.getId() + \"|\" + name;\n }\n\n public Session session() {\n return session;\n }\n\n public String name() {\n return name;\n }\n\n @Override\n public String toString() {\n return id;\n }\n\n @Override\n public int hashCode() {\n return Objects.hashCode(session);\n }\n\n @Override\n public boolean equals(Object obj) {\n if (obj instanceof Player other) {\n return Objects.equals(this.session(), other.session());\n }\n return false;\n }\n}"
},
{
"identifier": "Turn",
"path": "src/main/java/fwf/turn/Turn.java",
"snippet": "public class Turn {\n @Inject\n Event<TurnClockTicked> clockTicked;\n\n @Inject\n Event<TurnGuessRecorded> guessRecorded;\n\n private Game game;\n private int turnNumber;\n private Country countryToGuess;\n private boolean done = false;\n private boolean resultDone = false;\n\n private Map<Player, Guess> guesses = new ConcurrentHashMap<>();\n private int turnTicksRemaining;\n private int resultTicksRemaining;\n\n public void init(Game game, int turnNumber, Country country, int secondsPerTurn, int secondsPerResult) {\n this.game = Objects.requireNonNull(game);\n this.turnNumber = turnNumber;\n this.countryToGuess = Objects.requireNonNull(country);\n this.turnTicksRemaining = secondsPerTurn;\n this.resultTicksRemaining = secondsPerResult;\n }\n\n public void guess(@Observes PlayerGuessed event) {\n var turn = event.turn();\n var game = event.game();\n var player = event.player();\n\n if (turn.isDone()) {\n Log.infof(\"Game %s turn %s is done, guess for player %s not recorded\", game.toString(), turn.turnNumber(), event.player().name());\n return;\n }\n\n if (!game.players().contains(player)) {\n Log.infof(\"Player %s is not part of the game %s, guess not recorded\", player, game);\n return;\n }\n\n var guess = new Guess(player, turn, game, event.country());\n turn.guesses.put(player, guess);\n\n guessRecorded.fire(new TurnGuessRecorded(game, turn, player, guess));\n }\n\n public int scoreForPlayer(Player player) {\n if (!done)\n return 0;\n\n var guess = guesses.get(player);\n return Optional.ofNullable(guess).map(Guess::guessedCountry).filter(g -> countryToGuess.equals(g)).map(g -> 1)\n .orElse(0);\n }\n\n public void tick() {\n if (game == null)\n return;\n\n turnTicksRemaining = Math.max(-1, turnTicksRemaining - 1);\n if (done) {\n resultTicksRemaining = Math.max(-1, resultTicksRemaining - 1);\n resultDone = resultTicksRemaining == -1;\n }\n done = turnTicksRemaining == -1;\n Log.debugf(\"Game turn ticked: %s, secondsLeft: %d\", game.players().stream().map(Player::name).toList(),\n turnTicksRemaining);\n clockTicked.fire(new TurnClockTicked(game, this, secondsLeft()));\n }\n\n public int turnNumber() {\n return turnNumber;\n }\n\n public Collection<Guess> guesses() {\n return guesses.values();\n }\n\n public Country countryToGuess() {\n return countryToGuess;\n }\n\n public int secondsLeft() {\n return Math.max(0, turnTicksRemaining);\n }\n\n public int resultsSecondsLeft() {\n return Math.max(0, resultTicksRemaining);\n }\n\n public boolean isDone() {\n return done;\n }\n\n public boolean isResultDone() {\n return resultDone;\n }\n\n @Override\n public String toString() {\n return String.format(\"Turn %d of game %s: %d seconds remaining\", turnNumber, game, secondsLeft());\n }\n}"
}
] | import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import fwf.ApplicationStatus;
import fwf.FunWithFlagsGame;
import fwf.country.Country;
import fwf.game.Game;
import fwf.game.GameFinished;
import fwf.game.GameStarted;
import fwf.guess.Guess;
import fwf.lobby.Lobby;
import fwf.lobby.LobbyFilled;
import fwf.player.Player;
import fwf.player.PlayerRegistered;
import fwf.player.PlayerUnregistered;
import fwf.turn.Turn;
import fwf.turn.TurnClockTicked;
import fwf.turn.TurnFinished;
import fwf.turn.TurnGuessRecorded;
import fwf.turn.TurnStarted;
import io.quarkus.logging.Log;
import io.quarkus.qute.CheckedTemplate;
import io.quarkus.qute.TemplateInstance;
import io.quarkus.scheduler.Scheduled;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.enterprise.event.Observes;
import jakarta.inject.Inject;
import jakarta.websocket.OnClose;
import jakarta.websocket.OnError;
import jakarta.websocket.OnOpen;
import jakarta.websocket.Session;
import jakarta.websocket.server.PathParam;
import jakarta.websocket.server.ServerEndpoint; | 2,968 | package fwf.web;
@ServerEndpoint("/game/{player}")
@ApplicationScoped
public class FunWithFlagsWebSocket {
@CheckedTemplate
public static class Templates {
public static native TemplateInstance submissionPartial(Country choice);
| package fwf.web;
@ServerEndpoint("/game/{player}")
@ApplicationScoped
public class FunWithFlagsWebSocket {
@CheckedTemplate
public static class Templates {
public static native TemplateInstance submissionPartial(Country choice);
| public static native TemplateInstance game$countdownPartial(Player receiver, Game game, Turn turn); | 5 | 2023-10-17 19:10:37+00:00 | 4k |
Amanastel/Hotel-Management-Microservices | User/src/main/java/com/lcwd/user/service/Service/service/Impl/WalletServicesImpl.java | [
{
"identifier": "TransactionType",
"path": "User/src/main/java/com/lcwd/user/service/Service/entities/TransactionType.java",
"snippet": "public enum TransactionType {\n DEBIT, CREDIT\n}"
},
{
"identifier": "Transactions",
"path": "User/src/main/java/com/lcwd/user/service/Service/entities/Transactions.java",
"snippet": "@Entity\n@Getter\n@Setter\n@AllArgsConstructor\n@NoArgsConstructor\npublic class Transactions {\n @Id\n @GeneratedValue(strategy= GenerationType.AUTO)\n private Integer transactionId;\n\n// @JsonFormat(pattern=\"yyyy-MM-dd-HH-mm-ss\")\n private LocalDateTime transactionDate;\n\n @DecimalMin(\"0.0\")\n private Float amount;\n\n\n private Float CurrentBalance;\n\n @Enumerated(EnumType.STRING)\n private TransactionType type;\n}"
},
{
"identifier": "User",
"path": "User/src/main/java/com/lcwd/user/service/Service/entities/User.java",
"snippet": "@Entity\n@Getter\n@Setter\n@NoArgsConstructor\n@AllArgsConstructor\n@Table(name = \"micro_users\")\npublic class User {\n @Id\n @Column(name = \"ID\")\n private String userId;\n @Column(name = \"NAME\")\n private String name;\n @Column(name = \"EMAIL\")\n private String email;\n @Column(name = \"ABOUT\")\n private String about;\n @Transient\n private List<Rating> ratings = new ArrayList<>();\n @OneToMany(mappedBy = \"user\", cascade = CascadeType.ALL)\n private List<Booking> bookings = new ArrayList<>();\n\n @OneToOne(mappedBy=\"user\" ,cascade=CascadeType.ALL)\n private Wallet wallet;\n}"
},
{
"identifier": "Wallet",
"path": "User/src/main/java/com/lcwd/user/service/Service/entities/Wallet.java",
"snippet": "@Entity\n@Getter\n@Setter\n@AllArgsConstructor\n@NoArgsConstructor\npublic class Wallet {\n\n @Id\n @GeneratedValue(strategy= GenerationType.AUTO)\n private Integer walletId;\n\n\n @DecimalMin(\"0.0\")\n @NotNull(message=\"Balance cannot be null\")\n private Float balance;\n\n @OneToMany(cascade=CascadeType.ALL)\n @JoinColumn(name=\"walletId\")\n private List<Transactions> transactions = new ArrayList<>();\n\n @OneToOne\n @JsonIgnore\n private User user;\n\n}"
},
{
"identifier": "UserException",
"path": "User/src/main/java/com/lcwd/user/service/Service/exception/UserException.java",
"snippet": "public class UserException extends RuntimeException{\n\n public UserException(String str){\n super(str) ;\n }\n public UserException(){\n\n }\n}"
},
{
"identifier": "WalletException",
"path": "User/src/main/java/com/lcwd/user/service/Service/exception/WalletException.java",
"snippet": "public class WalletException extends RuntimeException{\n\n public WalletException(String str){\n super(str) ;\n }\n\n public WalletException(){\n\n }\n}"
},
{
"identifier": "UserRepository",
"path": "User/src/main/java/com/lcwd/user/service/Service/repository/UserRepository.java",
"snippet": "@Repository\npublic interface UserRepository extends JpaRepository<User, String> {\n public User findByEmail(String email);\n}"
},
{
"identifier": "WalletRepository",
"path": "User/src/main/java/com/lcwd/user/service/Service/repository/WalletRepository.java",
"snippet": "@Repository\npublic interface WalletRepository extends JpaRepository<Wallet, Integer>, JpaRepositoryImplementation<Wallet, Integer> {\n}"
},
{
"identifier": "WalletServices",
"path": "User/src/main/java/com/lcwd/user/service/Service/service/WalletServices.java",
"snippet": "public interface WalletServices {\n /**\n * Adds money to a wallet.\n *\n * @param walletId The ID of the wallet to add money to.\n * @param amount The amount of money to add.\n * @return The updated wallet details.\n */\n public Wallet addMoney(Integer walletId, Float amount);\n\n /**\n * Retrieves all transactions associated with a wallet.\n *\n * @param walletId The ID of the wallet to retrieve transactions for.\n * @return A list of transactions associated with the wallet.\n */\n public List<Transactions> getAllTranactions(Integer walletId);\n\n\n /**\n * Creates a new wallet for a user with the given email.\n *\n * @param email The email of the user for whom to create a wallet.\n * @return The created wallet details.\n */\n public Wallet createWallet(String email);\n\n /**\n * Retrieves the details of a wallet by its ID.\n *\n * @param id The ID of the wallet to retrieve.\n * @return The wallet details.\n */\n public Wallet getWallet(Integer id);\n\n /**\n * Retrieves the wallet associated with a logged-in user by their email.\n *\n * @param email The email of the logged-in user.\n * @return The wallet details associated with the user.\n */\n public Wallet getLoggedUserWallet(String email);\n\n /**\n * Retrieves the balance of a wallet associated with a logged-in user by their email.\n *\n * @param email The email of the logged-in user.\n * @return The balance of the wallet associated with the user.\n */\n\n public Float getBalance(String email);\n\n public Wallet payRideBill(Integer walletId, Float bill);\n}"
}
] | import com.lcwd.user.service.Service.entities.TransactionType;
import com.lcwd.user.service.Service.entities.Transactions;
import com.lcwd.user.service.Service.entities.User;
import com.lcwd.user.service.Service.entities.Wallet;
import com.lcwd.user.service.Service.exception.UserException;
import com.lcwd.user.service.Service.exception.WalletException;
import com.lcwd.user.service.Service.repository.UserRepository;
import com.lcwd.user.service.Service.repository.WalletRepository;
import com.lcwd.user.service.Service.service.WalletServices;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.List; | 2,003 | package com.lcwd.user.service.Service.service.Impl;
@Service
@Slf4j
public class WalletServicesImpl implements WalletServices {
@Autowired
private WalletRepository wrepo;
@Autowired
private UserRepository urepo;
/**
* Adds money to a wallet.
*
* @param walletId The ID of the wallet to add money to.
* @param amount The amount of money to add.
* @return The updated wallet details.
*/
@Override
public Wallet addMoney(Integer walletId, Float amount) {
if(walletId==null || amount == null)
throw new WalletException("Invalid Details");
Wallet ob= wrepo.findById(walletId).orElseThrow(()->new WalletException("No Wallet Found"));
ob.setBalance(ob.getBalance()+amount);
Transactions trans= new Transactions();
trans.setTransactionDate(LocalDateTime.now());
trans.setAmount(amount);
trans.setType(TransactionType.CREDIT);
trans.setCurrentBalance(ob.getBalance());
ob.getTransactions().add(trans);
Wallet res= wrepo.save(ob);
return res;
}
/**
* Retrieves all transactions associated with a wallet.
*
* @param walletId The ID of the wallet to retrieve transactions for.
* @return A list of transactions associated with the wallet.
*/
@Override
public List<Transactions> getAllTranactions(Integer walletId) {
if(walletId==null )
throw new WalletException("Invalid Details");
Wallet ob= wrepo.findById(walletId).orElseThrow(()->new WalletException("No Wallet Found"));
List<Transactions> list= ob.getTransactions();
return list;
}
/**
* Pays a ride bill using a wallet.
*
* @param walletId The ID of the wallet to pay the bill from.
* @param bill The bill amount to be paid.
* @return The updated wallet details.
*/
@Override
public Wallet payRideBill(Integer walletId, Float bill) {
if(walletId==null || bill == null)
throw new WalletException("Invalid Details");
Wallet ob= wrepo.findById(walletId).orElseThrow(()->new WalletException("No Wallet Found"));
if(ob.getBalance()<bill)
{
float required= bill - ob.getBalance();
throw new WalletException("Wallet Balance is low please add "+required+" amount first into your wallet");
}
ob.setBalance(ob.getBalance()-bill);
Transactions trans= new Transactions();
trans.setTransactionDate(LocalDateTime.now());
trans.setAmount(bill);
trans.setType(TransactionType.DEBIT);
trans.setCurrentBalance(ob.getBalance());
ob.getTransactions().add(trans);
Wallet res= wrepo.save(ob);
return res;
}
/**
* Creates a new wallet for a user with the given email.
*
* @param email The email of the user for whom to create a wallet.
* @return The created wallet details.
*/
@Override
public Wallet createWallet(String email) {
if(email==null )
throw new WalletException("Invalid Details");
User user= urepo.findByEmail(email);
if(user==null) | package com.lcwd.user.service.Service.service.Impl;
@Service
@Slf4j
public class WalletServicesImpl implements WalletServices {
@Autowired
private WalletRepository wrepo;
@Autowired
private UserRepository urepo;
/**
* Adds money to a wallet.
*
* @param walletId The ID of the wallet to add money to.
* @param amount The amount of money to add.
* @return The updated wallet details.
*/
@Override
public Wallet addMoney(Integer walletId, Float amount) {
if(walletId==null || amount == null)
throw new WalletException("Invalid Details");
Wallet ob= wrepo.findById(walletId).orElseThrow(()->new WalletException("No Wallet Found"));
ob.setBalance(ob.getBalance()+amount);
Transactions trans= new Transactions();
trans.setTransactionDate(LocalDateTime.now());
trans.setAmount(amount);
trans.setType(TransactionType.CREDIT);
trans.setCurrentBalance(ob.getBalance());
ob.getTransactions().add(trans);
Wallet res= wrepo.save(ob);
return res;
}
/**
* Retrieves all transactions associated with a wallet.
*
* @param walletId The ID of the wallet to retrieve transactions for.
* @return A list of transactions associated with the wallet.
*/
@Override
public List<Transactions> getAllTranactions(Integer walletId) {
if(walletId==null )
throw new WalletException("Invalid Details");
Wallet ob= wrepo.findById(walletId).orElseThrow(()->new WalletException("No Wallet Found"));
List<Transactions> list= ob.getTransactions();
return list;
}
/**
* Pays a ride bill using a wallet.
*
* @param walletId The ID of the wallet to pay the bill from.
* @param bill The bill amount to be paid.
* @return The updated wallet details.
*/
@Override
public Wallet payRideBill(Integer walletId, Float bill) {
if(walletId==null || bill == null)
throw new WalletException("Invalid Details");
Wallet ob= wrepo.findById(walletId).orElseThrow(()->new WalletException("No Wallet Found"));
if(ob.getBalance()<bill)
{
float required= bill - ob.getBalance();
throw new WalletException("Wallet Balance is low please add "+required+" amount first into your wallet");
}
ob.setBalance(ob.getBalance()-bill);
Transactions trans= new Transactions();
trans.setTransactionDate(LocalDateTime.now());
trans.setAmount(bill);
trans.setType(TransactionType.DEBIT);
trans.setCurrentBalance(ob.getBalance());
ob.getTransactions().add(trans);
Wallet res= wrepo.save(ob);
return res;
}
/**
* Creates a new wallet for a user with the given email.
*
* @param email The email of the user for whom to create a wallet.
* @return The created wallet details.
*/
@Override
public Wallet createWallet(String email) {
if(email==null )
throw new WalletException("Invalid Details");
User user= urepo.findByEmail(email);
if(user==null) | throw new UserException("No User Found"); | 4 | 2023-10-17 19:25:18+00:00 | 4k |
xiezhihui98/GAT1400 | src/main/java/com/cz/viid/be/task/action/VIIDServerAction.java | [
{
"identifier": "VIIDServerClient",
"path": "src/main/java/com/cz/viid/rpc/VIIDServerClient.java",
"snippet": "@FeignClient(name = \"VIIDServerClient\", url = \"http://127.0.0.254\")\npublic interface VIIDServerClient {\n\n @PostMapping(\"/VIID/System/Register\")\n Response register(URI uri, @RequestBody RegisterRequest request,\n @RequestHeader(HttpHeaders.AUTHORIZATION) String authorization);\n\n @PostMapping(\"/VIID/System/UnRegister\")\n VIIDBaseResponse unRegister(URI uri, @RequestBody UnRegisterRequest request,\n @RequestHeader(\"User-Identify\") String authorization);\n\n @PostMapping(\"/VIID/System/Keepalive\")\n VIIDBaseResponse keepalive(URI uri, @RequestBody KeepaliveRequest keepaliveRequest,\n @RequestHeader(\"User-Identify\") String userIdentifier);\n\n @PostMapping(\"/VIID/Subscribes\")\n VIIDSubscribesResponse addSubscribes(URI uri, @RequestBody SubscribesRequest request,\n @RequestHeader(\"User-Identify\") String userIdentifier);\n\n @PutMapping(\"/VIID/Subscribes\")\n VIIDSubscribesResponse updateSubscribes(URI uri, @RequestBody SubscribesRequest request,\n @RequestHeader(\"User-Identify\") String userIdentifier);\n\n @DeleteMapping(\"/VIID/Subscribes\")\n VIIDSubscribesResponse cancelSubscribes(URI uri, @RequestParam(\"IDList\") List<String> resourceIds,\n @RequestHeader(\"User-Identify\") String userIdentifier);\n\n// @PostMapping(\"/VIID/SubscribeNotifications\")\n @PostMapping\n VIIDNotificationResponse subscribeNotifications(URI uri, @RequestBody SubscribeNotificationRequest request,\n @RequestHeader(\"User-Identify\") String userIdentifier);\n}"
},
{
"identifier": "VIIDRuntimeException",
"path": "src/main/java/com/cz/viid/framework/exception/VIIDRuntimeException.java",
"snippet": "public class VIIDRuntimeException extends RuntimeException{\n\n public VIIDRuntimeException() {\n super(\"\");\n }\n\n public VIIDRuntimeException(String message) {\n super(message);\n }\n}"
},
{
"identifier": "DigestData",
"path": "src/main/java/com/cz/viid/framework/security/DigestData.java",
"snippet": "@Data\npublic class DigestData {\n public static final String DIGEST_KEY = \"chenzhou\";\n public static final String DIGEST_REALM = \"viid\";\n protected static MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor();\n\n /**\n * 第一次注册请求带过来 realm qop nonce opaque\n */\n private final String realm;\n private final String qop;\n private final String nonce;\n private final String opaque;\n\n private String username;\n private String uri = \"/VIID/System/Register\";\n private String nc = \"00000001\";\n private String response;\n private String cnonce;\n private final String section212response;\n private long nonceExpiryTime;\n\n public DigestData(String header) {\n this.section212response = header.substring(7);\n String[] headerEntries = DigestAuthUtils.splitIgnoringQuotes(this.section212response, ',');\n Map<String, String> headerMap = DigestAuthUtils.splitEachArrayElementAndCreateMap(headerEntries, \"=\", \"\\\"\");\n this.username = (String) headerMap.get(\"username\");\n this.realm = (String) headerMap.get(\"realm\");\n this.nonce = (String) headerMap.get(\"nonce\");\n this.response = (String) headerMap.get(\"response\");\n this.qop = (String) headerMap.get(\"qop\");\n Optional.ofNullable(headerMap.get(\"uri\")).ifPresent(value -> this.uri = value);\n Optional.ofNullable(headerMap.get(\"nc\")).ifPresent(value -> this.nc = value);\n this.cnonce = (String) headerMap.get(\"cnonce\");\n if (Objects.isNull(this.cnonce)) {\n this.cnonce = new String(Hex.encodeHex(Digests.generateSalt(8)));\n }\n this.opaque = headerMap.get(\"opaque\");\n }\n\n /**\n * 转换第一次注册请求带回来的摘要数据并写入第二次请求摘要信息\n * @param username 用户名\n * @param password 凭证\n * @param httpMethod http方法\n * @return 第二次请求 authenticate 字符串\n */\n public String toDigestHeader(String username, String password, String httpMethod) {\n this.username = username;\n if (Objects.isNull(this.response)) {\n this.response = this.calculateServerDigest(password, httpMethod);\n }\n return String.format(\"Digest username=\\\"%s\\\", realm=\\\"%s\\\", nonce=\\\"%s\\\", uri=\\\"%s\\\", response=\\\"%s\\\", qop=\\\"%s\\\", nc=\\\"%s\\\", cnonce=\\\"%s\\\", algorithm=\\\"%s\\\", opaque=\\\"%s\\\"\",\n this.username, this.realm, this.nonce, this.uri, this.response, this.qop, this.nc, this.cnonce, \"MD5\", this.opaque);\n }\n\n public String calculateServerDigest(String password, String httpMethod) {\n return DigestAuthUtils.generateDigest(false, this.username, this.realm, password, httpMethod, this.uri, this.qop, this.nonce, this.nc, this.cnonce);\n }\n\n public void validateAndDecode(String entryPointKey, String expectedRealm) throws BadCredentialsException {\n if (this.username != null && this.realm != null && this.nonce != null && this.uri != null && this.response != null) {\n if (\"auth\".equals(this.qop) && (this.nc == null || this.cnonce == null)) {\n throw new BadCredentialsException(messages.getMessage(\"DigestAuthenticationFilter.missingAuth\", new Object[]{this.section212response}, \"Missing mandatory digest value; received header {0}\"));\n } else if (!expectedRealm.equals(this.realm)) {\n throw new BadCredentialsException(messages.getMessage(\"DigestAuthenticationFilter.incorrectRealm\", new Object[]{this.realm, expectedRealm}, \"Response realm name '{0}' does not match system realm name of '{1}'\"));\n } else {\n try {\n Base64.getDecoder().decode(this.nonce.getBytes());\n } catch (IllegalArgumentException var7) {\n throw new BadCredentialsException(messages.getMessage(\"DigestAuthenticationFilter.nonceEncoding\", new Object[]{this.nonce}, \"Nonce is not encoded in Base64; received nonce {0}\"));\n }\n\n String nonceAsPlainText = new String(Base64.getDecoder().decode(this.nonce.getBytes()));\n String[] nonceTokens = StringUtils.delimitedListToStringArray(nonceAsPlainText, \":\");\n if (nonceTokens.length != 2) {\n throw new BadCredentialsException(messages.getMessage(\"DigestAuthenticationFilter.nonceNotTwoTokens\", new Object[]{nonceAsPlainText}, \"Nonce should have yielded two tokens but was {0}\"));\n } else {\n try {\n this.nonceExpiryTime = new Long(nonceTokens[0]);\n } catch (NumberFormatException var6) {\n throw new BadCredentialsException(messages.getMessage(\"DigestAuthenticationFilter.nonceNotNumeric\", new Object[]{nonceAsPlainText}, \"Nonce token should have yielded a numeric first token, but was {0}\"));\n }\n\n String expectedNonceSignature = DigestAuthUtils.md5Hex(this.nonceExpiryTime + \":\" + entryPointKey);\n if (!expectedNonceSignature.equals(nonceTokens[1])) {\n throw new BadCredentialsException(messages.getMessage(\"DigestAuthenticationFilter.nonceCompromised\", new Object[]{nonceAsPlainText}, \"Nonce token compromised {0}\"));\n }\n }\n }\n } else {\n throw new BadCredentialsException(messages.getMessage(\"DigestAuthenticationFilter.missingMandatory\", new Object[]{this.section212response}, \"Missing mandatory digest value; received header {0}\"));\n }\n }\n}"
},
{
"identifier": "DeviceIdObject",
"path": "src/main/java/com/cz/viid/framework/domain/dto/DeviceIdObject.java",
"snippet": "@Data\npublic class DeviceIdObject {\n\n @JsonProperty(\"DeviceID\")\n private String deviceId;\n\n public DeviceIdObject() {}\n\n public DeviceIdObject(String deviceId) {\n this.deviceId = deviceId;\n }\n}"
},
{
"identifier": "ResponseStatusObject",
"path": "src/main/java/com/cz/viid/framework/domain/dto/ResponseStatusObject.java",
"snippet": "@Data\npublic class ResponseStatusObject {\n\n @JsonProperty(\"Id\")\n private String id;\n @JsonProperty(\"RequestURL\")\n private String requestUrl;\n @JsonProperty(\"StatusCode\")\n private String statusCode;\n @JsonProperty(\"StatusString\")\n private String statusString;\n @JsonProperty(\"LocalTime\")\n private String localTime;\n\n public ResponseStatusObject() {\n }\n\n public ResponseStatusObject(String requestUrl, String statusCode, String statusString) {\n this(null, requestUrl, statusCode, statusString);\n }\n\n public ResponseStatusObject(String id, String requestUrl, String statusCode, String statusString) {\n this.id = id;\n this.requestUrl = requestUrl;\n this.statusCode = statusCode;\n this.statusString = statusString;\n this.localTime = DateFormatUtils.format(new Date(), \"yyyyMMddHHmmss\");\n }\n\n}"
},
{
"identifier": "VIIDServer",
"path": "src/main/java/com/cz/viid/framework/domain/entity/VIIDServer.java",
"snippet": "@Data\n@TableName(\"viid_server\")\npublic class VIIDServer {\n\n @ApiModelProperty(value = \"视图库编号\")\n @TableId(value = \"server_id\",type = IdType.NONE)\n private String serverId;\n @ApiModelProperty(value = \"视图库名称\")\n @TableField(value = \"server_name\")\n private String serverName;\n @ApiModelProperty(value = \"交互协议\")\n @TableField(\"scheme\")\n private String scheme = \"http\";\n @ApiModelProperty(value = \"视图库地址\")\n @TableField(value = \"host\")\n private String host;\n @ApiModelProperty(value = \"视图库端口\")\n @TableField(value = \"port\")\n private Integer port;\n @ApiModelProperty(value = \"授权用户\")\n @TableField(value = \"username\")\n private String username;\n @ApiModelProperty(value = \"授权用户凭证\")\n @TableField(value = \"authenticate\")\n private String authenticate;\n @ApiModelProperty(value = \"是否启用\")\n @TableField(value = \"enabled\")\n private Boolean enabled;\n @ApiModelProperty(value = \"服务类别\", notes = \"0=自己,1=下级,2=上级\")\n @TableField(value = \"category\")\n private String category;\n @ApiModelProperty(\"创建时间\")\n @TableField(value = \"create_time\")\n private Date createTime;\n @ApiModelProperty(\"是否开启双向保活\")\n @TableField(value = \"keepalive\")\n private Boolean keepalive;\n @ApiModelProperty(value = \"数据传输类型\", example = \"HTTP\")\n @TableField(\"transmission\")\n private String transmission = Constants.VIID_SERVER.TRANSMISSION.HTTP;\n @ApiModelProperty(\"在线状态\")\n @TableField(value = \"online\", exist = false)\n private Boolean online = false;\n\n public String httpUrlBuilder() {\n return scheme + \"://\" + host + \":\" + port;\n }\n}"
},
{
"identifier": "KeepaliveRequest",
"path": "src/main/java/com/cz/viid/framework/domain/vo/KeepaliveRequest.java",
"snippet": "@Data\npublic class KeepaliveRequest {\n\n @JsonProperty(\"KeepaliveObject\")\n private DeviceIdObject keepaliveObject;\n\n public static KeepaliveRequest builder(DeviceIdObject keepaliveObject) {\n KeepaliveRequest keepaliveRequest = new KeepaliveRequest();\n keepaliveRequest.setKeepaliveObject(keepaliveObject);\n return keepaliveRequest;\n }\n\n}"
},
{
"identifier": "RegisterRequest",
"path": "src/main/java/com/cz/viid/framework/domain/vo/RegisterRequest.java",
"snippet": "@Data\npublic class RegisterRequest {\n\n @JsonProperty(\"RegisterObject\")\n private DeviceIdObject registerObject;\n\n public DeviceIdObject getRegisterObject() {\n return registerObject;\n }\n\n public void setRegisterObject(DeviceIdObject registerObject) {\n this.registerObject = registerObject;\n }\n}"
},
{
"identifier": "UnRegisterRequest",
"path": "src/main/java/com/cz/viid/framework/domain/vo/UnRegisterRequest.java",
"snippet": "@Data\npublic class UnRegisterRequest {\n\n @JsonProperty(\"UnRegisterObject\")\n private DeviceIdObject unRegisterObject;\n}"
},
{
"identifier": "VIIDBaseResponse",
"path": "src/main/java/com/cz/viid/framework/domain/vo/VIIDBaseResponse.java",
"snippet": "@Data\npublic class VIIDBaseResponse {\n\n @JsonProperty(\"ResponseStatusObject\")\n private ResponseStatusObject responseStatusObject;\n\n public VIIDBaseResponse() {}\n\n public VIIDBaseResponse(ResponseStatusObject responseStatusObject) {\n this.responseStatusObject = responseStatusObject;\n }\n}"
},
{
"identifier": "VIIDServerService",
"path": "src/main/java/com/cz/viid/framework/service/VIIDServerService.java",
"snippet": "public interface VIIDServerService extends IService<VIIDServer> {\n\n void afterPropertiesSet();\n VIIDServer getByIdAndEnabled(String id);\n\n VIIDServer getCurrentServer(boolean useCache);\n VIIDServer getCurrentServer();\n\n VIIDServer register(RegisterRequest request, DigestData digestData);\n\n boolean unRegister(String deviceId);\n\n ResponseStatusObject keepalive(String deviceId);\n\n Page<VIIDServer> list(SearchDataRequest request);\n\n boolean upsert(VIIDServer request);\n\n void changeDomain(String source);\n\n boolean maintenance(VIIDServer viidServer);\n}"
}
] | import com.cz.viid.rpc.VIIDServerClient;
import com.cz.viid.framework.exception.VIIDRuntimeException;
import com.cz.viid.framework.security.DigestData;
import com.cz.viid.framework.domain.dto.DeviceIdObject;
import com.cz.viid.framework.domain.dto.ResponseStatusObject;
import com.cz.viid.framework.domain.entity.VIIDServer;
import com.cz.viid.framework.domain.vo.KeepaliveRequest;
import com.cz.viid.framework.domain.vo.RegisterRequest;
import com.cz.viid.framework.domain.vo.UnRegisterRequest;
import com.cz.viid.framework.domain.vo.VIIDBaseResponse;
import com.cz.viid.framework.service.VIIDServerService;
import com.fasterxml.jackson.databind.ObjectMapper;
import feign.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.Collection;
import java.util.LinkedList;
import java.util.Objects;
import java.util.Optional; | 3,342 | package com.cz.viid.be.task.action;
@Component
public class VIIDServerAction {
@Autowired
ObjectMapper objectMapper;
@Autowired | package com.cz.viid.be.task.action;
@Component
public class VIIDServerAction {
@Autowired
ObjectMapper objectMapper;
@Autowired | VIIDServerClient viidServerClient; | 0 | 2023-10-23 11:25:43+00:00 | 4k |
eclipse-egit/egit | org.eclipse.egit.ui/src/org/eclipse/egit/ui/internal/synchronize/mapping/GitChangeSetDropAdapterAssistant.java | [
{
"identifier": "runCommand",
"path": "org.eclipse.egit.ui/src/org/eclipse/egit/ui/internal/CommonUtils.java",
"snippet": "public static boolean runCommand(String commandId,\n\t\tIStructuredSelection selection) {\n\treturn runCommand(commandId, selection, null);\n}"
},
{
"identifier": "ADD_TO_INDEX",
"path": "org.eclipse.egit.ui/src/org/eclipse/egit/ui/internal/actions/ActionCommands.java",
"snippet": "public static final String ADD_TO_INDEX = \"org.eclipse.egit.ui.team.AddToIndex\"; //$NON-NLS-1$"
},
{
"identifier": "REMOVE_FROM_INDEX",
"path": "org.eclipse.egit.ui/src/org/eclipse/egit/ui/internal/actions/ActionCommands.java",
"snippet": "public static final String REMOVE_FROM_INDEX = \"org.eclipse.egit.ui.team.RemoveFromIndex\"; //$NON-NLS-1$"
},
{
"identifier": "GitModelCache",
"path": "org.eclipse.egit.ui/src/org/eclipse/egit/ui/internal/synchronize/model/GitModelCache.java",
"snippet": "public class GitModelCache extends GitModelObjectContainer {\n\n\tprivate final Path location;\n\n\tprivate final Repository repo;\n\n\tprivate GitModelObject[] children;\n\n\t/**\n\t * Constructs model node that represents current status of Git cache.\n\t *\n\t * @param parent\n\t * parent object\n\t *\n\t * @param repo\n\t * repository associated with this object\n\t * @param cache\n\t * cache containing all changed objects\n\t */\n\tpublic GitModelCache(GitModelRepository parent, Repository repo,\n\t\t\tMap<String, Change> cache) {\n\t\tthis(parent, repo, cache, new FileModelFactory() {\n\t\t\t@Override\n\t\t\tpublic GitModelBlob createFileModel(\n\t\t\t\t\tGitModelObjectContainer objParent, Repository nestedRepo,\n\t\t\t\t\tChange change, IPath path) {\n\t\t\t\treturn new GitModelCacheFile(objParent, nestedRepo, change,\n\t\t\t\t\t\tpath);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic boolean isWorkingTree() {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t});\n\t}\n\n\t/**\n\t * @param parent\n\t * parent object\n\t * @param repo\n\t * repository associated with this object\n\t * @param changes\n\t * list of changes associated with this object\n\t * @param fileFactory\n\t * leaf instance factory\n\t */\n\tprotected GitModelCache(GitModelRepository parent, final Repository repo,\n\t\t\tMap<String, Change> changes, final FileModelFactory fileFactory) {\n\t\tsuper(parent);\n\t\tthis.repo = repo;\n\t\tthis.location = new Path(repo.getWorkTree().toString());\n\n\t\tthis.children = TreeBuilder.build(this, repo, changes, fileFactory,\n\t\t\t\tnew TreeModelFactory() {\n\t\t\t\t\t@Override\n\t\t\t\t\tpublic GitModelTree createTreeModel(\n\t\t\t\t\t\t\tGitModelObjectContainer parentObject,\n\t\t\t\t\t\t\tIPath fullPath,\n\t\t\t\t\t\t\tint kind) {\n\t\t\t\t\t\treturn new GitModelCacheTree(parentObject, repo,\n\t\t\t\t\t\t\t\tfullPath, fileFactory);\n\t\t\t\t\t}\n\t\t\t\t});\n\t}\n\n\t@Override\n\tpublic String getName() {\n\t\treturn UIText.GitModelIndex_index;\n\t}\n\n\t@Override\n\tpublic GitModelObject[] getChildren() {\n\t\tif (children == null) {\n\t\t\treturn new GitModelObject[0];\n\t\t}\n\t\treturn children;\n\t}\n\n\t@Override\n\tpublic int getKind() {\n\t\treturn Differencer.CHANGE | Differencer.RIGHT;\n\t}\n\n\t@Override\n\tpublic int repositoryHashCode() {\n\t\treturn repo.getWorkTree().hashCode();\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (obj == this)\n\t\t\treturn true;\n\n\t\tif (obj instanceof GitModelCache\n\t\t\t\t&& !(obj instanceof GitModelWorkingTree)) {\n\t\t\tGitModelCache left = (GitModelCache) obj;\n\t\t\treturn left.getParent().equals(getParent());\n\t\t}\n\n\t\treturn false;\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\treturn repositoryHashCode();\n\t}\n\n\t@Override\n\tpublic IPath getLocation() {\n\t\treturn location;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"ModelCache\"; //$NON-NLS-1$\n\t}\n\n\t@Override\n\tpublic void dispose() {\n\t\tif (children != null) {\n\t\t\tfor (GitModelObject object : children)\n\t\t\t\tobject.dispose();\n\t\t\tchildren = null;\n\t\t}\n\t}\n}"
},
{
"identifier": "GitModelCacheFile",
"path": "org.eclipse.egit.ui/src/org/eclipse/egit/ui/internal/synchronize/model/GitModelCacheFile.java",
"snippet": "public class GitModelCacheFile extends GitModelBlob {\n\n\tGitModelCacheFile(GitModelObjectContainer parent, Repository repo,\n\t\t\tChange change, IPath path) {\n\t\tsuper(parent, repo, change, path);\n\t}\n\n\t@Override\n\tprotected GitCompareInput getCompareInput(ComparisonDataSource baseData,\n\t\t\tComparisonDataSource remoteData, ComparisonDataSource ancestorData) {\n\t\tString gitPath = Repository.stripWorkDir(repo.getWorkTree(), path.toFile());\n\n\t\treturn new GitCacheCompareInput(repo, (IFile) getResource(),\n\t\t\t\tancestorData, baseData, remoteData, gitPath);\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (obj == this)\n\t\t\treturn true;\n\n\t\tif (obj == null)\n\t\t\treturn false;\n\n\t\tif (obj.getClass() != getClass())\n\t\t\treturn false;\n\n\t\tGitModelCacheFile objBlob = (GitModelCacheFile) obj;\n\n\t\treturn hashCode() == objBlob.hashCode();\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\treturn super.hashCode() + 31;\n\t}\n\n}"
},
{
"identifier": "GitModelCacheTree",
"path": "org.eclipse.egit.ui/src/org/eclipse/egit/ui/internal/synchronize/model/GitModelCacheTree.java",
"snippet": "public class GitModelCacheTree extends GitModelTree {\n\n\tprivate final FileModelFactory factory;\n\n\t/**\n\t * @param parent\n\t * parent object\n\t * @param repo\n\t * repository associated with this object parent object\n\t * @param fullPath\n\t * absolute path of object\n\t * @param factory\n\t */\n\tpublic GitModelCacheTree(GitModelObjectContainer parent, Repository repo,\n\t\t\tIPath fullPath, FileModelFactory factory) {\n\t\tsuper(parent, fullPath, RIGHT | CHANGE);\n\t\tthis.factory = factory;\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (obj == this)\n\t\t\treturn true;\n\n\t\tif (obj == null)\n\t\t\treturn false;\n\n\t\tif (obj.getClass() != getClass())\n\t\t\treturn false;\n\n\t\tGitModelCacheTree objTree = (GitModelCacheTree) obj;\n\t\treturn path.equals(objTree.path)\n\t\t\t\t&& factory.isWorkingTree() == objTree.factory.isWorkingTree();\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\treturn path.hashCode() + (factory.isWorkingTree() ? 31 : 41);\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"GitModelCacheTree[\" + getLocation() + \", isWorkingTree:\" + factory.isWorkingTree() + \"]\"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$\n\t}\n\n\t/**\n\t * Distinguish working tree from cached/staged tree\n\t *\n\t * @return {@code true} when this tree is working tree, {@code false}\n\t * when it is a cached tree\n\t */\n\tpublic boolean isWorkingTree() {\n\t\treturn factory.isWorkingTree();\n\t}\n\n}"
},
{
"identifier": "GitModelWorkingFile",
"path": "org.eclipse.egit.ui/src/org/eclipse/egit/ui/internal/synchronize/model/GitModelWorkingFile.java",
"snippet": "public class GitModelWorkingFile extends GitModelBlob {\n\n\tGitModelWorkingFile(GitModelObjectContainer parent, Repository repo,\n\t\t\tChange change, IPath path) {\n\t\tsuper(parent, repo, change, path);\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (obj == this)\n\t\t\treturn true;\n\n\t\tif (obj == null)\n\t\t\treturn false;\n\n\t\tif (obj.getClass() != getClass())\n\t\t\treturn false;\n\n\t\tGitModelWorkingFile objBlob = (GitModelWorkingFile) obj;\n\n\t\treturn hashCode() == objBlob.hashCode();\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\treturn super.hashCode() + 41;\n\t}\n\n}"
},
{
"identifier": "GitModelWorkingTree",
"path": "org.eclipse.egit.ui/src/org/eclipse/egit/ui/internal/synchronize/model/GitModelWorkingTree.java",
"snippet": "public class GitModelWorkingTree extends GitModelCache {\n\n\t/**\n\t * @param parent\n\t * parent object\n\t * @param repo\n\t * repository associated with this object\n\t * @param cache\n\t * list of cached changes\n\t */\n\tpublic GitModelWorkingTree(GitModelRepository parent, Repository repo,\n\t\t\tMap<String, Change> cache) {\n\t\tsuper(parent, repo, cache, new FileModelFactory() {\n\t\t\t@Override\n\t\t\tpublic GitModelBlob createFileModel(\n\t\t\t\t\tGitModelObjectContainer objParent, Repository nestedRepo,\n\t\t\t\t\tChange change, IPath path) {\n\t\t\t\treturn new GitModelWorkingFile(objParent, nestedRepo, change,\n\t\t\t\t\t\tpath);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic boolean isWorkingTree() {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t});\n\t}\n\n\t@Override\n\tpublic String getName() {\n\t\treturn UIText.GitModelWorkingTree_workingTree;\n\t}\n\n\t@Override\n\tpublic int getKind() {\n\t\t// changes in working tree are always outgoing modifications\n\t\treturn Differencer.RIGHT | Differencer.CHANGE;\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (obj == this)\n\t\t\treturn true;\n\n\t\tif (obj == null)\n\t\t\treturn false;\n\n\t\tif (obj.getClass() != getClass())\n\t\t\treturn false;\n\n\t\tGitModelCache left = (GitModelCache) obj;\n\t\treturn left.getParent().equals(getParent());\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\treturn getParent().hashCode() + 31;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"ModelWorkingTree\"; //$NON-NLS-1$\n\t}\n\n}"
}
] | import static org.eclipse.egit.ui.internal.CommonUtils.runCommand;
import static org.eclipse.egit.ui.internal.actions.ActionCommands.ADD_TO_INDEX;
import static org.eclipse.egit.ui.internal.actions.ActionCommands.REMOVE_FROM_INDEX;
import java.util.Iterator;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.egit.ui.internal.synchronize.model.GitModelCache;
import org.eclipse.egit.ui.internal.synchronize.model.GitModelCacheFile;
import org.eclipse.egit.ui.internal.synchronize.model.GitModelCacheTree;
import org.eclipse.egit.ui.internal.synchronize.model.GitModelWorkingFile;
import org.eclipse.egit.ui.internal.synchronize.model.GitModelWorkingTree;
import org.eclipse.jface.util.LocalSelectionTransfer;
import org.eclipse.jface.viewers.TreeSelection;
import org.eclipse.swt.dnd.DropTargetEvent;
import org.eclipse.swt.dnd.TransferData;
import org.eclipse.swt.dnd.URLTransfer;
import org.eclipse.ui.navigator.CommonDropAdapter;
import org.eclipse.ui.navigator.CommonDropAdapterAssistant; | 3,288 | /*******************************************************************************
* Copyright (C) 2011, Dariusz Luksza <[email protected]>
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License 2.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifier: EPL-2.0
*******************************************************************************/
package org.eclipse.egit.ui.internal.synchronize.mapping;
/**
* Drop Adapter Assistant for the Git Change Set model
*/
public class GitChangeSetDropAdapterAssistant extends
CommonDropAdapterAssistant {
private static final URLTransfer SELECTION_TRANSFER = URLTransfer
.getInstance();
/**
* Stage operation type
*/
private static final String STAGE_OP = "STAGE"; //$NON-NLS-1$
/**
* Unstage operation type
*/
private static final String UNSTAGE_OP = "UNSTAGE"; //$NON-NLS-1$
/**
* Unsupported operation type
*/
private static final String UNSUPPORTED_OP = "UNSUPPORTED"; //$NON-NLS-1$
@Override
public IStatus validateDrop(Object target, int operationCode,
TransferData transferType) {
TreeSelection selection = (TreeSelection) LocalSelectionTransfer
.getTransfer().getSelection();
String operation = getOperationType(selection);
if (!UNSUPPORTED_OP.equals(operation)) {
if (target instanceof GitModelWorkingTree) {
if (UNSTAGE_OP.equals(operation))
return Status.OK_STATUS;
} else if (STAGE_OP.equals(operation)
&& target instanceof GitModelCache)
return Status.OK_STATUS;
}
return Status.CANCEL_STATUS;
}
@Override
public IStatus handleDrop(CommonDropAdapter aDropAdapter,
DropTargetEvent aDropTargetEvent, Object aTarget) {
TreeSelection selection = (TreeSelection) LocalSelectionTransfer
.getTransfer().getSelection();
String operation = getOperationType(selection);
if (STAGE_OP.equals(operation))
runCommand(ADD_TO_INDEX, selection);
else if (UNSTAGE_OP.equals(operation))
runCommand(REMOVE_FROM_INDEX, selection);
return Status.OK_STATUS;
}
@Override
public boolean isSupportedType(TransferData aTransferType) {
return SELECTION_TRANSFER.isSupportedType(aTransferType);
}
private String getOperationType(TreeSelection selection) {
String operation = null;
for (Iterator<?> i = selection.iterator(); i.hasNext();) {
String tmpOperation = null;
Object next = i.next(); | /*******************************************************************************
* Copyright (C) 2011, Dariusz Luksza <[email protected]>
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License 2.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifier: EPL-2.0
*******************************************************************************/
package org.eclipse.egit.ui.internal.synchronize.mapping;
/**
* Drop Adapter Assistant for the Git Change Set model
*/
public class GitChangeSetDropAdapterAssistant extends
CommonDropAdapterAssistant {
private static final URLTransfer SELECTION_TRANSFER = URLTransfer
.getInstance();
/**
* Stage operation type
*/
private static final String STAGE_OP = "STAGE"; //$NON-NLS-1$
/**
* Unstage operation type
*/
private static final String UNSTAGE_OP = "UNSTAGE"; //$NON-NLS-1$
/**
* Unsupported operation type
*/
private static final String UNSUPPORTED_OP = "UNSUPPORTED"; //$NON-NLS-1$
@Override
public IStatus validateDrop(Object target, int operationCode,
TransferData transferType) {
TreeSelection selection = (TreeSelection) LocalSelectionTransfer
.getTransfer().getSelection();
String operation = getOperationType(selection);
if (!UNSUPPORTED_OP.equals(operation)) {
if (target instanceof GitModelWorkingTree) {
if (UNSTAGE_OP.equals(operation))
return Status.OK_STATUS;
} else if (STAGE_OP.equals(operation)
&& target instanceof GitModelCache)
return Status.OK_STATUS;
}
return Status.CANCEL_STATUS;
}
@Override
public IStatus handleDrop(CommonDropAdapter aDropAdapter,
DropTargetEvent aDropTargetEvent, Object aTarget) {
TreeSelection selection = (TreeSelection) LocalSelectionTransfer
.getTransfer().getSelection();
String operation = getOperationType(selection);
if (STAGE_OP.equals(operation))
runCommand(ADD_TO_INDEX, selection);
else if (UNSTAGE_OP.equals(operation))
runCommand(REMOVE_FROM_INDEX, selection);
return Status.OK_STATUS;
}
@Override
public boolean isSupportedType(TransferData aTransferType) {
return SELECTION_TRANSFER.isSupportedType(aTransferType);
}
private String getOperationType(TreeSelection selection) {
String operation = null;
for (Iterator<?> i = selection.iterator(); i.hasNext();) {
String tmpOperation = null;
Object next = i.next(); | if (next instanceof GitModelWorkingFile) | 6 | 2023-10-20 15:17:51+00:00 | 4k |
leforero4-ui/unico_proyecto_con_todos_los_patrones_de_diseno_en_java | src/main/application/driver/adapter/usecase/factory_enemies/EnemyHighMethod.java | [
{
"identifier": "EnemyMethod",
"path": "src/main/application/driver/port/usecase/EnemyMethod.java",
"snippet": "public interface EnemyMethod {\n\tList<Enemy> createEnemies();\n\tFavorableEnvironment createFavorableEnvironments();\n}"
},
{
"identifier": "ArmyFactory",
"path": "src/main/domain/model/ArmyFactory.java",
"snippet": "public interface ArmyFactory {\n\tPlayer createPlayer(PlayerBuilder playerBuilder);\n\tSoldier createSoldier(int life, int attackLevel, Skillfull skill);\n\tEnemy createSquadron(List<Enemy> squadron, Skillfull skill);\n\tSupreme getSupreme();\n}"
},
{
"identifier": "Enemy",
"path": "src/main/domain/model/Enemy.java",
"snippet": "public abstract class Enemy implements Protective {\n\tprotected int life;\n\tprotected int attackLevel;\n\tprotected final Skillfull skill;\n\tprotected Status status;\n\t\n\tpublic Enemy(int life, int attackLevel, Skillfull skill) {\n\t\tthis.life = life;\n\t\tthis.attackLevel = attackLevel;\n\t\tthis.skill = skill;\n\t\tthis.status = new Asleep();\n\t}\n\n\tpublic int getLife() {\n\t\treturn this.life;\n\t}\n\t\n\tpublic int getAttackLevel(boolean isAttacking) {\n\t\treturn this.skill.getEnhancedAttackLevel(this.attackLevel, isAttacking);\n\t}\n\t\n\tpublic int getCounterAttackLevel(final int attackLevelReceived) {\n\t\treturn this.status.getAttackLevel(attackLevelReceived, this);\n\t}\n\t\n\tpublic void setStatus(final Status status) {\n\t\tthis.status = status;\n\t}\n\t\n\t@Override\n\tpublic void protect(final Supreme theProtected) {\n\t\tthis.receiveAttack(1);\n\t\tif (this.getLife() <= 0) {\n\t\t\ttheProtected.removeProtector(this);\n\t\t}\n\t}\n\n\tpublic abstract void receiveAttack(final int attack);\n\t\n\tpublic abstract String getAvatar(final String prefix);\n\t\n\tpublic abstract void acceptVisit(Visitor visitor);\n}"
},
{
"identifier": "FavorableEnvironment",
"path": "src/main/domain/model/FavorableEnvironment.java",
"snippet": "public interface FavorableEnvironment {\n\tvoid setNextFavorableEnvironment(FavorableEnvironment favorableEnvironment);\n\tboolean canAttack(Enemy enemy);\n\tboolean canHandleAttack(Enemy enemy);\n}"
},
{
"identifier": "Fort",
"path": "src/main/domain/model/Fort.java",
"snippet": "public class Fort extends DecoratorEnemy {\n\n\tpublic Fort(final Enemy enemy) {\n\t\tsuper(enemy);\n\t}\n\n\t@Override\n\tpublic void receiveAttack(int attack) {\n\t\tsuper.receiveAttack(attack - 2);\n\t}\n\n\t@Override\n\tpublic String getAvatar(String prefix) {\n\t\treturn super.getAvatar(prefix + \"F\");\n\t}\n\n}"
},
{
"identifier": "Soldier",
"path": "src/main/domain/model/Soldier.java",
"snippet": "public abstract class Soldier extends Enemy {\n\tpublic Soldier(int life, int attackLevel, final Skillfull skill) {\n\t\tsuper(life, attackLevel, skill);\n\t}\n\t\n\t@Override\n\tpublic void receiveAttack(int attack) {\n\t\tthis.life -= attack;\n\t}\n\n\t@Override\n\tpublic void acceptVisit(Visitor visitor) {\n\t\tvisitor.visitSoldier(this);\n\t}\n\n\tpublic abstract Soldier clone();\n\tpublic abstract String getTypeEye();\n\tpublic abstract String getTypeHair();\n\tpublic abstract String getTypeShirt();\n\tpublic abstract String getTypePant();\n\tpublic abstract String getTypeShoes();\n}"
},
{
"identifier": "Supreme",
"path": "src/main/domain/model/Supreme.java",
"snippet": "public abstract class Supreme extends Enemy {\n\t\n\tprivate final List<Protective> protectors;\n\t\n\tprotected Supreme(int life, int attackLevel, Skillfull skill) {\n\t\tsuper(life, attackLevel, skill);\n\t\tthis.protectors = new ArrayList<>();\n\t}\n\n\t@Override\n\tpublic void acceptVisit(Visitor visitor) {\n\t\tvisitor.visitSupreme(this);\n\t}\n\n\t@Override\n\tpublic void receiveAttack(int attack) {\n\t\tthis.life -= this.notifyAttackToProtectors(attack);\n\t}\n\t\n\tpublic void addProtector(Protective protective) {\n\t\tthis.protectors.add(protective);\n\t}\n\t\n\tpublic void removeProtector(Protective protective) {\n\t\tthis.protectors.remove(protective);\n\t}\n\t\n\tprivate int notifyAttackToProtectors(int attack) {\n\t\tfinal List<Protective> protectorsTemp = new ArrayList<>(this.protectors);\n\t\tprotectorsTemp.forEach(protective -> {\n\t\t\tprotective.protect(this);\n\t\t});\n\t\t\n\t\treturn attack - protectorsTemp.size();\n\t}\n\n}"
},
{
"identifier": "City",
"path": "src/main/domain/model/environment/City.java",
"snippet": "public class City extends BaseFavorableEnvironment {\n\t\n\tpublic City(final int probability) {\n\t\tsuper(probability);\n\t}\n\n\t@Override\n\tpublic boolean canHandleAttack(final Enemy enemy) {\n\t\tif (enemy instanceof Squadron) {\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n\t@Override\n\tprotected boolean calculateIfCanAttack() {\n\t\tif (this.probability > 75) {\n\t\t\treturn true;\n\t\t}\n\t\treturn this.calculateIfCanAttackByProbability();\n\t}\n\n}"
},
{
"identifier": "Cold",
"path": "src/main/domain/model/environment/Cold.java",
"snippet": "public class Cold extends BaseFavorableEnvironment {\n\t\n\tpublic Cold() {\n\t\tsuper(25);\n\t}\n\n\t@Override\n\tpublic boolean canHandleAttack(final Enemy enemy) {\n\t\tif (enemy instanceof Fort) {\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n\t@Override\n\tprotected boolean calculateIfCanAttack() {\n\t\treturn this.calculateIfCanAttackByProbability();\n\t}\n\n}"
},
{
"identifier": "Heat",
"path": "src/main/domain/model/environment/Heat.java",
"snippet": "public class Heat extends BaseFavorableEnvironment {\n\t\n\tpublic Heat() {\n\t\tsuper(75);\n\t}\n\n\t@Override\n\tpublic boolean canHandleAttack(final Enemy enemy) {\n\t\tif (enemy instanceof Soldier) {\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n\t@Override\n\tprotected boolean calculateIfCanAttack() {\n\t\treturn this.calculateIfCanAttackByProbability();\n\t}\n\n}"
},
{
"identifier": "Jungle",
"path": "src/main/domain/model/environment/Jungle.java",
"snippet": "public class Jungle extends BaseFavorableEnvironment {\n\tprivate List<Enemy> enemiesCache;\n\t\n\tpublic Jungle(final int probability) {\n\t\tsuper(probability);\n\t\tthis.enemiesCache = new ArrayList<>();\n\t}\n\n\t@Override\n\tpublic boolean canHandleAttack(final Enemy enemy) {\n\t\tif (this.enemiesCache.contains(enemy)) {\n\t\t\tthis.enemiesCache.remove(this.enemiesCache.size() - 1);\n\t\t\treturn true;\n\t\t}\n\t\t\n\t\tthis.enemiesCache.add(enemy);\n\t\treturn false;\n\t}\n\n\t@Override\n\tprotected boolean calculateIfCanAttack() {\n\t\tif (this.enemiesCache.isEmpty()) {\n\t\t\treturn false;\n\t\t}\n\t\treturn this.calculateIfCanAttackByProbability();\n\t}\n\n}"
},
{
"identifier": "Rainy",
"path": "src/main/domain/model/environment/Rainy.java",
"snippet": "public class Rainy extends BaseFavorableEnvironment {\n\t\n\tpublic Rainy() {\n\t\tsuper(50);\n\t}\n\n\t@Override\n\tpublic boolean canHandleAttack(final Enemy enemy) {\n\t\tif (enemy.getLife() > 30) {\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n\t@Override\n\tprotected boolean calculateIfCanAttack() {\n\t\treturn !this.calculateIfCanAttackByProbability();\n\t}\n\n}"
},
{
"identifier": "Bang",
"path": "src/main/domain/model/skill/Bang.java",
"snippet": "public class Bang implements Skillfull {\n\tprivate int remainingUsage;\n\n\tpublic Bang(int remainingUsage) {\n\t\tthis.remainingUsage = remainingUsage;\n\t}\n\n\t@Override\n\tpublic int getEnhancedAttackLevel(int attackLevel, boolean isAttacking) {\n\t\tif (this.remainingUsage > 0) {\n\t\t\tif (isAttacking) {\n\t\t\t\t--this.remainingUsage;\n\t\t\t}\n\t\t\tattackLevel *= 2;\n\t\t}\n\t\treturn attackLevel;\n\t}\n\n\t@Override\n\tpublic Skillfull getClone() {\n\t\treturn new Bang(this.remainingUsage);\n\t}\n\n\t@Override\n\tpublic String getIdentifier() {\n\t\treturn \"B\";\n\t}\n\n}"
},
{
"identifier": "MultipleShots",
"path": "src/main/domain/model/skill/MultipleShots.java",
"snippet": "public class MultipleShots implements Skillfull {\n\tprivate int numberOfSimultaneousShots;\n\n\tpublic MultipleShots(int numberOfSimultaneousShots) {\n\t\tthis.numberOfSimultaneousShots = numberOfSimultaneousShots;\n\t}\n\n\t@Override\n\tpublic int getEnhancedAttackLevel(int attackLevel, boolean isAttacking) {\n\t\treturn attackLevel + numberOfSimultaneousShots;\n\t}\n\n\t@Override\n\tpublic Skillfull getClone() {\n\t\treturn new MultipleShots(this.numberOfSimultaneousShots);\n\t}\n\n\t@Override\n\tpublic String getIdentifier() {\n\t\treturn \"M\";\n\t}\n\n}"
},
{
"identifier": "Poison",
"path": "src/main/domain/model/skill/Poison.java",
"snippet": "public class Poison implements Skillfull {\n\tprivate int substance = 100;\n\n\t@Override\n\tpublic int getEnhancedAttackLevel(int attackLevel, boolean isAttacking) {\n\t\tif (this.substance > 0) {\n\t\t\tif (isAttacking) {\n\t\t\t\t--this.substance;\n\t\t\t}\n\t\t\tattackLevel += 1;\n\t\t}\n\t\treturn attackLevel;\n\t}\n\n\t@Override\n\tpublic Skillfull getClone() {\n\t\treturn new Poison();\n\t}\n\n\t@Override\n\tpublic String getIdentifier() {\n\t\treturn \"V\";\n\t}\n\n}"
}
] | import java.util.ArrayList;
import java.util.List;
import main.application.driver.port.usecase.EnemyMethod;
import main.domain.model.ArmyFactory;
import main.domain.model.Enemy;
import main.domain.model.FavorableEnvironment;
import main.domain.model.Fort;
import main.domain.model.Soldier;
import main.domain.model.Supreme;
import main.domain.model.environment.City;
import main.domain.model.environment.Cold;
import main.domain.model.environment.Heat;
import main.domain.model.environment.Jungle;
import main.domain.model.environment.Rainy;
import main.domain.model.skill.Bang;
import main.domain.model.skill.MultipleShots;
import main.domain.model.skill.Poison; | 3,059 | package main.application.driver.adapter.usecase.factory_enemies;
public class EnemyHighMethod implements EnemyMethod {
private final ArmyFactory armyFactory;
public EnemyHighMethod(final ArmyFactory armyFactory) {
this.armyFactory = armyFactory;
}
@Override
public List<Enemy> createEnemies() {
final List<Enemy> enemies = new ArrayList<>();
final int lifeSoldier = 25;
final int attackLevelSoldier = 5;
final Soldier soldierEnemyBase = armyFactory.createSoldier(lifeSoldier, attackLevelSoldier, new Bang(3));
// supreme
Supreme supreme = armyFactory.getSupreme();
enemies.add(supreme);
// soldiers
final int quantitySoldiers = 5;
for (int created = 1; created <= quantitySoldiers; created++) {
final Soldier soldierEnemy = soldierEnemyBase.clone();
enemies.add(soldierEnemy);
supreme.addProtector(soldierEnemy);
}
// soldiers with fort
final int quantitySoldiersWithFork = 2;
for (int created = 1; created <= quantitySoldiersWithFork; created++) {
enemies.add(new Fort(soldierEnemyBase.clone()));
}
// infantry
final int quantitySquadron = 2;
final int quantitySoldiersForSquadron = 3;
final List<Enemy> squadronsAndSoldiers = new ArrayList<>();
for (int createdSquadron = 1; createdSquadron <= quantitySquadron; createdSquadron++) {
final List<Enemy> soldiers = new ArrayList<>();
for (int created = 1; created <= quantitySoldiersForSquadron; created++) {
soldiers.add(soldierEnemyBase.clone());
}
Enemy squadron = armyFactory.createSquadron(soldiers, new MultipleShots(2));
if (createdSquadron == 1) {
squadron = new Fort(squadron);
}
squadronsAndSoldiers.add(squadron);
}
final int quantitySoldiersInSquadron = 4;
for (int created = 1; created <= quantitySoldiersInSquadron; created++) {
squadronsAndSoldiers.add(soldierEnemyBase.clone());
}
final Enemy infantry = armyFactory.createSquadron(squadronsAndSoldiers, new Poison());
enemies.add(infantry);
return enemies;
}
@Override
public FavorableEnvironment createFavorableEnvironments() {
final FavorableEnvironment favorableEnvironmentFirst = new Heat();
final FavorableEnvironment favorableEnvironmentSecond = new Cold();
final FavorableEnvironment favorableEnvironmentThird = new Rainy(); | package main.application.driver.adapter.usecase.factory_enemies;
public class EnemyHighMethod implements EnemyMethod {
private final ArmyFactory armyFactory;
public EnemyHighMethod(final ArmyFactory armyFactory) {
this.armyFactory = armyFactory;
}
@Override
public List<Enemy> createEnemies() {
final List<Enemy> enemies = new ArrayList<>();
final int lifeSoldier = 25;
final int attackLevelSoldier = 5;
final Soldier soldierEnemyBase = armyFactory.createSoldier(lifeSoldier, attackLevelSoldier, new Bang(3));
// supreme
Supreme supreme = armyFactory.getSupreme();
enemies.add(supreme);
// soldiers
final int quantitySoldiers = 5;
for (int created = 1; created <= quantitySoldiers; created++) {
final Soldier soldierEnemy = soldierEnemyBase.clone();
enemies.add(soldierEnemy);
supreme.addProtector(soldierEnemy);
}
// soldiers with fort
final int quantitySoldiersWithFork = 2;
for (int created = 1; created <= quantitySoldiersWithFork; created++) {
enemies.add(new Fort(soldierEnemyBase.clone()));
}
// infantry
final int quantitySquadron = 2;
final int quantitySoldiersForSquadron = 3;
final List<Enemy> squadronsAndSoldiers = new ArrayList<>();
for (int createdSquadron = 1; createdSquadron <= quantitySquadron; createdSquadron++) {
final List<Enemy> soldiers = new ArrayList<>();
for (int created = 1; created <= quantitySoldiersForSquadron; created++) {
soldiers.add(soldierEnemyBase.clone());
}
Enemy squadron = armyFactory.createSquadron(soldiers, new MultipleShots(2));
if (createdSquadron == 1) {
squadron = new Fort(squadron);
}
squadronsAndSoldiers.add(squadron);
}
final int quantitySoldiersInSquadron = 4;
for (int created = 1; created <= quantitySoldiersInSquadron; created++) {
squadronsAndSoldiers.add(soldierEnemyBase.clone());
}
final Enemy infantry = armyFactory.createSquadron(squadronsAndSoldiers, new Poison());
enemies.add(infantry);
return enemies;
}
@Override
public FavorableEnvironment createFavorableEnvironments() {
final FavorableEnvironment favorableEnvironmentFirst = new Heat();
final FavorableEnvironment favorableEnvironmentSecond = new Cold();
final FavorableEnvironment favorableEnvironmentThird = new Rainy(); | final FavorableEnvironment favorableEnvironmentFourth = new Jungle(12); | 10 | 2023-10-20 18:36:47+00:00 | 4k |
Squawkykaka/when_pigs_fly | src/main/java/com/squawkykaka/when_pigs_fly/commands/Spawn.java | [
{
"identifier": "CommandBase",
"path": "src/main/java/com/squawkykaka/when_pigs_fly/util/CommandBase.java",
"snippet": "public abstract class CommandBase extends BukkitCommand implements CommandExecutor {\n private List<String> delayedPlayers = null;\n private int delay = 0;\n private final int minArguments;\n private final int maxArguments;\n private final boolean playerOnly;\n public CommandBase(String command) {\n this(command, 0);\n }\n\n public CommandBase(String command, boolean playerOnly) {\n this(command, 0, playerOnly);\n }\n\n public CommandBase(String command, int requiredArguments) {\n this(command, requiredArguments, requiredArguments);\n }\n\n public CommandBase(String command, int minArguments, int maxArguments) {\n this(command, minArguments, maxArguments, false);\n }\n\n public CommandBase(String command, int requiredArguments, boolean playerOnly) {\n this(command, requiredArguments, requiredArguments, playerOnly);\n }\n\n public CommandBase(String command, int minArguments, int maxArguments, boolean playerOnly) {\n super(command);\n\n this.minArguments = minArguments;\n this.maxArguments = maxArguments;\n this.playerOnly = playerOnly;\n\n CommandMap commandMap = getCommandMap();\n if (command != null) {\n commandMap.register(command, this);\n }\n }\n\n public CommandMap getCommandMap() {\n try {\n if (Bukkit.getPluginManager() instanceof SimplePluginManager) {\n Field field = SimplePluginManager.class.getDeclaredField(\"commandMap\");\n field.setAccessible(true);\n\n return (CommandMap) field.get(Bukkit.getPluginManager());\n }\n } catch (NoSuchFieldException | IllegalAccessException e) {\n e.printStackTrace();\n }\n return null;\n }\n\n public CommandBase enableDelay(int delay) {\n this.delay = delay;\n this.delayedPlayers = new ArrayList<>();\n return this;\n }\n\n public void removeDelay(Player player) {\n this.delayedPlayers.remove(player.getName());\n }\n\n public void sendUsage(CommandSender sender) {\n Msg.send(sender, getUsage());\n }\n\n public boolean execute(CommandSender sender, String alias, String [] arguments) {\n if (arguments.length < minArguments || (arguments.length > maxArguments && maxArguments != -1)) {\n sendUsage(sender);\n return true;\n }\n\n if (playerOnly && !(sender instanceof Player)) {\n Msg.send(sender,\"&cOnly players can use this command.\");\n return true;\n }\n\n String permission = getPermission();\n if (permission != null && !sender.hasPermission(permission)) {\n Msg.send(sender, \"&cYou do not have permission to use this command.\");\n return true;\n }\n\n if (delayedPlayers != null && sender instanceof Player) {\n Player player = (Player) sender;\n if (delayedPlayers.contains(player.getName())) {\n Msg.send(player, \"&cPlease wait \" + delay + \" seconds before using this command again.\");\n return true;\n }\n\n delayedPlayers.add(player.getName());\n Bukkit.getScheduler().scheduleSyncDelayedTask(WhenPigsFly.getInstance(), () -> {\n delayedPlayers.remove(player.getName());\n }, 20L * delay);\n }\n\n if (!onCommand(sender, arguments))\n sendUsage(sender);\n\n return true;\n }\n\n public boolean onCommand(CommandSender sender, Command command, String alias, String [] arguments) {\n return this.onCommand(sender, arguments);\n }\n\n public abstract boolean onCommand(CommandSender sender, String [] arguments);\n\n public abstract String getUsage();\n}"
},
{
"identifier": "EventUtil",
"path": "src/main/java/com/squawkykaka/when_pigs_fly/util/EventUtil.java",
"snippet": "public class EventUtil {\n public static void register(Listener listener) {\n Bukkit.getServer().getPluginManager().registerEvents(listener, WhenPigsFly.getInstance());\n }\n}"
},
{
"identifier": "Msg",
"path": "src/main/java/com/squawkykaka/when_pigs_fly/util/Msg.java",
"snippet": "public class Msg {\n public static void send(CommandSender sender, String message) {\n send(sender, message, \"&a\");\n }\n\n public static void send(CommandSender sender, String message, String prefix) {\n sender.sendMessage(ChatColor.translateAlternateColorCodes('&', prefix + message));\n }\n}"
},
{
"identifier": "WhenPigsFly",
"path": "src/main/java/com/squawkykaka/when_pigs_fly/WhenPigsFly.java",
"snippet": "public final class WhenPigsFly extends JavaPlugin {\n\n private static WhenPigsFly instance;\n\n @Override\n public void onEnable() {\n instance = this; // Set the instance to the current plugin\n saveDefaultConfig();\n getLogger().info(\"------------------------\");\n getLogger().info(\"---- Plugin Loading ----\");\n\n EventUtil.register(new AxolotlThrowListener(this));\n EventUtil.register(new PluginEvents());\n new Heal_Feed();\n new Spawn(this);\n new Menu(this);\n Metrics metrics = new Metrics(this, 20271);\n getLogger().info(\"------------------------\");\n getLogger().info(\"---- Plugin enabled ----\");\n getLogger().info(\"------------------------\");\n }\n\n @Override\n public void onDisable() {\n getLogger().info(\"Plugin disabled.\");\n }\n\n // Create a method to obtain the plugin instance\n public static WhenPigsFly getInstance() {\n return instance;\n }\n}"
}
] | import com.squawkykaka.when_pigs_fly.util.CommandBase;
import com.squawkykaka.when_pigs_fly.util.EventUtil;
import com.squawkykaka.when_pigs_fly.util.Msg;
import com.squawkykaka.when_pigs_fly.WhenPigsFly;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.Player; | 1,618 | package com.squawkykaka.when_pigs_fly.commands;
public class Spawn {
private Location spawn = null;
public Spawn(WhenPigsFly plugin) {
FileConfiguration config = plugin.getConfig();
String worldName = config.getString("spawn.world");
if (worldName == null) {
Bukkit.getLogger().warning("spawn.world does not exist within config.yml");
return;
}
World world = Bukkit.getWorld(worldName);
if (world == null) {
Bukkit.getLogger().severe("World \"" + worldName + "\" does not exist.");
return;
}
int x = config.getInt("spawn.x");
int y = config.getInt("spawn.y");
int z = config.getInt("spawn.z");
float yaw = (float) config.getDouble("spawn.yaw");
float pitch = (float) config.getDouble("spawn.pitch");
spawn = new Location(world, x, y, z, yaw, pitch);
| package com.squawkykaka.when_pigs_fly.commands;
public class Spawn {
private Location spawn = null;
public Spawn(WhenPigsFly plugin) {
FileConfiguration config = plugin.getConfig();
String worldName = config.getString("spawn.world");
if (worldName == null) {
Bukkit.getLogger().warning("spawn.world does not exist within config.yml");
return;
}
World world = Bukkit.getWorld(worldName);
if (world == null) {
Bukkit.getLogger().severe("World \"" + worldName + "\" does not exist.");
return;
}
int x = config.getInt("spawn.x");
int y = config.getInt("spawn.y");
int z = config.getInt("spawn.z");
float yaw = (float) config.getDouble("spawn.yaw");
float pitch = (float) config.getDouble("spawn.pitch");
spawn = new Location(world, x, y, z, yaw, pitch);
| new CommandBase("setspawn", true) { | 0 | 2023-10-17 02:07:39+00:00 | 4k |
greatwqs/finance-manager | src/main/java/com/github/greatwqs/app/controller/TicketController.java | [
{
"identifier": "RequestComponent",
"path": "src/main/java/com/github/greatwqs/app/component/RequestComponent.java",
"snippet": "@Slf4j\n@Component\npublic class RequestComponent {\n\n public HttpServletRequest getRequest() {\n if (getRequestAttributes() != null) {\n return getRequestAttributes().getRequest();\n } else {\n return null;\n }\n }\n\n public String getRequestUri() {\n HttpServletRequest request = getRequest();\n if (request == null) {\n return \"unkonw uri\";\n } else {\n return request.getRequestURI();\n }\n }\n\n public String getRequestUrl() {\n HttpServletRequest request = getRequest();\n if (request == null) {\n return \"unkonw url\";\n } else {\n return request.getRequestURL().toString();\n }\n }\n\n public HttpServletResponse getResponse() {\n return getRequestAttributes().getResponse();\n }\n\n public ServletRequestAttributes getRequestAttributes() {\n return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes());\n }\n\n /***\n * getExecuteIp\n * @return\n */\n public String getClientIp() {\n HttpServletRequest request = getRequest();\n if (request == null) {\n return \"\";\n }\n String ip = request.getHeader(\"x-forwarded-for\");\n if (StringUtils.isBlank(ip) || \"unknown\".equalsIgnoreCase(ip)) {\n ip = request.getHeader(\"Proxy-Client-IP\");\n }\n if (StringUtils.isBlank(ip) || \"unknown\".equalsIgnoreCase(ip)) {\n ip = request.getHeader(\"WL-Proxy-Client-IP\");\n }\n if (StringUtils.isBlank(ip) || \"unknown\".equalsIgnoreCase(ip)) {\n ip = request.getRemoteAddr();\n }\n if (StringUtils.isBlank(ip) || \"unknown\".equalsIgnoreCase(ip)) {\n ip = request.getHeader(\"X-Real-IP\");\n }\n if (ip != null && ip.trim().length() > 0) {\n int index = ip.indexOf(',');\n return (index != -1) ? ip.substring(0, index) : ip;\n }\n return ip;\n }\n\n /***\n * default zh_CN\n * @return\n */\n public Locale getLocale() {\n return AppConstants.LOCALE;\n }\n\n /***\n * get locale\n * @return\n */\n private Locale getRequestLocale() {\n HttpServletRequest request = getRequest();\n final String APP_LOCALE = \"app_locale\";\n final Cookie cookie = WebUtils.getCookie(request, APP_LOCALE);\n if (cookie != null && StringUtils.isNotEmpty(cookie.getValue())) {\n return org.springframework.util.StringUtils.parseLocaleString(cookie.getValue());\n }\n\n /**\n * based on the Accept-Language header. If the client request\n * doesn't provide an Accept-Language header, this method returns the\n * default locale for the server.\n */\n return request.getLocale();\n }\n\n public void setParam(String key, Object value) {\n RequestContextHolder.currentRequestAttributes()\n .setAttribute(key, value, RequestAttributes.SCOPE_REQUEST);\n }\n\n public Object getParam(String key) {\n return RequestContextHolder.currentRequestAttributes()\n .getAttribute(key, RequestAttributes.SCOPE_REQUEST);\n }\n\n public UserPo getLoginUser() {\n return (UserPo) RequestContextHolder.currentRequestAttributes()\n .getAttribute(AppConstants.REQUEST_USER, RequestAttributes.SCOPE_REQUEST);\n }\n\n public String getLoginToken() {\n return (String) RequestContextHolder.currentRequestAttributes()\n .getAttribute(AppConstants.REQUEST_USER_TOKEN, RequestAttributes.SCOPE_REQUEST);\n }\n}"
},
{
"identifier": "TicketTypeDto",
"path": "src/main/java/com/github/greatwqs/app/domain/dto/TicketTypeDto.java",
"snippet": "@Getter\n@Setter\n@ToString\npublic class TicketTypeDto {\n private Long id;\n\n private String name;\n\n private Long createuserid;\n\n private Long updateuserid;\n}"
},
{
"identifier": "TicketTypePo",
"path": "src/main/java/com/github/greatwqs/app/domain/po/TicketTypePo.java",
"snippet": "@Getter\n@Setter\n@ToString\npublic class TicketTypePo {\n private Long id;\n\n private String name;\n\n private Boolean isvalid;\n\n private Long createuserid;\n\n private Date createtime;\n\n private Long updateuserid;\n\n private Date updatetime;\n}"
},
{
"identifier": "UserPo",
"path": "src/main/java/com/github/greatwqs/app/domain/po/UserPo.java",
"snippet": "@Getter\n@Setter\n@ToString\npublic class UserPo {\n\n\tprivate Long id;\n\n\tprivate String username;\n\n\tprivate String password;\n\n\tprivate String content;\n\n\tprivate Boolean issuperadmin;\n\n\tprivate Boolean isvalid;\n\n\tprivate Date createtime;\n\n\tprivate Date updatetime;\n}"
},
{
"identifier": "SubjectVo",
"path": "src/main/java/com/github/greatwqs/app/domain/vo/SubjectVo.java",
"snippet": "@Getter\n@Setter\n@ToString\npublic class SubjectVo {\n private Long id;\n\n private String school;\n\n private String name;\n\n private Boolean isvalid;\n\n private Long createuserid;\n\n private Date createtime;\n\n private Long updateuserid;\n\n private Date updatetime;\n}"
},
{
"identifier": "TicketTypeVo",
"path": "src/main/java/com/github/greatwqs/app/domain/vo/TicketTypeVo.java",
"snippet": "@Getter\n@Setter\n@ToString\npublic class TicketTypeVo {\n private Long id;\n\n private String name;\n\n private Boolean isvalid;\n\n private Long createuserid;\n\n private Date createtime;\n\n private Long updateuserid;\n\n private Date updatetime;\n}"
},
{
"identifier": "TicketTypeManager",
"path": "src/main/java/com/github/greatwqs/app/manager/TicketTypeManager.java",
"snippet": "public interface TicketTypeManager {\n\n void insert(TicketTypePo ticketTypePo);\n\n TicketTypePo getPo(String ticketTypeName);\n\n List<TicketTypePo> getPoList(List<Long> ticketTypeIdList);\n\n TicketTypeVo getVo(Long ticketTypeId);\n\n List<TicketTypeVo> getVoList(List<Long> ticketTypeIdList);\n\n Map<Long, TicketTypeVo> getVoMap(List<Long> ticketTypeIdList);\n\n Map<String, TicketTypeVo> getNameVoMap();\n\n void update(TicketTypePo ticketTypePo);\n\n void delete(Long ticketTypeId, Long userId);\n}"
},
{
"identifier": "TicketTypeService",
"path": "src/main/java/com/github/greatwqs/app/service/TicketTypeService.java",
"snippet": "public interface TicketTypeService {\n\n List<TicketTypeVo> getAllTicketTypes();\n\n Long add(TicketTypeDto ticketTypeDto);\n\n void update(TicketTypeDto ticketTypeDto);\n\n /***\n * 返回 Boolean:\n * true: 删除成功\n * false: 未删除 (exist order)\n * @param ticketTypeId\n * @param userId\n * @return\n */\n Boolean delete(Long ticketTypeId, Long userId);\n}"
}
] | import com.github.greatwqs.app.component.RequestComponent;
import com.github.greatwqs.app.domain.dto.TicketTypeDto;
import com.github.greatwqs.app.domain.po.TicketTypePo;
import com.github.greatwqs.app.domain.po.UserPo;
import com.github.greatwqs.app.domain.vo.SubjectVo;
import com.github.greatwqs.app.domain.vo.TicketTypeVo;
import com.github.greatwqs.app.interceptor.annotation.LoginRequired;
import com.github.greatwqs.app.manager.TicketTypeManager;
import com.github.greatwqs.app.service.TicketTypeService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List; | 1,898 | package com.github.greatwqs.app.controller;
/**
* 票据类型
*
* @author greatwqs
* Create on 2020/6/27
*/
@RestController
@RequestMapping("ticket")
public class TicketController {
@Autowired
private TicketTypeManager ticketTypeManager;
@Autowired
private TicketTypeService ticketTypeService;
@Autowired | package com.github.greatwqs.app.controller;
/**
* 票据类型
*
* @author greatwqs
* Create on 2020/6/27
*/
@RestController
@RequestMapping("ticket")
public class TicketController {
@Autowired
private TicketTypeManager ticketTypeManager;
@Autowired
private TicketTypeService ticketTypeService;
@Autowired | private RequestComponent requestComponent; | 0 | 2023-10-16 12:45:57+00:00 | 4k |
Wind-Gone/Vodka | code/src/main/java/benchmark/olap/OLAPClient.java | [
{
"identifier": "OrderLine",
"path": "code/src/main/java/bean/OrderLine.java",
"snippet": "@Getter\npublic class OrderLine {\n public Timestamp ol_delivery_d;\n public Timestamp ol_receipdate;\n public Timestamp ol_commitdate;\n\n public OrderLine(Timestamp ol_delivery_d, Timestamp ol_commitdate, Timestamp ol_receiptdate) {\n this.ol_delivery_d = ol_delivery_d;\n this.ol_receipdate = ol_receiptdate;\n this.ol_commitdate = ol_commitdate;\n }\n\n public int compareToByReceiptDate(OrderLine other) {\n return ol_receipdate.compareTo(other.ol_receipdate);\n }\n\n public int compareToByDeliveryDate(OrderLine other) {\n return ol_delivery_d.compareTo(other.ol_delivery_d);\n }\n\n public int compareToByCommitDate(OrderLine other) {\n return ol_commitdate.compareTo(other.ol_commitdate);\n }\n}"
},
{
"identifier": "ReservoirSamplingSingleton",
"path": "code/src/main/java/bean/ReservoirSamplingSingleton.java",
"snippet": "public class ReservoirSamplingSingleton {\n\n // 私有构造函数,防止直接实例化\n private ReservoirSamplingSingleton() {\n }\n\n private static final class InstanceHolder {\n private static final ReservoirSampling instance = new ReservoirSampling(400000);\n }\n\n // 获取单例实例\n public static ReservoirSampling getInstance() {\n return InstanceHolder.instance;\n }\n}"
},
{
"identifier": "baseQuery",
"path": "code/src/main/java/benchmark/olap/query/baseQuery.java",
"snippet": "public abstract class baseQuery {\n public String q;\n public String name;\n public double filterRate;\n // public long tpmc;\n public String dynamicParam;\n // public int warehouseNumber;\n public static int orderOriginSize = 4500000; //oorder表的原始大小 已调整在initFilterRatio函数里一并更新\n public static int olOriginSize = 44997903; //orderline表的原始大小\n public static int olNotnullSize = 31498050; //orderline表非空的数量\n// public int orderTSize; //oorder表的实时大小\n// public int orderlineTSize; //orderline表的实时大小\n\n baseQuery() throws ParseException {\n // this.tpmc = tpmc;\n // this.q = getQuery();\n this.name = this.getClass().getName();\n // this.warehouseNumber = warehouseNumber;\n // this.orderTSize = OLAPTerminal.oorderTableSize;\n // this.orderlineTSize = OLAPTerminal.orderLineTableSize;\n }\n\n public abstract String getQuery() throws ParseException;\n\n public abstract String updateQuery() throws ParseException;\n\n // public abstract String getCountQuery();\n public abstract String getExplainQuery();\n\n public abstract String getFilterCheckQuery();\n\n public abstract String getDetailedExecutionPlan();\n\n public Date getDateAfter(Date d, int s) {\n Calendar now = Calendar.getInstance();\n now.setTime(d);\n// System.out.println(\"原先的时间是:\" + now.getTime() + \",需要增加\" + s + \"秒\");\n now.add(Calendar.SECOND, s);\n // now.set(Calendar.DATE, now.get(Calendar.DATE) + day);\n// System.out.println(\"现在的时间是:\" + now.getTime());\n return now.getTime();\n }\n\n// public static void setTableSize(int orderOriginSize, int olOriginSize, int olNotnullSize) {\n// this.orderOriginSize = orderOriginSize;\n//\n// }\n}"
},
{
"identifier": "CommonConfig",
"path": "code/src/main/java/config/CommonConfig.java",
"snippet": "public interface CommonConfig {\n String VdokaVersion = \"1.0 DEV\";\n\n int DB_UNKNOWN = 0,\n DB_FIREBIRD = 1,\n DB_ORACLE = 2,\n DB_POSTGRES = 3,\n DB_OCEANBASE = 4,\n DB_TIDB = 5,\n DB_POLARDB = 6,\n DB_GAUSSDB = 7,\n DB_MYSQL = 8;\n\n int NEW_ORDER = 1,\n PAYMENT = 2,\n ORDER_STATUS = 3,\n DELIVERY = 4,\n STOCK_LEVEL = 5,\n RECIEVE_GOODS = 6;\n\n SimpleDateFormat dateFormat = new SimpleDateFormat(\"yyyy-MM-dd HH:mm:ss\");\n\n\n}"
}
] | import bean.OrderLine;
import bean.ReservoirSamplingSingleton;
import benchmark.olap.query.baseQuery;
import config.CommonConfig;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.sql.*;
import java.util.Arrays;
import java.util.Properties;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger; | 1,696 | package benchmark.olap;
public class OLAPClient {
private static Logger log = Logger.getLogger(OLAPClient.class);
private static Properties dbProps;
private static Integer queryNumber = 22;
private static Integer seed = 2023;
public static double[] filterRate = { 0.700, 1, 0.3365, 0.2277, 0.3040,
0.2098, 0.3156, 0.4555, 1, 0.2659,
1, 0.2054, 1, 0.3857, 0.4214,
1, 1, 1, 1, 0.2098,
1, 1, 1 };
public static void initFilterRatio(String database, Properties dbProps, int dbType) {
log.info("Initiating filter rate ...");
try {
Connection con = DriverManager.getConnection(database, dbProps);
Statement stmt = con.createStatement();
if (dbType == CommonConfig.DB_POSTGRES) {
stmt.execute("SET max_parallel_workers_per_gather = 64;");
}
ResultSet result;
for (int i = 0; i < queryNumber; i++) {
String filterSQLPath = "filterQuery/" + (i + 1) + ".sql";
if (dbType == CommonConfig.DB_POSTGRES || dbType == CommonConfig.DB_POLARDB)
filterSQLPath = "filterQuery/pg/" + (i + 1) + ".sql";
if (i == 0 || i == 2 || i == 3 | i == 4 || i == 5 || i == 6 || i == 7 || i == 9 || i == 11 || i == 13
|| i == 14 || i == 19) {
String filterSQLQuery = OLAPClient.readSQL(filterSQLPath);
System.out.println("We are executing query: " + filterSQLQuery);
result = stmt.executeQuery(filterSQLQuery);
if (result.next())
filterRate[i] = Double.parseDouble(result.getString(1));
} else
filterRate[i] = 1;
}
System.out.println(
"We are executing query: select count(*) from vodka_order_line where ol_delivery_d IS NOT NULL;");
result = stmt.executeQuery("select count(*) from vodka_order_line where ol_delivery_d IS NOT NULL;");
if (result.next()) | package benchmark.olap;
public class OLAPClient {
private static Logger log = Logger.getLogger(OLAPClient.class);
private static Properties dbProps;
private static Integer queryNumber = 22;
private static Integer seed = 2023;
public static double[] filterRate = { 0.700, 1, 0.3365, 0.2277, 0.3040,
0.2098, 0.3156, 0.4555, 1, 0.2659,
1, 0.2054, 1, 0.3857, 0.4214,
1, 1, 1, 1, 0.2098,
1, 1, 1 };
public static void initFilterRatio(String database, Properties dbProps, int dbType) {
log.info("Initiating filter rate ...");
try {
Connection con = DriverManager.getConnection(database, dbProps);
Statement stmt = con.createStatement();
if (dbType == CommonConfig.DB_POSTGRES) {
stmt.execute("SET max_parallel_workers_per_gather = 64;");
}
ResultSet result;
for (int i = 0; i < queryNumber; i++) {
String filterSQLPath = "filterQuery/" + (i + 1) + ".sql";
if (dbType == CommonConfig.DB_POSTGRES || dbType == CommonConfig.DB_POLARDB)
filterSQLPath = "filterQuery/pg/" + (i + 1) + ".sql";
if (i == 0 || i == 2 || i == 3 | i == 4 || i == 5 || i == 6 || i == 7 || i == 9 || i == 11 || i == 13
|| i == 14 || i == 19) {
String filterSQLQuery = OLAPClient.readSQL(filterSQLPath);
System.out.println("We are executing query: " + filterSQLQuery);
result = stmt.executeQuery(filterSQLQuery);
if (result.next())
filterRate[i] = Double.parseDouble(result.getString(1));
} else
filterRate[i] = 1;
}
System.out.println(
"We are executing query: select count(*) from vodka_order_line where ol_delivery_d IS NOT NULL;");
result = stmt.executeQuery("select count(*) from vodka_order_line where ol_delivery_d IS NOT NULL;");
if (result.next()) | baseQuery.olNotnullSize = Integer.parseInt(result.getString(1)); | 2 | 2023-10-22 11:22:32+00:00 | 4k |
Onuraktasj/stock-tracking-system | src/main/java/com/onuraktas/stocktrackingsystem/impl/CategoryServiceImpl.java | [
{
"identifier": "CategoryProducer",
"path": "src/main/java/com/onuraktas/stocktrackingsystem/amqp/producer/CategoryProducer.java",
"snippet": "@Component\npublic class CategoryProducer {\n\n private final RabbitTemplate rabbitTemplate;\n\n\n public CategoryProducer(RabbitTemplate rabbitTemplate) {\n this.rabbitTemplate = rabbitTemplate;\n }\n\n public void sendToQueue(DeletedCategoryMessage message) {\n rabbitTemplate.convertAndSend(QueueName.DELETED_CATEGORY_QUEUE, message);\n }\n}"
},
{
"identifier": "DeletedCategoryMessage",
"path": "src/main/java/com/onuraktas/stocktrackingsystem/dto/amqp/DeletedCategoryMessage.java",
"snippet": "@Getter\n@Setter\n@EqualsAndHashCode\n@ToString\n@NoArgsConstructor\n@AllArgsConstructor(access = AccessLevel.PRIVATE)\n@Builder\npublic class DeletedCategoryMessage implements Serializable {\n\n private UUID categoryId;\n}"
},
{
"identifier": "CategoryDto",
"path": "src/main/java/com/onuraktas/stocktrackingsystem/dto/entity/CategoryDto.java",
"snippet": "@Getter\n@Setter\n@NoArgsConstructor\n@AllArgsConstructor(access = AccessLevel.PRIVATE)\n@ToString\n@EqualsAndHashCode\n@Builder\npublic class CategoryDto implements Serializable {\n\n private UUID categoryId;\n private String categoryName;\n private Boolean isActive;\n}"
},
{
"identifier": "CreateCategoryRequest",
"path": "src/main/java/com/onuraktas/stocktrackingsystem/dto/request/CreateCategoryRequest.java",
"snippet": "@Getter\n@Setter\n@NoArgsConstructor\n@AllArgsConstructor(access = AccessLevel.PRIVATE)\n@ToString\n@EqualsAndHashCode\n@Builder\npublic class CreateCategoryRequest {\n\n private String categoryName;\n}"
},
{
"identifier": "UpdateCategoryNameRequest",
"path": "src/main/java/com/onuraktas/stocktrackingsystem/dto/request/UpdateCategoryNameRequest.java",
"snippet": "@Getter\n@Setter\n@NoArgsConstructor\n@AllArgsConstructor(access = AccessLevel.PRIVATE)\n@ToString\n@EqualsAndHashCode\n@Builder\npublic class UpdateCategoryNameRequest {\n\n private String categoryName;\n}"
},
{
"identifier": "CreateCategoryResponse",
"path": "src/main/java/com/onuraktas/stocktrackingsystem/dto/response/CreateCategoryResponse.java",
"snippet": "@Getter\n@Setter\n@NoArgsConstructor\n@AllArgsConstructor(access = AccessLevel.PRIVATE)\n@ToString\n@EqualsAndHashCode\n@SuperBuilder\npublic class CreateCategoryResponse {\n\n private String status;\n\n private UUID categoryId;\n\n\n}"
},
{
"identifier": "DeleteCategoryResponse",
"path": "src/main/java/com/onuraktas/stocktrackingsystem/dto/response/DeleteCategoryResponse.java",
"snippet": "@Getter\n@Setter\n@NoArgsConstructor\n@AllArgsConstructor(access = AccessLevel.PRIVATE)\n@ToString\n@EqualsAndHashCode\n@Builder\npublic class DeleteCategoryResponse {\n\n public UUID categoryId;\n}"
},
{
"identifier": "Category",
"path": "src/main/java/com/onuraktas/stocktrackingsystem/entity/Category.java",
"snippet": "@AllArgsConstructor\n@NoArgsConstructor\n@Getter\n@Setter\n@EqualsAndHashCode\n@ToString\n@Builder\n@Entity\npublic class Category {\n\n @Id\n @GeneratedValue(strategy = GenerationType.AUTO)\n private UUID categoryId;\n private String categoryName;\n @Builder.Default\n private Boolean isActive = true;\n}"
},
{
"identifier": "Status",
"path": "src/main/java/com/onuraktas/stocktrackingsystem/entity/enums/Status.java",
"snippet": "public enum Status {\n\n OK(\"OK\"),\n NOK(\"NOK\");\n\n private final String status;\n\n Status(String status){\n this.status = status;\n }\n\n public String getStatus(){\n return status;\n }\n}"
},
{
"identifier": "CategoryAlreadyExistsException",
"path": "src/main/java/com/onuraktas/stocktrackingsystem/exception/CategoryAlreadyExistsException.java",
"snippet": "public class CategoryAlreadyExistsException extends RuntimeException{\n\n private final String message;\n\n public CategoryAlreadyExistsException(String message){\n this.message = message;\n }\n\n @Override\n public String getMessage() {\n return message;\n }\n}"
},
{
"identifier": "CategoryBadRequestException",
"path": "src/main/java/com/onuraktas/stocktrackingsystem/exception/CategoryBadRequestException.java",
"snippet": "public class CategoryBadRequestException extends RuntimeException {\n\n private final String message;\n\n public CategoryBadRequestException(String message) {\n this.message = message;\n }\n\n @Override\n public String getMessage() {\n return message;\n }\n}"
},
{
"identifier": "CategoryNotFoundException",
"path": "src/main/java/com/onuraktas/stocktrackingsystem/exception/CategoryNotFoundException.java",
"snippet": "public class CategoryNotFoundException extends RuntimeException {\n\n private final String message;\n public CategoryNotFoundException(String message) {\n this.message = message;\n }\n\n @Override\n public String getMessage() {\n return message;\n }\n}"
},
{
"identifier": "CategoryMapper",
"path": "src/main/java/com/onuraktas/stocktrackingsystem/mapper/CategoryMapper.java",
"snippet": "public class CategoryMapper {\n\n public static CategoryDto toDto(Category category){\n if (Objects.isNull(category))\n return null;\n\n return CategoryDto.builder()\n .categoryId(category.getCategoryId())\n .categoryName(category.getCategoryName())\n .isActive(category.getIsActive())\n .build();\n }\n\n public static CategoryDto toEntity(Category category){\n if (Objects.isNull(category))\n return null;\n return CategoryDto.builder()\n .categoryId(category.getCategoryId())\n .categoryName(category.getCategoryName())\n .isActive(category.getIsActive())\n .build();\n }\n\n public static Category toEntity(CategoryDto categoryDto){\n if (Objects.isNull(categoryDto))\n return null;\n return Category.builder()\n .categoryName(categoryDto.getCategoryName())\n .build();\n }\n\n public static Category toEntity(CreateCategoryRequest categoryRequest){\n if (Objects.isNull(categoryRequest))\n return null;\n return Category.builder()\n .categoryName(categoryRequest.getCategoryName())\n .build();\n }\n\n public static CreateCategoryResponse toCreateCategoryResponse(Category category){\n if (Objects.isNull(category))\n return null;\n return CreateCategoryResponse.builder()\n .categoryId(category.getCategoryId())\n .build();\n }\n\n public static List<CategoryDto> toDtoList(List<Category> categories){\n return categories.stream().parallel()\n .map(CategoryMapper::toDto)\n .toList();\n }\n}"
},
{
"identifier": "CategoryMessages",
"path": "src/main/java/com/onuraktas/stocktrackingsystem/message/CategoryMessages.java",
"snippet": "public class CategoryMessages {\n\n public static final String CATEGORY_ALREADY_EXIST = \"Category already exist\";\n public static final String CATEGORY_NOT_FOUND = \"Category not found\";\n public static final String CATEGORY_NAME_CANNOT_BE_NULL = \"Category name cannot be null\";\n public static final String CATEGORY_ID_NOT_MATCH = \"Category id not match\";\n}"
},
{
"identifier": "CategoryRepository",
"path": "src/main/java/com/onuraktas/stocktrackingsystem/repository/CategoryRepository.java",
"snippet": "public interface CategoryRepository extends JpaRepository<Category, UUID> {\n\n Optional<Category> findByCategoryIdAndIsActive(UUID categoryId, Boolean isActive);\n\n Category findByCategoryName(String categoryName);\n\n List<Category> findAllByCategoryIdInAndIsActive(List<UUID> categoryIds, Boolean isActive);\n}"
},
{
"identifier": "CategoryService",
"path": "src/main/java/com/onuraktas/stocktrackingsystem/service/CategoryService.java",
"snippet": "public interface CategoryService {\n CreateCategoryResponse createCategory(CreateCategoryRequest categoryRequest);\n\n List<CategoryDto> getAllCategory();\n\n CategoryDto getCategory(UUID categoryId);\n\n CategoryDto updateCategory(UUID categoryId, CategoryDto categoryDto);\n\n CategoryDto updateCategory(UUID categoryId, UpdateCategoryNameRequest request);\n\n DeleteCategoryResponse deleteCategory(UUID categoryId);\n}"
}
] | import com.onuraktas.stocktrackingsystem.amqp.producer.CategoryProducer;
import com.onuraktas.stocktrackingsystem.dto.amqp.DeletedCategoryMessage;
import com.onuraktas.stocktrackingsystem.dto.entity.CategoryDto;
import com.onuraktas.stocktrackingsystem.dto.request.CreateCategoryRequest;
import com.onuraktas.stocktrackingsystem.dto.request.UpdateCategoryNameRequest;
import com.onuraktas.stocktrackingsystem.dto.response.CreateCategoryResponse;
import com.onuraktas.stocktrackingsystem.dto.response.DeleteCategoryResponse;
import com.onuraktas.stocktrackingsystem.entity.Category;
import com.onuraktas.stocktrackingsystem.entity.enums.Status;
import com.onuraktas.stocktrackingsystem.exception.CategoryAlreadyExistsException;
import com.onuraktas.stocktrackingsystem.exception.CategoryBadRequestException;
import com.onuraktas.stocktrackingsystem.exception.CategoryNotFoundException;
import com.onuraktas.stocktrackingsystem.mapper.CategoryMapper;
import com.onuraktas.stocktrackingsystem.message.CategoryMessages;
import com.onuraktas.stocktrackingsystem.repository.CategoryRepository;
import com.onuraktas.stocktrackingsystem.service.CategoryService;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Objects;
import java.util.UUID; | 2,219 | package com.onuraktas.stocktrackingsystem.impl;
@Service
public class CategoryServiceImpl implements CategoryService {
private final CategoryRepository categoryRepository;
private final CategoryProducer categoryProducer;
public CategoryServiceImpl(CategoryRepository categoryRepository, CategoryProducer categoryProducer){
this.categoryRepository = categoryRepository;
this.categoryProducer = categoryProducer;
}
@Override
public CreateCategoryResponse createCategory(CreateCategoryRequest categoryRequest) {
this.checkCategoryNameExists(categoryRequest.getCategoryName());
Category category = this.categoryRepository.save(CategoryMapper.toEntity(categoryRequest));
CreateCategoryResponse createCategoryResponse = CategoryMapper.toCreateCategoryResponse(category);
createCategoryResponse.setStatus(Status.OK.getStatus());
return createCategoryResponse;
}
private void checkCategoryNameExists(String categoryName) {
Category existCategory = categoryRepository.findByCategoryName(categoryName);
if (Objects.nonNull(existCategory)) | package com.onuraktas.stocktrackingsystem.impl;
@Service
public class CategoryServiceImpl implements CategoryService {
private final CategoryRepository categoryRepository;
private final CategoryProducer categoryProducer;
public CategoryServiceImpl(CategoryRepository categoryRepository, CategoryProducer categoryProducer){
this.categoryRepository = categoryRepository;
this.categoryProducer = categoryProducer;
}
@Override
public CreateCategoryResponse createCategory(CreateCategoryRequest categoryRequest) {
this.checkCategoryNameExists(categoryRequest.getCategoryName());
Category category = this.categoryRepository.save(CategoryMapper.toEntity(categoryRequest));
CreateCategoryResponse createCategoryResponse = CategoryMapper.toCreateCategoryResponse(category);
createCategoryResponse.setStatus(Status.OK.getStatus());
return createCategoryResponse;
}
private void checkCategoryNameExists(String categoryName) {
Category existCategory = categoryRepository.findByCategoryName(categoryName);
if (Objects.nonNull(existCategory)) | throw new CategoryAlreadyExistsException(CategoryMessages.CATEGORY_ALREADY_EXIST); | 13 | 2023-10-23 19:00:09+00:00 | 4k |
ushh789/FinancialCalculator | src/main/java/com/netrunners/financialcalculator/MenuControllers/ResultTableController.java | [
{
"identifier": "Converter",
"path": "src/main/java/com/netrunners/financialcalculator/LogicalInstrumnts/CurrencyConverter/Converter.java",
"snippet": "public class Converter {\n public static JsonArray getRates() throws IOException {\n URL url = new URL(\"https://bank.gov.ua/NBUStatService/v1/statdirectory/exchange?json\");\n HttpURLConnection connection = (HttpURLConnection) url.openConnection();\n\n connection.setRequestMethod(\"GET\");\n\n int responseCode = connection.getResponseCode();\n if (responseCode != 200) {\n LogHelper.log(Level.WARNING, \"Failed to get json from National Bank of Ukraine, response code: \" + responseCode, null);\n return null;\n }\n\n InputStream inputStream = connection.getInputStream();\n BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));\n StringBuilder json = new StringBuilder();\n String line;\n\n while ((line = reader.readLine()) != null) {\n json.append(line);\n }\n reader.close();\n inputStream.close();\n Gson gson = new Gson();\n\n return gson.fromJson(json.toString(), JsonArray.class).getAsJsonArray();\n }\n\n public static float getRateByCC(String cc) {\n try {\n JsonArray rates = getRates();\n if (rates == null) {\n LogHelper.log(Level.WARNING, \"Failed to retrieve exchange rates\", null);\n throw new RuntimeException(\"Failed to retrieve exchange rates\");\n }\n if (cc.equals(\"UAH\")){\n return 1;\n }\n for (JsonElement element : rates) {\n JsonObject obj = element.getAsJsonObject();\n if (obj.get(\"cc\").getAsString().equals(cc)) {\n return obj.get(\"rate\").getAsFloat();\n }\n }\n LogHelper.log(Level.WARNING, \"Currency code \" + cc + \" not found\", null);\n throw new IllegalArgumentException(\"Currency code \" + cc + \" not found\");\n } catch (IOException e) {\n LogHelper.log(Level.WARNING, \"IOException in Converter.getRateByCC, caused by input: \" + cc, null);\n throw new RuntimeException(e);\n }\n }\n\n public static String getCC(String userSelectedCurrency) {\n switch (userSelectedCurrency) {\n case \"$\" -> {\n return \"USD\";\n }\n case \"£\" -> {\n return \"GBP\";\n }\n case \"€\" -> {\n return \"EUR\";\n }\n case \"zł\" ->{\n return \"PLN\";\n }\n case \"₴\" ->{\n return \"UAH\";\n }\n default -> {\n return \"ERROR\";\n }\n }\n }\n}"
},
{
"identifier": "LogHelper",
"path": "src/main/java/com/netrunners/financialcalculator/LogicalInstrumnts/FileInstruments/LogHelper.java",
"snippet": "public class LogHelper {\n\n // Додаємо об'єкт логування\n private static final Logger logger = Logger.getLogger(LogHelper.class.getName());\n\n static {\n try {\n // Налаштовуємо об'єкт логування для запису в файл \"log.txt\"\n FileHandler fileHandler = new FileHandler(\"logs/log\"+ LocalDateTime.now().format(DateTimeFormatter.ofPattern(\"dd-MM-yyyy_HH-mm-ss\"))+\".log\");\n SimpleFormatter formatter = new SimpleFormatter();\n fileHandler.setFormatter(formatter);\n logger.addHandler(fileHandler);\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n // Метод для логування повідомлень\n public static void log(Level level, String message, Throwable throwable) {\n logger.log(level, message, throwable);\n }\n}"
},
{
"identifier": "DateTimeFunctions",
"path": "src/main/java/com/netrunners/financialcalculator/LogicalInstrumnts/TimeFunctions/DateTimeFunctions.java",
"snippet": "public class DateTimeFunctions {\n\n public static int countDaysBetweenDates(LocalDate startDate, LocalDate endDate) {\n return (int) ChronoUnit.DAYS.between(startDate, endDate);\n }\n\n public static int countDaysToNextPeriod(Credit credit, LocalDate date) {\n switch (credit.getPaymentType()) {\n case 1 -> {\n if (date.plusMonths(1).withDayOfMonth(1).isAfter(credit.getEndDate())) {\n return countDaysBetweenDates(date, credit.getEndDate());\n } else {\n return countDaysBetweenDates(date, date.plusMonths(1).withDayOfMonth(1));\n }\n }\n case 2 -> {\n if (date.plusMonths(3).withDayOfMonth(1).isAfter(credit.getEndDate())) {\n return countDaysBetweenDates(date, credit.getEndDate());\n } else {\n return countDaysBetweenDates(date, date.plusMonths(3).withDayOfMonth(1));\n }\n }\n case 3 -> {\n if (date.plusYears(1).withMonth(1).withDayOfMonth(1).isAfter(credit.getEndDate())) {\n return countDaysBetweenDates(date, credit.getEndDate());\n } else {\n return countDaysBetweenDates(date, date.plusYears(1).withMonth(1).withDayOfMonth(1));\n }\n }\n case 4 -> {\n return countDaysBetweenDates(date, credit.getEndDate());\n }\n }\n return 0;\n }\n\n public static int countDaysToNextPeriod(Deposit deposit, LocalDate tempDate, LocalDate endDate) {\n switch (deposit.getWithdrawalOption()) {\n case 1 -> {\n if (tempDate.plusMonths(1).withDayOfMonth(1).isAfter(endDate)) {\n return countDaysBetweenDates(tempDate, endDate);\n } else {\n return countDaysBetweenDates(tempDate, tempDate.plusMonths(1).withDayOfMonth(1));\n }\n }\n case 2 -> {\n if (tempDate.plusMonths(3).withDayOfMonth(1).isAfter(endDate)) {\n return countDaysBetweenDates(tempDate, endDate);\n } else {\n return countDaysBetweenDates(tempDate, tempDate.plusMonths(3).withDayOfMonth(1));\n }\n }\n case 3 -> {\n if (tempDate.plusYears(1).withMonth(1).withDayOfMonth(1).isAfter(endDate)) {\n return countDaysBetweenDates(tempDate, endDate);\n } else {\n return countDaysBetweenDates(tempDate, tempDate.plusYears(1).withMonth(1).withDayOfMonth(1));\n }\n }\n case 4 -> {\n return countDaysBetweenDates(tempDate, endDate);\n }\n }\n return 0;\n }\n\n public static boolean isDateBetweenDates(LocalDate dateToCheck, LocalDate start, LocalDate end) {\n return !dateToCheck.isBefore(start) && !dateToCheck.isAfter(end);\n }\n\n}"
},
{
"identifier": "WindowsOpener",
"path": "src/main/java/com/netrunners/financialcalculator/VisualInstruments/WindowsOpener.java",
"snippet": "public class WindowsOpener{\n public static void depositOpener(){\n try {\n FXMLLoader fxmlLoader = new FXMLLoader(StartMenu.class.getResource(\"DepositMenu.fxml\"));\n Stage stage = new Stage();\n stage.titleProperty().bind(LanguageManager.getInstance().getStringBinding(\"DepositButton\"));\n Scene scene = new Scene(fxmlLoader.load());\n scene.getStylesheets().add(StartMenu.currentTheme);\n stage.setScene(scene);\n StartMenu.openScenes.add(scene);\n stage.getIcons().add(new Image(\"file:src/main/resources/com/netrunners/financialcalculator/assets/Logo.png\"));\n stage.setMaxHeight(820);\n stage.setMaxWidth(620);\n stage.setMinHeight(820);\n stage.setMinWidth(620);\n stage.show();\n\n } catch (IOException e) {\n LogHelper.log(Level.SEVERE, \"Error opening DepositMenu.fxml: \", e);\n }\n }\n public static void creditOpener(){\n try {\n FXMLLoader fxmlLoader = new FXMLLoader(StartMenu.class.getResource(\"CreditMenu.fxml\"));\n Stage stage = new Stage();\n stage.titleProperty().bind(LanguageManager.getInstance().getStringBinding(\"CreditButton\"));\n Scene scene = new Scene(fxmlLoader.load());\n scene.getStylesheets().add(StartMenu.currentTheme);\n stage.setScene(scene);\n StartMenu.openScenes.add(scene);\n stage.getIcons().add(new Image(\"file:src/main/resources/com/netrunners/financialcalculator/assets/Logo.png\"));\n stage.setMaxHeight(820);\n stage.setMaxWidth(620);\n stage.setMinHeight(820);\n stage.setMinWidth(620);\n stage.show();\n\n } catch (Exception e) {\n LogHelper.log(Level.SEVERE, \"Error opening CreditMenu.fxml: \", e);\n }\n }\n}"
}
] | import com.netrunners.financialcalculator.LogicalInstrumnts.CurrencyConverter.Converter;
import com.netrunners.financialcalculator.LogicalInstrumnts.FileInstruments.LogHelper;
import com.netrunners.financialcalculator.LogicalInstrumnts.TimeFunctions.DateTimeFunctions;
import com.netrunners.financialcalculator.LogicalInstrumnts.TypesOfFinancialOpearation.Deposit.*;
import com.netrunners.financialcalculator.LogicalInstrumnts.TypesOfFinancialOpearation.Credit.*;
import com.netrunners.financialcalculator.VisualInstruments.MenuActions.*;
import com.netrunners.financialcalculator.VisualInstruments.WindowsOpener;
import javafx.beans.property.SimpleObjectProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
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.usermodel.XSSFWorkbook;
import java.io.*;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.logging.Level; | 2,722 | package com.netrunners.financialcalculator.MenuControllers;
public class ResultTableController {
@FXML
private MenuItem aboutUs;
@FXML
private MenuItem creditButtonMenu;
@FXML
private MenuItem currency;
@FXML
private MenuItem darkTheme;
@FXML
private Menu fileButton;
@FXML
private Menu aboutButton;
@FXML
private MenuItem depositButtonMenu;
@FXML
private MenuItem exitApp;
@FXML
private TableColumn<Object[], Integer> periodColumn;
@FXML
private MenuItem languageButton;
@FXML
private MenuItem lightTheme;
@FXML
private TableColumn<Object[], String> investmentloanColumn;
@FXML
private MenuItem openFileButton;
@FXML
private TableColumn<Object[], String> periodProfitLoanColumn;
@FXML
private TableView<Object[]> resultTable;
@FXML
private MenuItem saveAsButton;
@FXML
private MenuItem saveButton;
@FXML
private Menu viewButton;
@FXML
private Menu settingsButton;
@FXML
private Menu themeButton;
@FXML
private TableColumn<Object[], String> totalColumn;
@FXML
private TableColumn<Object[], String> periodPercentsColumn;
@FXML
private Button exportButton;
@FXML
private Menu newButton;
@FXML
private Label financialCalculatorLabel;
@FXML
private Button convertButton;
float loan;
float dailyPart;
private LanguageManager languageManager = LanguageManager.getInstance();
List<Integer> DaystoNextPeriodWithHolidays = new ArrayList<>();
List<Integer> DaystoNextPeriod = new ArrayList<>();
private String userSelectedCurrency;
float tempinvest;
@FXML
void initialize() {
openFileButton.setDisable(true);
currency.setDisable(true);
darkTheme.setOnAction(event -> ThemeSelector.setDarkTheme());
lightTheme.setOnAction(event -> ThemeSelector.setLightTheme());
aboutUs.setOnAction(event -> AboutUsAlert.showAboutUs());
exitApp.setOnAction(event -> ExitApp.exitApp()); | package com.netrunners.financialcalculator.MenuControllers;
public class ResultTableController {
@FXML
private MenuItem aboutUs;
@FXML
private MenuItem creditButtonMenu;
@FXML
private MenuItem currency;
@FXML
private MenuItem darkTheme;
@FXML
private Menu fileButton;
@FXML
private Menu aboutButton;
@FXML
private MenuItem depositButtonMenu;
@FXML
private MenuItem exitApp;
@FXML
private TableColumn<Object[], Integer> periodColumn;
@FXML
private MenuItem languageButton;
@FXML
private MenuItem lightTheme;
@FXML
private TableColumn<Object[], String> investmentloanColumn;
@FXML
private MenuItem openFileButton;
@FXML
private TableColumn<Object[], String> periodProfitLoanColumn;
@FXML
private TableView<Object[]> resultTable;
@FXML
private MenuItem saveAsButton;
@FXML
private MenuItem saveButton;
@FXML
private Menu viewButton;
@FXML
private Menu settingsButton;
@FXML
private Menu themeButton;
@FXML
private TableColumn<Object[], String> totalColumn;
@FXML
private TableColumn<Object[], String> periodPercentsColumn;
@FXML
private Button exportButton;
@FXML
private Menu newButton;
@FXML
private Label financialCalculatorLabel;
@FXML
private Button convertButton;
float loan;
float dailyPart;
private LanguageManager languageManager = LanguageManager.getInstance();
List<Integer> DaystoNextPeriodWithHolidays = new ArrayList<>();
List<Integer> DaystoNextPeriod = new ArrayList<>();
private String userSelectedCurrency;
float tempinvest;
@FXML
void initialize() {
openFileButton.setDisable(true);
currency.setDisable(true);
darkTheme.setOnAction(event -> ThemeSelector.setDarkTheme());
lightTheme.setOnAction(event -> ThemeSelector.setLightTheme());
aboutUs.setOnAction(event -> AboutUsAlert.showAboutUs());
exitApp.setOnAction(event -> ExitApp.exitApp()); | depositButtonMenu.setOnAction(event -> WindowsOpener.depositOpener()); | 3 | 2023-10-18 16:03:09+00:00 | 4k |
bowbahdoe/java-audio-stack | tritonus-share/src/main/java/dev/mccue/tritonus/share/sampled/convert/TMatrixFormatConversionProvider.java | [
{
"identifier": "ArraySet",
"path": "tritonus-share/src/main/java/dev/mccue/tritonus/share/ArraySet.java",
"snippet": "public class ArraySet<E>\r\nextends ArrayList<E>\r\nimplements Set<E>\r\n{\r\n\tprivate static final long serialVersionUID = 1;\r\n\r\n\tpublic ArraySet()\r\n\t{\r\n\t\tsuper();\r\n\t}\r\n\r\n\r\n\r\n\tpublic ArraySet(Collection<E> c)\r\n\t{\r\n\t\tthis();\r\n\t\taddAll(c);\r\n\t}\r\n\r\n\r\n\r\n\tpublic boolean add(E element)\r\n\t{\r\n\t\tif (!contains(element))\r\n\t\t{\r\n\t\t\tsuper.add(element);\r\n\t\t\treturn true;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\treturn false;\r\n\t\t}\r\n\t}\r\n\r\n\r\n\r\n\tpublic void add(int index, E element)\r\n\t{\r\n\t\tthrow new UnsupportedOperationException(\"ArraySet.add(int index, Object element) unsupported\");\r\n\t}\r\n\r\n\tpublic E set(int index, E element)\r\n\t{\r\n\t\tthrow new UnsupportedOperationException(\"ArraySet.set(int index, Object element) unsupported\");\r\n\t}\r\n\r\n}\r"
},
{
"identifier": "AudioFormats",
"path": "tritonus-share/src/main/java/dev/mccue/tritonus/share/sampled/AudioFormats.java",
"snippet": "public class AudioFormats\r\n{\r\n\tprivate static boolean doMatch(int i1, int i2)\r\n\t{\r\n\t\treturn i1 == AudioSystem.NOT_SPECIFIED\r\n\t\t\t|| i2 == AudioSystem.NOT_SPECIFIED\r\n\t\t\t|| i1 == i2;\r\n\t}\r\n\r\n\r\n\r\n\tprivate static boolean doMatch(float f1, float f2)\r\n\t{\r\n\t\treturn f1 == AudioSystem.NOT_SPECIFIED\r\n\t\t\t|| f2 == AudioSystem.NOT_SPECIFIED\r\n\t\t\t|| Math.abs(f1 - f2) < 1.0e-9;\r\n\t}\r\n\r\n\r\n\r\n\t/**\r\n\t * Tests whether 2 AudioFormats have matching formats.\r\n\t * A field matches when it is AudioSystem.NOT_SPECIFIED in\r\n\t * at least one of the formats or the field is the same\r\n\t * in both formats.<br>\r\n\t * Exceptions:\r\n\t * <ul>\r\n\t * <li>Encoding must always be equal for a match.\r\n\t * <li> For a match, endianness must be equal if SampleSizeInBits is not\r\n\t * AudioSystem.NOT_SPECIFIED and greater than 8bit in both formats.<br>\r\n\t * In other words: If SampleSizeInBits is AudioSystem.NOT_SPECIFIED\r\n\t * in either format or both formats have a SampleSizeInBits<8,\r\n\t * endianness does not matter.\r\n\t * </ul>\r\n\t * This is a proposition to be used as AudioFormat.matches.\r\n\t * It can therefore be considered as a temporary workaround.\r\n\t */\r\n\t// IDEA: create a special \"NOT_SPECIFIED\" encoding\r\n\t// and a AudioFormat.Encoding.matches method.\r\n\tpublic static boolean matches(AudioFormat format1,\r\n\t\t\t\t AudioFormat format2)\r\n\t{\r\n\t\t//$$fb 19 Dec 99: endian must be checked, too.\r\n\t\t//\r\n\t\t// we do have a problem with redundant elements:\r\n\t\t// e.g.\r\n\t\t// encoding=ALAW || ULAW -> bigEndian and samplesizeinbits don't matter\r\n\t\t// sample size in bits == 8 -> bigEndian doesn't matter\r\n\t\t// sample size in bits > 8 -> PCM is always signed.\r\n\t\t// This is an overall issue in JavaSound, I think.\r\n\t\t// At present, it is not consistently implemented to support these\r\n\t\t// redundancies and implicit definitions\r\n\t\t//\r\n\t\t// As a workaround of this issue I return in the converters\r\n\t\t// all combinations, e.g. for ULAW I return bigEndian and !bigEndian formats.\r\n/* old version\r\n*/\r\n\t\t// as proposed by florian\r\n\t\treturn format1.getEncoding().equals(format2.getEncoding())\r\n\t\t\t&& (format2.getSampleSizeInBits()<=8\r\n\t\t\t || format1.getSampleSizeInBits()==AudioSystem.NOT_SPECIFIED\r\n\t\t\t || format2.getSampleSizeInBits()==AudioSystem.NOT_SPECIFIED\r\n\t\t\t || format1.isBigEndian()==format2.isBigEndian())\r\n\t\t\t&& doMatch(format1.getChannels(),format2.getChannels())\r\n\t\t\t&& doMatch(format1.getSampleSizeInBits(), format2.getSampleSizeInBits())\r\n\t\t\t&& doMatch(format1.getFrameSize(), format2.getFrameSize())\r\n\t\t\t&& doMatch(format1.getSampleRate(), format2.getSampleRate())\r\n\t\t\t&& doMatch(format1.getFrameRate(),format2.getFrameRate());\r\n\t}\r\n\r\n\t/**\r\n\t * Tests for exact equality of 2 AudioFormats.\r\n\t * This is the behaviour of AudioFormat.matches in JavaSound 1.0.\r\n\t * <p>\r\n\t * This is a proposition to be used as AudioFormat.equals.\r\n\t * It can therefore be considered as a temporary workaround.\r\n\t */\r\n\tpublic static boolean equals(AudioFormat format1,\r\n\t\t\t\t AudioFormat format2)\r\n\t{\r\n\t\treturn format1.getEncoding().equals(format2.getEncoding())\r\n\t\t\t&& format1.getChannels() == format2.getChannels()\r\n\t\t\t&& format1.getSampleSizeInBits() == format2.getSampleSizeInBits()\r\n\t\t\t&& format1.getFrameSize() == format2.getFrameSize()\r\n\t\t\t&& (Math.abs(format1.getSampleRate() - format2.getSampleRate()) < 1.0e-9)\r\n\t\t\t&& (Math.abs(format1.getFrameRate() - format2.getFrameRate()) < 1.0e-9);\r\n\t}\r\n\r\n}\r"
}
] | import java.util.Iterator;
import javax.sound.sampled.AudioFormat;
import dev.mccue.tritonus.share.ArraySet;
import dev.mccue.tritonus.share.sampled.AudioFormats;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
| 1,950 | /*
* TMatrixFormatConversionProvider.java
*/
/*
* Copyright (c) 1999, 2000 by Matthias Pfisterer <[email protected]>
*
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Library General Public License as published
* by the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
*/
package dev.mccue.tritonus.share.sampled.convert;
/**
* Base class for arbitrary formatConversionProviders.
*
* @author Matthias Pfisterer
*/
@SuppressWarnings("unchecked")
public abstract class TMatrixFormatConversionProvider
extends TSimpleFormatConversionProvider
{
/*
* keys: source AudioFormat
* values: collection of possible target encodings
*
* Note that accessing values with get() is not appropriate,
* since the equals() method in AudioFormat is not overloaded.
* The hashtable is just used as a convenient storage
* organization.
*/
private Map m_targetEncodingsFromSourceFormat;
/*
* keys: source AudioFormat
* values: a Map that contains a mapping from target encodings
* (keys) to a collection of target formats (values).
*
* Note that accessing values with get() is not appropriate,
* since the equals() method in AudioFormat is not overloaded.
* The hashtable is just used as a convenient storage
* organization.
*/
private Map m_targetFormatsFromSourceFormat;
protected TMatrixFormatConversionProvider(
List sourceFormats,
List targetFormats,
boolean[][] abConversionPossible)
{
super(sourceFormats,
targetFormats);
m_targetEncodingsFromSourceFormat = new HashMap();
m_targetFormatsFromSourceFormat = new HashMap();
for (int nSourceFormat = 0;
nSourceFormat < sourceFormats.size();
nSourceFormat++)
{
AudioFormat sourceFormat = (AudioFormat) sourceFormats.get(nSourceFormat);
| /*
* TMatrixFormatConversionProvider.java
*/
/*
* Copyright (c) 1999, 2000 by Matthias Pfisterer <[email protected]>
*
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Library General Public License as published
* by the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
*/
package dev.mccue.tritonus.share.sampled.convert;
/**
* Base class for arbitrary formatConversionProviders.
*
* @author Matthias Pfisterer
*/
@SuppressWarnings("unchecked")
public abstract class TMatrixFormatConversionProvider
extends TSimpleFormatConversionProvider
{
/*
* keys: source AudioFormat
* values: collection of possible target encodings
*
* Note that accessing values with get() is not appropriate,
* since the equals() method in AudioFormat is not overloaded.
* The hashtable is just used as a convenient storage
* organization.
*/
private Map m_targetEncodingsFromSourceFormat;
/*
* keys: source AudioFormat
* values: a Map that contains a mapping from target encodings
* (keys) to a collection of target formats (values).
*
* Note that accessing values with get() is not appropriate,
* since the equals() method in AudioFormat is not overloaded.
* The hashtable is just used as a convenient storage
* organization.
*/
private Map m_targetFormatsFromSourceFormat;
protected TMatrixFormatConversionProvider(
List sourceFormats,
List targetFormats,
boolean[][] abConversionPossible)
{
super(sourceFormats,
targetFormats);
m_targetEncodingsFromSourceFormat = new HashMap();
m_targetFormatsFromSourceFormat = new HashMap();
for (int nSourceFormat = 0;
nSourceFormat < sourceFormats.size();
nSourceFormat++)
{
AudioFormat sourceFormat = (AudioFormat) sourceFormats.get(nSourceFormat);
| List supportedTargetEncodings = new ArraySet();
| 0 | 2023-10-19 14:09:37+00:00 | 4k |
dvillavicencio/Riven-of-a-Thousand-Servers | src/test/java/com/danielvm/destiny2bot/service/WeeklyActivitiesServiceTest.java | [
{
"identifier": "BungieClient",
"path": "src/main/java/com/danielvm/destiny2bot/client/BungieClient.java",
"snippet": "public interface BungieClient {\n\n /**\n * Gets the membership info for the current user\n *\n * @param bearerToken The user's bearer token\n * @return {@link MembershipResponse}\n */\n @GetExchange(\"/User/GetMembershipsForCurrentUser/\")\n ResponseEntity<MembershipResponse> getMembershipForCurrentUser(\n @RequestHeader(name = HttpHeaders.AUTHORIZATION) String bearerToken);\n\n /**\n * Gets the membership info for the current user in a reactive way\n *\n * @param bearerToken The user's bearer token\n * @return {@link MembershipResponse}\n */\n @GetExchange(\"/User/GetMembershipsForCurrentUser/\")\n Mono<MembershipResponse> getMembershipInfoForCurrentUser(\n @RequestHeader(name = HttpHeaders.AUTHORIZATION) String bearerToken);\n\n /**\n * Ges a manifest entity from the Manifest API\n *\n * @param entityType The entity type (see {@link ManifestEntity})\n * @param hashIdentifier The entity hash identifier\n * @return {@link GenericResponse} of {@link ResponseFields}\n */\n @GetExchange(\"/Destiny2/Manifest/{entityType}/{hashIdentifier}/\")\n ResponseEntity<GenericResponse<ResponseFields>> getManifestEntity(\n @PathVariable(value = \"entityType\") String entityType,\n @PathVariable(value = \"hashIdentifier\") String hashIdentifier);\n\n /**\n * Ges a manifest entity from the Manifest API asynchronously\n *\n * @param entityType The entity type (see {@link ManifestEntity})\n * @param hashIdentifier The entity hash identifier\n * @return {@link Mono} of {@link ResponseFields}\n */\n @GetExchange(\"/Destiny2/Manifest/{entityType}/{hashIdentifier}/\")\n Mono<GenericResponse<ResponseFields>> getManifestEntityRx(\n @PathVariable(value = \"entityType\") String entityType,\n @PathVariable(value = \"hashIdentifier\") String hashIdentifier);\n\n /**\n * Get public Milestones\n *\n * @return {@link Mono} of Map of {@link MilestoneEntry}\n */\n @GetExchange(\"/Destiny2/Milestones/\")\n Mono<GenericResponse<Map<String, MilestoneEntry>>> getPublicMilestonesRx();\n\n /**\n * Get a user characters\n *\n * @param membershipType the membership type of the user\n * @param destinyMembershipId the destiny membership id of the user\n * @return {@link Mono} containing {@link CharactersResponse}\n */\n @GetExchange(\"/Destiny2/{membershipType}/Profile/{destinyMembershipId}/?components=200\")\n Mono<GenericResponse<CharactersResponse>> getUserCharacters(\n @PathVariable Integer membershipType,\n @PathVariable String destinyMembershipId\n );\n\n}"
},
{
"identifier": "BungieClientWrapper",
"path": "src/main/java/com/danielvm/destiny2bot/client/BungieClientWrapper.java",
"snippet": "@Service\n@RequiredArgsConstructor\n@Slf4j\npublic class BungieClientWrapper {\n\n private final BungieClient bungieClient;\n\n /**\n * Wraps the client call to the Manifest with a Cacheable method\n *\n * @param entityType The entity type (see\n * {@link ManifestEntity})\n * @param hashIdentifier The hash identifier\n * @return {@link GenericResponse} of {@link ResponseFields}\n */\n @Cacheable(cacheNames = \"entity\", cacheManager = \"inMemoryCacheManager\")\n public Mono<GenericResponse<ResponseFields>> getManifestEntityRx(\n ManifestEntity entityType, String hashIdentifier) {\n return bungieClient.getManifestEntityRx(entityType.getId(), hashIdentifier).cache();\n }\n\n}"
},
{
"identifier": "WeeklyActivity",
"path": "src/main/java/com/danielvm/destiny2bot/dto/WeeklyActivity.java",
"snippet": "@Data\n@AllArgsConstructor\n@NoArgsConstructor\n@Builder\npublic class WeeklyActivity {\n\n /**\n * Name of the milestone\n */\n private String name;\n\n /**\n * Description of the milestone\n */\n private String description;\n\n /**\n * The start date for this milestone\n */\n private ZonedDateTime startDate;\n\n /**\n * The end date for this milestone\n */\n private ZonedDateTime endDate;\n\n}"
},
{
"identifier": "GenericResponse",
"path": "src/main/java/com/danielvm/destiny2bot/dto/destiny/GenericResponse.java",
"snippet": "@Data\n@AllArgsConstructor\n@NoArgsConstructor\npublic class GenericResponse<T> {\n\n /**\n * Most of the responses from Bungie.net have a Json element named 'Response' with arbitrary info\n * depending on the endpoint. This field is just a generic-wrapper for it.\n */\n @JsonAlias(\"Response\")\n @Nullable\n private T response;\n}"
},
{
"identifier": "DisplayProperties",
"path": "src/main/java/com/danielvm/destiny2bot/dto/destiny/manifest/DisplayProperties.java",
"snippet": "@Data\n@AllArgsConstructor\n@NoArgsConstructor\npublic class DisplayProperties {\n\n private String description;\n private String name;\n private String icon;\n private String highResIcon;\n private Boolean hasIcon;\n}"
},
{
"identifier": "ResponseFields",
"path": "src/main/java/com/danielvm/destiny2bot/dto/destiny/manifest/ResponseFields.java",
"snippet": "@Data\n@AllArgsConstructor\n@NoArgsConstructor\npublic class ResponseFields {\n\n private DisplayProperties displayProperties;\n\n private Stats stats;\n\n private EquipmentBlock equipmentBlock;\n\n private String defaultDamageType;\n\n private Integer itemType;\n\n private Integer itemSubType;\n\n private Integer directActivityModeType;\n\n private String activityTypeHash;\n\n private Long hash;\n}"
},
{
"identifier": "ActivitiesDto",
"path": "src/main/java/com/danielvm/destiny2bot/dto/destiny/milestone/ActivitiesDto.java",
"snippet": "@Data\n@AllArgsConstructor\n@NoArgsConstructor\npublic class ActivitiesDto {\n\n private String activityHash;\n private List<String> challengeObjectiveHashes;\n\n}"
},
{
"identifier": "MilestoneEntry",
"path": "src/main/java/com/danielvm/destiny2bot/dto/destiny/milestone/MilestoneEntry.java",
"snippet": "@Data\n@AllArgsConstructor\n@NoArgsConstructor\npublic class MilestoneEntry {\n\n private String milestoneHash;\n private ZonedDateTime startDate;\n private ZonedDateTime endDate;\n private List<ActivitiesDto> activities;\n}"
},
{
"identifier": "ActivityMode",
"path": "src/main/java/com/danielvm/destiny2bot/enums/ActivityMode.java",
"snippet": "public enum ActivityMode {\n\n STORY(\"story\"),\n STRIKE(\"strike\"),\n DUNGEON(\"dungeon\"),\n RAID(\"raid\");\n\n @Getter\n private final String label;\n\n ActivityMode(String label) {\n this.label = label;\n }\n}"
},
{
"identifier": "ManifestEntity",
"path": "src/main/java/com/danielvm/destiny2bot/enums/ManifestEntity.java",
"snippet": "public enum ManifestEntity {\n\n BUCKET_DEFINITION(\"DestinyInventoryItemDefinition\"),\n STAT_DEFINITION(\"DestinyStatDefinition\"),\n CLASS_DEFINITION(\"DestinyClassDefinition\"),\n ITEM_INVENTORY_DEFINITION(\"DestinyInventoryItemDefinition\"),\n MILESTONE_DEFINITION(\"DestinyMilestoneDefinition\"),\n ACTIVITY_TYPE_DEFINITION(\"DestinyActivityTypeDefinition\"),\n ACTIVITY_DEFINITION(\"DestinyActivityDefinition\");\n\n @Getter\n private final String id;\n\n ManifestEntity(String id) {\n this.id = id;\n }\n}"
},
{
"identifier": "ResourceNotFoundException",
"path": "src/main/java/com/danielvm/destiny2bot/exception/ResourceNotFoundException.java",
"snippet": "public class ResourceNotFoundException extends BaseException {\n\n @Serial\n private static final long serialVersionUID = -4367872183871777447L;\n\n public ResourceNotFoundException(String message) {\n super(message, HttpStatus.NOT_FOUND);\n }\n}"
}
] | import static org.mockito.Mockito.when;
import com.danielvm.destiny2bot.client.BungieClient;
import com.danielvm.destiny2bot.client.BungieClientWrapper;
import com.danielvm.destiny2bot.dto.WeeklyActivity;
import com.danielvm.destiny2bot.dto.destiny.GenericResponse;
import com.danielvm.destiny2bot.dto.destiny.manifest.DisplayProperties;
import com.danielvm.destiny2bot.dto.destiny.manifest.ResponseFields;
import com.danielvm.destiny2bot.dto.destiny.milestone.ActivitiesDto;
import com.danielvm.destiny2bot.dto.destiny.milestone.MilestoneEntry;
import com.danielvm.destiny2bot.enums.ActivityMode;
import com.danielvm.destiny2bot.enums.ManifestEntity;
import com.danielvm.destiny2bot.exception.ResourceNotFoundException;
import java.time.ZonedDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Map;
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 reactor.core.publisher.Mono;
import reactor.test.StepVerifier; | 2,389 | package com.danielvm.destiny2bot.service;
@ExtendWith(MockitoExtension.class)
public class WeeklyActivitiesServiceTest {
@Mock
private BungieClient bungieClient;
@Mock
private BungieClientWrapper bungieClientWrapper;
@InjectMocks
private WeeklyActivitiesService sut;
@Test
@DisplayName("Retrieve weekly raid works successfully")
public void retrieveWeeklyRaidWorksSuccessfully() {
// given: an activity mode
ActivityMode activity = ActivityMode.RAID;
var startTime = ZonedDateTime.now();
var endTime = ZonedDateTime.now().plusDays(2L);
var activitiesNoWeekly = List.of(new ActivitiesDto("1262462921", Collections.emptyList()));
var activitiesWeekly = List.of(new ActivitiesDto("2823159265", List.of("897950155")));
var milestoneResponse = new GenericResponse<>(
Map.of(
"526718853", new MilestoneEntry("526718853",
startTime, endTime, activitiesNoWeekly),
"3618845105", new MilestoneEntry("3618845105",
startTime, endTime, activitiesWeekly),
"2029743966", new MilestoneEntry("2029743966",
startTime, endTime, null)
)
);
when(bungieClient.getPublicMilestonesRx())
.thenReturn(Mono.just(milestoneResponse));
| package com.danielvm.destiny2bot.service;
@ExtendWith(MockitoExtension.class)
public class WeeklyActivitiesServiceTest {
@Mock
private BungieClient bungieClient;
@Mock
private BungieClientWrapper bungieClientWrapper;
@InjectMocks
private WeeklyActivitiesService sut;
@Test
@DisplayName("Retrieve weekly raid works successfully")
public void retrieveWeeklyRaidWorksSuccessfully() {
// given: an activity mode
ActivityMode activity = ActivityMode.RAID;
var startTime = ZonedDateTime.now();
var endTime = ZonedDateTime.now().plusDays(2L);
var activitiesNoWeekly = List.of(new ActivitiesDto("1262462921", Collections.emptyList()));
var activitiesWeekly = List.of(new ActivitiesDto("2823159265", List.of("897950155")));
var milestoneResponse = new GenericResponse<>(
Map.of(
"526718853", new MilestoneEntry("526718853",
startTime, endTime, activitiesNoWeekly),
"3618845105", new MilestoneEntry("3618845105",
startTime, endTime, activitiesWeekly),
"2029743966", new MilestoneEntry("2029743966",
startTime, endTime, null)
)
);
when(bungieClient.getPublicMilestonesRx())
.thenReturn(Mono.just(milestoneResponse));
| var activityWithType = new ResponseFields(); | 5 | 2023-10-20 05:53:03+00:00 | 4k |
MinecraftForge/ModLauncher | src/main/java/cpw/mods/modlauncher/TransformingClassLoader.java | [
{
"identifier": "IEnvironment",
"path": "src/main/java/cpw/mods/modlauncher/api/IEnvironment.java",
"snippet": "public interface IEnvironment {\n /**\n * Get a property from the Environment\n * @param key to find\n * @param <T> Type of key\n * @return the value\n */\n <T> Optional<T> getProperty(TypesafeMap.Key<T> key);\n\n /**\n * Compute a new value for insertion into the environment, if not already present.\n *\n * @param key to insert\n * @param valueFunction the supplier of a value\n * @param <T> Type of key\n * @return The value of the key\n */\n <T> T computePropertyIfAbsent(TypesafeMap.Key<T> key, final Function<? super TypesafeMap.Key<T>, ? extends T> valueFunction);\n /**\n * Find the named {@link ILaunchPluginService}\n *\n * @param name name to lookup\n * @return the launch plugin\n */\n Optional<ILaunchPluginService> findLaunchPlugin(String name);\n\n /**\n * Find the named {@link ILaunchHandlerService}\n *\n * @param name name to lookup\n * @return the launch handler\n */\n Optional<ILaunchHandlerService> findLaunchHandler(String name);\n\n Optional<IModuleLayerManager> findModuleLayerManager();\n\n /**\n * Find the naming translation for the targetMapping.\n * @param targetMapping the name of the mapping to lookup\n * @return a function mapping names from the current naming domain to the requested one, if available\n */\n Optional<BiFunction<INameMappingService.Domain, String, String>> findNameMapping(String targetMapping);\n\n final class Keys {\n /**\n * Version passed in through arguments\n */\n public static final Supplier<TypesafeMap.Key<String>> VERSION = buildKey(\"version\", String.class);\n /**\n * The identified game directory (usually passed as an argument)\n */\n public static final Supplier<TypesafeMap.Key<Path>> GAMEDIR = buildKey(\"gamedir\", Path.class);\n /**\n * The identified assets directory (usually passed as an argument)\n */\n public static final Supplier<TypesafeMap.Key<Path>> ASSETSDIR = buildKey(\"assetsdir\", Path.class);\n /**\n * The UUID of the player on the client\n */\n public static final Supplier<TypesafeMap.Key<String>> UUID = buildKey(\"uuid\", String.class);\n /**\n * The name of the identified launch target (passed as an argument)\n */\n public static final Supplier<TypesafeMap.Key<String>> LAUNCHTARGET = buildKey(\"launchtarget\", String.class);\n /**\n * The naming scheme in use. Populated at startup. See: {@link INameMappingService}\n */\n public static final Supplier<TypesafeMap.Key<String>> NAMING = buildKey(\"naming\", String.class);\n /**\n * The audit trail for transformers applied to a class. See {@link ITransformerAuditTrail}\n */\n public static final Supplier<TypesafeMap.Key<ITransformerAuditTrail>> AUDITTRAIL = buildKey(\"audittrail\", ITransformerAuditTrail.class);\n /**\n * A simple List of Maps for Mod data. Map keys should include a \"name\" and \"description\". \"file\" and \"type\" are\n * populated automatically, as is \"name\".\n */\n public static final Supplier<TypesafeMap.Key<List<Map<String,String>>>> MODLIST = buildKey(\"modlist\", List.class);\n /**\n * The specification version for ModLauncher.\n */\n public static final Supplier<TypesafeMap.Key<String>> MLSPEC_VERSION = buildKey(\"mlspecVersion\", String.class);\n /**\n * The implementation version for ModLauncher.\n */\n public static final Supplier<TypesafeMap.Key<String>> MLIMPL_VERSION = buildKey(\"mlimplVersion\", String.class);\n /**\n * True if we can compute secured JAR state. JVMs < 8.0.61 do not have this feature because reasons\n */\n public static final Supplier<TypesafeMap.Key<Boolean>> SECURED_JARS_ENABLED = buildKey(\"securedJarsEnabled\", Boolean.class);\n }\n\n\n static <T> Supplier<TypesafeMap.Key<T>> buildKey(String name, Class<? super T> clazz) {\n return new TypesafeMap.KeyBuilder<>(name, clazz, IEnvironment.class);\n }\n}"
},
{
"identifier": "ITransformerActivity",
"path": "src/main/java/cpw/mods/modlauncher/api/ITransformerActivity.java",
"snippet": "public interface ITransformerActivity {\n /**\n * reason will be set to this value when TransformerClassWriter is trying to compute frames by loading the class\n * hierarchy for a class. No real classloading will be done when this reason is submitted.\n */\n String COMPUTING_FRAMES_REASON = \"computing_frames\";\n\n /**\n * reason will be set to this value when we're attempting to actually classload the class\n */\n String CLASSLOADING_REASON = \"classloading\";\n\n String[] getContext();\n\n Type getType();\n\n String getActivityString();\n\n enum Type {\n PLUGIN(\"pl\"), TRANSFORMER(\"xf\"), REASON(\"re\");\n\n private final String label;\n\n Type(final String label) {\n this.label = label;\n }\n\n public String getLabel() {\n return label;\n }\n }\n}"
},
{
"identifier": "Layer",
"path": "src/main/java/cpw/mods/modlauncher/api/IModuleLayerManager.java",
"snippet": "enum Layer {\n BOOT(),\n SERVICE(BOOT),\n PLUGIN(BOOT),\n GAME(PLUGIN, SERVICE);\n\n private final List<Layer> parents;\n\n Layer(Layer... parent) {\n this.parents = List.of(parent);\n }\n\n /** Returning a raw array is unsafe, it used to return the backing array directly which would allow others to screw with it. */\n @Deprecated(forRemoval = true, since = \"10.1\")\n public Layer[] getParent() {\n return this.parents.toArray(Layer[]::new);\n }\n\n /** Returns a potentially empty, immutable list of parent layers. */\n public List<Layer> getParents() {\n return this.parents;\n }\n}"
}
] | import cpw.mods.cl.ModuleClassLoader;
import cpw.mods.modlauncher.api.IEnvironment;
import cpw.mods.modlauncher.api.ITransformerActivity;
import cpw.mods.modlauncher.api.IModuleLayerManager.Layer;
import java.lang.module.Configuration;
import java.util.*; | 1,785 | /*
* Copyright (c) Forge Development LLC
* SPDX-License-Identifier: LGPL-3.0-only
*/
package cpw.mods.modlauncher;
/**
* Module transforming class loader
*/
public class TransformingClassLoader extends ModuleClassLoader {
static {
ClassLoader.registerAsParallelCapable();
}
private final ClassTransformer classTransformer;
private static ModuleLayer get(ModuleLayerHandler layers, Layer layer) {
return layers.getLayer(layer).orElseThrow(() -> new NullPointerException("Failed to find " + layer.name() + " layer"));
}
public TransformingClassLoader(TransformStore transformStore, LaunchPluginHandler pluginHandler, ModuleLayerHandler layers) {
super("TRANSFORMER", get(layers, Layer.GAME).configuration(), List.of(get(layers, Layer.SERVICE)));
this.classTransformer = new ClassTransformer(transformStore, pluginHandler, this);
}
TransformingClassLoader(String name, ClassLoader parent, Configuration config, List<ModuleLayer> parentLayers, List<ClassLoader> parentLoaders,
TransformStore transformStore, LaunchPluginHandler pluginHandler, Environment environment) {
super(name, parent, config, parentLayers, parentLoaders, true);
TransformerAuditTrail tat = new TransformerAuditTrail(); | /*
* Copyright (c) Forge Development LLC
* SPDX-License-Identifier: LGPL-3.0-only
*/
package cpw.mods.modlauncher;
/**
* Module transforming class loader
*/
public class TransformingClassLoader extends ModuleClassLoader {
static {
ClassLoader.registerAsParallelCapable();
}
private final ClassTransformer classTransformer;
private static ModuleLayer get(ModuleLayerHandler layers, Layer layer) {
return layers.getLayer(layer).orElseThrow(() -> new NullPointerException("Failed to find " + layer.name() + " layer"));
}
public TransformingClassLoader(TransformStore transformStore, LaunchPluginHandler pluginHandler, ModuleLayerHandler layers) {
super("TRANSFORMER", get(layers, Layer.GAME).configuration(), List.of(get(layers, Layer.SERVICE)));
this.classTransformer = new ClassTransformer(transformStore, pluginHandler, this);
}
TransformingClassLoader(String name, ClassLoader parent, Configuration config, List<ModuleLayer> parentLayers, List<ClassLoader> parentLoaders,
TransformStore transformStore, LaunchPluginHandler pluginHandler, Environment environment) {
super(name, parent, config, parentLayers, parentLoaders, true);
TransformerAuditTrail tat = new TransformerAuditTrail(); | environment.computePropertyIfAbsent(IEnvironment.Keys.AUDITTRAIL.get(), v->tat); | 0 | 2023-10-18 17:56:01+00:00 | 4k |
Kyrotechnic/KyroClient | Client/src/main/java/me/kyroclient/commands/impl/FriendCommand.java | [
{
"identifier": "KyroClient",
"path": "Client/src/main/java/me/kyroclient/KyroClient.java",
"snippet": "public class KyroClient {\n //Vars\n public static final String MOD_ID = \"dankers\";\n public static String VERSION = \"0.2-b3\";\n public static List<String> changelog;\n public static ModuleManager moduleManager;\n public static NotificationManager notificationManager;\n public static ConfigManager configManager;\n public static ThemeManager themeManager;\n public static FriendManager friendManager;\n public static CapeManager capeManager;\n public static Minecraft mc;\n public static boolean isDev = true;\n public static Color iconColor = new Color(237, 107, 0);\n public static long gameStarted;\n public static boolean banned = false;\n\n //Module Dependencies\n public static Gui clickGui;\n public static NickHider nickHider;\n public static CropNuker cropNuker;\n public static Velocity velocity;\n public static FastPlace fastPlace;\n public static Modless modless;\n public static Speed speed;\n public static AntiBot antiBot;\n public static Interfaces interfaces;\n public static Delays delays;\n public static Hitboxes hitBoxes;\n public static NoSlow noSlow;\n public static FreeCam freeCam;\n public static Giants giants;\n public static Animations animations;\n public static Aura aura;\n public static AutoBlock autoBlock;\n public static PopupAnimation popupAnimation;\n public static GuiMove guiMove;\n public static Camera camera;\n public static Reach reach;\n public static InventoryDisplay inventoryDisplay;\n public static LoreDisplay loreDisplay;\n public static FarmingMacro macro;\n public static MiningQOL miningQol;\n public static Tickless tickless;\n public static TeleportExploit teleportExploit;\n public static Hud hud;\n public static FakeLag fakeLag;\n public static Proxy proxy;\n public static CustomBrand customBrand;\n public static NoFallingBlocks noFallingBlocks;\n public static PlayerVisibility playerVisibility;\n public static NoDebuff noDebuff;\n public static Capes capes;\n\n\n //Methods\n\n /*\n Time to finally make it spoof being any random mod on boot!\n */\n public static List<ForgeRegister> registerEvents()\n {\n /*for (Module module : moduleManager.getModules())\n {\n MinecraftForge.EVENT_BUS.register(module);\n }*/\n\n ForgeSpoofer.update();\n List<ForgeRegister> registers = new ArrayList<>();\n\n for (Module module : moduleManager.getModules())\n {\n List<ForgeRegister> register = ForgeSpoofer.register(module, true);\n if (register.isEmpty()) continue;\n registers.addAll(register);\n }\n\n registers.add(ForgeSpoofer.register(notificationManager = new NotificationManager(), true).get(0));\n registers.add(ForgeSpoofer.register(new BlurUtils(), true).get(0));\n registers.add(ForgeSpoofer.register(new KyroClient(), true).get(0));\n\n Fonts.bootstrap();\n\n capeManager = new CapeManager();\n try {\n capeManager.init();\n } catch (Exception e) {\n e.printStackTrace();\n }\n\n return registers;\n }\n public static void init()\n {\n mc = Minecraft.getMinecraft();\n\n moduleManager = new ModuleManager(\"me.kyroclient.modules\");\n moduleManager.initReflection();\n\n configManager = new ConfigManager();\n themeManager = new ThemeManager();\n friendManager = new FriendManager();\n\n friendManager.init();\n\n CommandManager.init();\n\n KyroClient.proxy.setToggled(false);\n\n gameStarted = System.currentTimeMillis();\n\n //fixCertificate();\n\n Runtime.getRuntime().addShutdownHook(new Thread(() -> {\n friendManager.save();\n try {\n Class clazz = Class.forName(\"me.kyroclient.AgentLoader\");\n Method method = clazz.getMethod(\"downloadUpdate\");\n method.setAccessible(true);\n method.invoke(null);\n } catch (Exception e) {\n e.printStackTrace();\n }\n }));\n\n new Thread(KyroClient::threadTask).start();\n }\n\n @SneakyThrows\n public static void fixCertificate()\n {\n SSLContext sc = SSLContext.getInstance(\"SSL\");\n sc.init(null, new TrustManager[]{new TrustAnyTrustManager()}, new SecureRandom());\n HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());\n HostnameVerifier allHostsValid = new HostnameVerifier() {\n public boolean verify(String hostname, SSLSession session) {\n return true;\n }\n };\n HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);\n }\n\n @SubscribeEvent\n public void sendPacket(PacketSentEvent event)\n {\n if (event.packet instanceof C01PacketChatMessage)\n {\n C01PacketChatMessage message = (C01PacketChatMessage) event.packet;\n\n String str = message.getMessage();\n\n if (CommandManager.handle(str))\n {\n event.setCanceled(true);\n }\n }\n }\n\n public static void sendMessage(String message)\n {\n KyroClient.mc.thePlayer.addChatMessage(new ChatComponentText(message));\n }\n\n @SneakyThrows\n public static void threadTask()\n {\n URL url2 = new URL(\"https://raw.githubusercontent.com/Kyrotechnic/KyroClient/main/update/Changelog.txt\");\n\n List<String> changelog = new ArrayList<String>();\n\n BufferedReader reader = new BufferedReader(new InputStreamReader(url2.openStream()));\n String b = null;\n while ((b = reader.readLine()) != null)\n {\n changelog.add(b);\n }\n\n KyroClient.VERSION = changelog.get(0);\n\n KyroClient.changelog = changelog.stream().filter(c -> !(c.equals(KyroClient.VERSION))).collect(Collectors.toList());\n }\n\n public static void handleKey(int key)\n {\n for (Module module : moduleManager.getModules())\n {\n if (module.getKeycode() == key)\n {\n module.toggle();\n if (!clickGui.disableNotifs.isEnabled())\n notificationManager.showNotification(module.getName() + \" has been \" + (module.isToggled() ? \"Enabled\" : \"Disabled\"), 2000, Notification.NotificationType.INFO);\n }\n }\n }\n\n public static int ticks = 0;\n\n @SubscribeEvent\n public void joinWorld(TickEvent.ClientTickEvent event)\n {\n ticks++;\n SkyblockUtils.tick(event);\n }\n}"
},
{
"identifier": "Command",
"path": "Client/src/main/java/me/kyroclient/commands/Command.java",
"snippet": "public abstract class Command {\n public String[] names;\n public Command(String... name)\n {\n names = name;\n }\n public String[] getNames()\n {\n return names;\n }\n\n public abstract void execute(String[] args) throws Exception;\n\n public String getName()\n {\n return names[0];\n }\n\n public abstract String getDescription();\n\n public static void sendMessage(String message)\n {\n KyroClient.mc.thePlayer.addChatMessage(new ChatComponentText(message));\n }\n}"
}
] | import me.kyroclient.KyroClient;
import me.kyroclient.commands.Command;
import java.util.stream.Collectors; | 1,834 | package me.kyroclient.commands.impl;
public class FriendCommand extends Command {
public FriendCommand()
{
super("friend");
}
@Override
public void execute(String[] args) throws Exception {
if (args.length != 3)
{
printFriends();
return;
}
switch (args[1])
{
case "add": | package me.kyroclient.commands.impl;
public class FriendCommand extends Command {
public FriendCommand()
{
super("friend");
}
@Override
public void execute(String[] args) throws Exception {
if (args.length != 3)
{
printFriends();
return;
}
switch (args[1])
{
case "add": | KyroClient.friendManager.add(args[2]); | 0 | 2023-10-15 16:24:51+00:00 | 4k |
ssap-rainbow/SSAP-BackEnd | src/main/java/ssap/ssap/service/BidService.java | [
{
"identifier": "Auction",
"path": "src/main/java/ssap/ssap/domain/Auction.java",
"snippet": "@Getter\n@Setter\n@Entity\npublic class Auction {\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private Long id;\n\n private LocalDateTime startTime;\n private LocalDateTime endTime;\n\n @ManyToOne\n @JoinColumn(name = \"task_id\")\n private Task task;\n}"
},
{
"identifier": "Bid",
"path": "src/main/java/ssap/ssap/domain/Bid.java",
"snippet": "@Getter\n@Setter\n@Entity\npublic class Bid {\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private Long id;\n\n @ManyToOne\n @JoinColumn(name = \"task_id\", nullable = false)\n private Task task;\n\n @ManyToOne\n @JoinColumn(name = \"user_id\", nullable = false)\n private User user;\n\n @ManyToOne\n @JoinColumn(name = \"auction_id\", nullable = false)\n private Auction auction;\n\n private Integer amount; // 입찰 금액\n\n private LocalDateTime time; // 입찰 시간\n private Boolean termsAgreed;\n\n\n}"
},
{
"identifier": "Task",
"path": "src/main/java/ssap/ssap/domain/Task.java",
"snippet": "@Getter\n@Setter\n@ToString\n@NoArgsConstructor\n@Entity\n@Table(name = \"tasks\")\npublic class Task {\n //ToDo: 테이블 필드 검증 추가 필요\n\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n @Column\n private Long id;\n\n @Column\n private String title;\n\n @Column\n private String description;\n\n// @Column\n// private String location;\n\n @Column\n private String roadAddress;\n\n @Column\n private String jibunAddress;\n\n @Column\n private String detailedAddress;\n\n @Column\n private String preferredGender;\n\n @Column\n private String startTime;\n\n @Column\n private String endTime;\n\n @Column\n private String fee;\n\n @Column\n private Boolean auctionStatus;\n\n @Column\n private Boolean termsAgreed;\n\n @Column\n private String auctionStartTime;\n\n @Column\n private String auctionEndTime;\n\n @Column\n private String status;\n\n @ManyToOne(fetch = FetchType.LAZY)\n @JoinColumn(name = \"user_id\")\n private User user;\n\n @ManyToOne(fetch = FetchType.LAZY)\n @JoinColumn(name = \"helper_id\")\n private User helper;\n\n @ManyToOne(fetch = FetchType.LAZY)\n @JoinColumn(name = \"category_id\")\n private Category category;\n\n @ManyToOne(fetch = FetchType.LAZY)\n @JoinColumn(name = \"detailed_item_id\")\n private DetailedItem detailedItem;\n\n @ManyToOne(fetch = FetchType.LAZY)\n @JoinColumn(name = \"auction_id\")\n private Auction auction;\n\n @OneToMany(mappedBy = \"task\", cascade = CascadeType.ALL)\n private List<TaskAttachment> attachments; // Task와 ThumbNailEntity의 연관 관계 설정\n}"
},
{
"identifier": "User",
"path": "src/main/java/ssap/ssap/domain/User.java",
"snippet": "@Entity\n@Getter\n@Setter\n@Table(name = \"users\")\npublic class User {\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private Long userId;\n\n @Column(name = \"provider_id\", unique = true)\n private String providerId;\n\n @Column(name = \"name\", nullable = false)\n private String name;\n\n @Column(name = \"email\", nullable = false)\n private String email;\n\n @Column(name = \"gender\", nullable = true)\n private String gender;\n\n @Column(name = \"birthdate\", nullable = true)\n private String birthdate;\n\n @Column(name = \"ageRange\", nullable = true)\n private String ageRange;\n\n @Column(name = \"profileImageUrl\", nullable = true)\n private String profileImageUrl;\n\n}"
},
{
"identifier": "BidRequestDto",
"path": "src/main/java/ssap/ssap/dto/BidRequestDto.java",
"snippet": "@Getter\n@Setter\npublic class BidRequestDto {\n private Long taskId;\n private String userEmail;\n private Integer bidAmount;\n private boolean termsAgreed;\n private Long auctionId;\n\n\n}"
},
{
"identifier": "BidResponseDto",
"path": "src/main/java/ssap/ssap/dto/BidResponseDto.java",
"snippet": "@Getter\n@Setter\n@AllArgsConstructor\npublic class BidResponseDto {\n private Long id;\n private Integer amount;\n private String userEmail;\n private String userName;\n private LocalDateTime time;\n\n\n}"
},
{
"identifier": "AuctionRepository",
"path": "src/main/java/ssap/ssap/repository/AuctionRepository.java",
"snippet": "@Repository\npublic interface AuctionRepository extends JpaRepository<Auction, Long> {\n Optional<Auction> findByTaskId(Long taskId);\n}"
},
{
"identifier": "BidRepository",
"path": "src/main/java/ssap/ssap/repository/BidRepository.java",
"snippet": "public interface BidRepository extends JpaRepository<Bid, Long> {\n @Query(\"SELECT MIN(b.amount) FROM Bid b WHERE b.auction.id = :auctionId\")\n Integer findLowestBidAmountByAuctionId(@Param(\"auctionId\") Long auctionId);\n\n Bid findTopByAuctionIdOrderByTimeDesc(Long auctionId);\n}"
},
{
"identifier": "TaskRepository",
"path": "src/main/java/ssap/ssap/repository/TaskRepository.java",
"snippet": "@Repository\npublic interface TaskRepository extends JpaRepository<Task, Long> {\n Page<Task> findByCategoryId(Long categoryId, Pageable pageable);\n Page<Task> findByJibunAddressContaining(String district, Pageable pageable);\n Page<Task> findByCategoryIdAndJibunAddressContaining(Long categoryId, String district, Pageable pageable);\n}"
},
{
"identifier": "UserRepository",
"path": "src/main/java/ssap/ssap/repository/UserRepository.java",
"snippet": "public interface UserRepository extends JpaRepository<User, Long> {\n Optional<User> findByProviderId(String providerId);\n\n Optional<User> findByEmail(String email);\n}"
}
] | import jakarta.persistence.EntityNotFoundException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ssap.ssap.domain.Auction;
import ssap.ssap.domain.Bid;
import ssap.ssap.domain.Task;
import ssap.ssap.domain.User;
import ssap.ssap.dto.BidRequestDto;
import ssap.ssap.dto.BidResponseDto;
import ssap.ssap.repository.AuctionRepository;
import ssap.ssap.repository.BidRepository;
import ssap.ssap.repository.TaskRepository;
import ssap.ssap.repository.UserRepository;
import java.time.LocalDateTime; | 2,229 | package ssap.ssap.service;
@Slf4j
@Service
public class BidService {
private final TaskRepository taskRepository;
private final UserRepository userRepository;
private final BidRepository bidRepository;
private final AuctionRepository auctionRepository;
@Autowired
public BidService(TaskRepository taskRepository, UserRepository userRepository, BidRepository bidRepository, AuctionRepository auctionRepository) {
this.taskRepository = taskRepository;
this.userRepository = userRepository;
this.bidRepository = bidRepository;
this.auctionRepository = auctionRepository;
}
@Transactional
public String placeBid(BidRequestDto bidRequest) {
log.info("입찰 요청 처리 시작: {}", bidRequest);
Task task = taskRepository.findById(bidRequest.getTaskId())
.orElseThrow(() -> new EntityNotFoundException("심부름을 찾을 수 없습니다: " + bidRequest.getTaskId()));
log.debug("심부름 조회 성공: {}", task);
User user = userRepository.findByEmail(bidRequest.getUserEmail())
.orElseThrow(() -> new EntityNotFoundException("사용자를 찾을 수 없습니다: " + bidRequest.getUserEmail()));
log.debug("사용자 조회 성공: {}", user);
// 경매 상태 및 입찰 가능 여부 검증
Auction auction = auctionRepository.findById(bidRequest.getAuctionId())
.orElseThrow(() -> new EntityNotFoundException("경매를 찾을 수 없습니다: " + bidRequest.getAuctionId()));
log.debug("경매 조회 성공: {}", auction);
if (LocalDateTime.now().isAfter(auction.getEndTime())) {
throw new IllegalArgumentException("이미 종료된 경매에는 입찰할 수 없습니다.");
}
// 최저 입찰 금액 검증
Integer currentLowestBid = bidRepository.findLowestBidAmountByAuctionId(auction.getId());
Integer taskFee = Integer.valueOf(task.getFee());
if (currentLowestBid != null) {
if (bidRequest.getBidAmount() >= currentLowestBid) {
log.error("입찰 실패: 입찰 금액 ({})은 현재 최저 입찰 금액 ({})보다 낮아야 함", bidRequest.getBidAmount(), currentLowestBid);
throw new IllegalArgumentException("입찰 금액은 현재 최저 입찰 금액보다 낮아야 합니다.");
}
} else if (bidRequest.getBidAmount() >= taskFee) {
// 최초 입찰인 경우, 입찰 금액이 Task의 fee보다 낮아야 함
log.error("입찰 실패: 입찰 금액 ({})은 Task의 fee 금액 ({})보다 낮아야 함", bidRequest.getBidAmount(), taskFee);
throw new IllegalArgumentException("입찰 금액은 현재 최저 입찰 금액보다 낮아야 합니다.");
}
// 입찰 처리 | package ssap.ssap.service;
@Slf4j
@Service
public class BidService {
private final TaskRepository taskRepository;
private final UserRepository userRepository;
private final BidRepository bidRepository;
private final AuctionRepository auctionRepository;
@Autowired
public BidService(TaskRepository taskRepository, UserRepository userRepository, BidRepository bidRepository, AuctionRepository auctionRepository) {
this.taskRepository = taskRepository;
this.userRepository = userRepository;
this.bidRepository = bidRepository;
this.auctionRepository = auctionRepository;
}
@Transactional
public String placeBid(BidRequestDto bidRequest) {
log.info("입찰 요청 처리 시작: {}", bidRequest);
Task task = taskRepository.findById(bidRequest.getTaskId())
.orElseThrow(() -> new EntityNotFoundException("심부름을 찾을 수 없습니다: " + bidRequest.getTaskId()));
log.debug("심부름 조회 성공: {}", task);
User user = userRepository.findByEmail(bidRequest.getUserEmail())
.orElseThrow(() -> new EntityNotFoundException("사용자를 찾을 수 없습니다: " + bidRequest.getUserEmail()));
log.debug("사용자 조회 성공: {}", user);
// 경매 상태 및 입찰 가능 여부 검증
Auction auction = auctionRepository.findById(bidRequest.getAuctionId())
.orElseThrow(() -> new EntityNotFoundException("경매를 찾을 수 없습니다: " + bidRequest.getAuctionId()));
log.debug("경매 조회 성공: {}", auction);
if (LocalDateTime.now().isAfter(auction.getEndTime())) {
throw new IllegalArgumentException("이미 종료된 경매에는 입찰할 수 없습니다.");
}
// 최저 입찰 금액 검증
Integer currentLowestBid = bidRepository.findLowestBidAmountByAuctionId(auction.getId());
Integer taskFee = Integer.valueOf(task.getFee());
if (currentLowestBid != null) {
if (bidRequest.getBidAmount() >= currentLowestBid) {
log.error("입찰 실패: 입찰 금액 ({})은 현재 최저 입찰 금액 ({})보다 낮아야 함", bidRequest.getBidAmount(), currentLowestBid);
throw new IllegalArgumentException("입찰 금액은 현재 최저 입찰 금액보다 낮아야 합니다.");
}
} else if (bidRequest.getBidAmount() >= taskFee) {
// 최초 입찰인 경우, 입찰 금액이 Task의 fee보다 낮아야 함
log.error("입찰 실패: 입찰 금액 ({})은 Task의 fee 금액 ({})보다 낮아야 함", bidRequest.getBidAmount(), taskFee);
throw new IllegalArgumentException("입찰 금액은 현재 최저 입찰 금액보다 낮아야 합니다.");
}
// 입찰 처리 | Bid newBid = new Bid(); | 1 | 2023-10-17 08:45:39+00:00 | 4k |
AstroDev2023/2023-studio-1-but-better | source/core/src/main/com/csse3200/game/entities/EntityIndicator.java | [
{
"identifier": "CameraComponent",
"path": "source/core/src/main/com/csse3200/game/components/CameraComponent.java",
"snippet": "public class CameraComponent extends Component {\n\tprivate final Camera camera;\n\tprivate Vector2 lastPosition;\n\tprivate Entity trackEntity;\n\n\t/**\n\t * Creates a new CameraComponent with a default OrthographicCamera.\n\t */\n\tpublic CameraComponent() {\n\t\tthis(new OrthographicCamera());\n\t}\n\n\t/**\n\t * Creates a new CameraComponent with a specified camera.\n\t *\n\t * @param camera The camera to use for rendering.\n\t */\n\tpublic CameraComponent(Camera camera) {\n\t\tOrthographicCamera orthographicCamera = (OrthographicCamera) camera;\n\t\torthographicCamera.zoom = UserSettings.get().zoomScale;\n\t\tthis.camera = camera;\n\t\tlastPosition = Vector2.Zero.cpy();\n\t}\n\n\t/**\n\t * Updates the camera's position based on the tracked entity's position.\n\t */\n\t@Override\n\tpublic void update() {\n\t\tVector2 position;\n\t\tif (trackEntity != null) {\n\t\t\t// Since physics body is updated separately from entity position, camera should be set to body if it exists\n\t\t\t// This avoids glitchy camera behaviour when framerate != physics timestep\n\t\t\tPhysicsComponent physicsComponent = trackEntity.getComponent(PhysicsComponent.class);\n\t\t\tif (physicsComponent != null) {\n\t\t\t\tentity.setPosition(physicsComponent.getBody().getPosition().mulAdd(trackEntity.getScale(), 0.5f));\n\t\t\t} else {\n\t\t\t\tentity.setPosition(trackEntity.getCenterPosition());\n\t\t\t}\n\t\t}\n\n\t\tposition = entity.getPosition();\n\t\tif (!lastPosition.epsilonEquals(entity.getPosition())) {\n\t\t\tcamera.position.set(position.x, position.y, 0f);\n\t\t\tlastPosition = position;\n\t\t\tcamera.update();\n\t\t}\n\t}\n\n\tpublic Matrix4 getProjectionMatrix() {\n\t\treturn camera.combined;\n\t}\n\n\tpublic Camera getCamera() {\n\t\treturn camera;\n\t}\n\n\t/**\n\t * Sets the entity to track by the camera.\n\t *\n\t * @param trackEntity The entity to track.\n\t */\n\tpublic void setTrackEntity(Entity trackEntity) {\n\t\tthis.trackEntity = trackEntity;\n\t}\n\n\t/**\n\t * Gets the entity currently tracked by the camera.\n\t *\n\t * @return The tracked entity.\n\t */\n\tpublic Entity getTrackEntity() {\n\t\treturn trackEntity;\n\t}\n\n\tpublic void resize(int screenWidth, int screenHeight, float gameWidth) {\n\t\tfloat ratio = (float) screenHeight / screenWidth;\n\t\tcamera.viewportWidth = gameWidth;\n\t\tcamera.viewportHeight = gameWidth * ratio;\n\t\tcamera.update();\n\t}\n\n\t/**\n\t * Converts screen position vector to world position vector\n\t *\n\t * @param screenPosition Vector2 object with x, y screen position.\n\t * @return vector of real world position\n\t */\n\tpublic Vector2 screenPositionToWorldPosition(Vector2 screenPosition) {\n\t\tVector3 worldPosition = ServiceLocator.getCameraComponent().getCamera()\n\t\t\t\t.unproject(new Vector3(screenPosition.x, screenPosition.y, 0));\n\n\t\treturn new Vector2(worldPosition.x, worldPosition.y);\n\t}\n\n\t/**\n\t * Determines if the given entity is on the screen\n\t *\n\t * @param entity: entity to be checked\n\t * @return true if on screen else false\n\t */\n\tpublic boolean entityOnScreen(Entity entity) {\n\t\tVector2 position = entity.getCenterPosition();\n\t\treturn camera.frustum.pointInFrustum(position.x, position.y, 0);\n\t}\n}"
},
{
"identifier": "ServiceLocator",
"path": "source/core/src/main/com/csse3200/game/services/ServiceLocator.java",
"snippet": "public class ServiceLocator {\n\tprivate static final Logger logger = LoggerFactory.getLogger(ServiceLocator.class);\n\tprivate static EntityService entityService;\n\tprivate static RenderService renderService;\n\tprivate static PhysicsService physicsService;\n\tprivate static InputService inputService;\n\tprivate static ResourceService resourceService;\n\tprivate static TimeService timeService;\n\tprivate static GameTime timeSource;\n\tprivate static GameArea gameArea;\n\tprivate static LightService lightService;\n\tprivate static GameAreaDisplay pauseMenuArea;\n\tprivate static GameAreaDisplay craftArea;\n\tprivate static GdxGame game;\n\tprivate static InventoryDisplayManager inventoryDisplayManager;\n\tprivate static CameraComponent cameraComponent;\n\tprivate static SaveLoadService saveLoadService;\n\tprivate static MissionManager missions;\n\tprivate static PlanetOxygenService planetOxygenService;\n\tprivate static SoundService soundService;\n\tprivate static UIService uiService;\n\n\tprivate static PlantCommandService plantCommandService;\n\tprivate static PlayerHungerService playerHungerService;\n\n\tprivate static PlayerMapService playerMapService;\n\n\tprivate static PlantInfoService plantInfoService;\n\tprivate static boolean cutSceneRunning; // true for running and false otherwise\n\n\tprivate static ParticleService particleService;\n\n\tpublic static PlantCommandService getPlantCommandService() {\n\t\treturn plantCommandService;\n\t}\n\n\tpublic static PlantInfoService getPlantInfoService() {\n\t\treturn plantInfoService;\n\t}\n\n\tpublic static boolean god = false;\n\n\tpublic static GameArea getGameArea() {\n\t\treturn gameArea;\n\t}\n\n\tpublic static CameraComponent getCameraComponent() {\n\t\treturn cameraComponent;\n\t}\n\n\tpublic static EntityService getEntityService() {\n\t\treturn entityService;\n\t}\n\n\tpublic static RenderService getRenderService() {\n\t\treturn renderService;\n\t}\n\n\tpublic static PhysicsService getPhysicsService() {\n\t\treturn physicsService;\n\t}\n\n\tpublic static InputService getInputService() {\n\t\treturn inputService;\n\t}\n\n\tpublic static ResourceService getResourceService() {\n\t\treturn resourceService;\n\t}\n\n\tpublic static GameTime getTimeSource() {\n\t\treturn timeSource;\n\t}\n\n\tpublic static TimeService getTimeService() {\n\t\treturn timeService;\n\t}\n\n\tpublic static LightService getLightService() {\n\t\treturn lightService;\n\t}\n\n\tpublic static MissionManager getMissionManager() {\n\t\treturn missions;\n\t}\n\n\tpublic static PlanetOxygenService getPlanetOxygenService() {\n\t\treturn planetOxygenService;\n\t}\n\n\tpublic static PlayerHungerService getPlayerHungerService() {\n\t\treturn playerHungerService;\n\t}\n\n\tpublic static PlayerMapService getPlayerMapService() {\n\t\treturn playerMapService;\n\t}\n\n\tpublic static SaveLoadService getSaveLoadService() {\n\t\treturn saveLoadService;\n\t}\n\n\tpublic static SoundService getSoundService() {\n\t\treturn soundService;\n\t}\n\n\tpublic static UIService getUIService() {\n\t\treturn uiService;\n\t}\n\n\tpublic static ParticleService getParticleService() {\n\t\treturn particleService;\n\t}\n\n\t/**\n\t * Sets the cutscene status to either running or not running.\n\t *\n\t * @param isRunning true if cutscene is running, false otherwise\n\t */\n\tpublic static void setCutSceneRunning(boolean isRunning) {\n\t\tcutSceneRunning = isRunning;\n\t}\n\n\t/**\n\t * Gets the cutscene status.\n\t *\n\t * @return true if cutscene is running, false otherwise\n\t */\n\tpublic static boolean getCutSceneStatus() {\n\t\treturn cutSceneRunning;\n\t}\n\n\tpublic static void registerGameArea(GameArea area) {\n\t\tlogger.debug(\"Registering game area {}\", area);\n\t\tgameArea = area;\n\t}\n\n\tpublic static void registerCameraComponent(CameraComponent camera) {\n\t\tlogger.debug(\"Registering game area {}\", camera);\n\t\tcameraComponent = camera;\n\t}\n\n\tpublic static void registerEntityService(EntityService service) {\n\t\tlogger.debug(\"Registering entity service {}\", service);\n\t\tentityService = service;\n\t}\n\n\tpublic static void registerRenderService(RenderService service) {\n\t\tlogger.debug(\"Registering render service {}\", service);\n\t\trenderService = service;\n\t}\n\n\tpublic static void registerPhysicsService(PhysicsService service) {\n\t\tlogger.debug(\"Registering physics service {}\", service);\n\t\tphysicsService = service;\n\t}\n\n\tpublic static void registerTimeService(TimeService service) {\n\t\tlogger.debug(\"Registering time service {}\", service);\n\t\ttimeService = service;\n\t}\n\n\tpublic static void registerInputService(InputService source) {\n\t\tlogger.debug(\"Registering input service {}\", source);\n\t\tinputService = source;\n\t}\n\n\tpublic static void registerResourceService(ResourceService source) {\n\t\tlogger.debug(\"Registering resource service {}\", source);\n\t\tresourceService = source;\n\t}\n\n\tpublic static void registerTimeSource(GameTime source) {\n\t\tlogger.debug(\"Registering time source {}\", source);\n\t\ttimeSource = source;\n\t}\n\n\tpublic static void registerMissionManager(MissionManager source) {\n\t\tlogger.debug(\"Registering mission manager {}\", source);\n\t\tmissions = source;\n\t}\n\n\tpublic static void registerUIService(UIService source) {\n\t\tlogger.debug(\"Registering UI service {}\", source);\n\t\tuiService = source;\n\t}\n\n\tpublic static void registerPlanetOxygenService(PlanetOxygenService source) {\n\t\tlogger.debug(\"Registering planet oxygen service {}\", source);\n\t\tplanetOxygenService = source;\n\t}\n\n\n\tpublic static void registerPlayerHungerService(PlayerHungerService source) {\n\t\tlogger.debug(\"Registering player hunger service {}\", source);\n\t\tplayerHungerService = source;\n\t}\n\n\tpublic static void registerPlayerMapService(PlayerMapService source) {\n\t\tlogger.debug(\"Registering player map service {}\", source);\n\t\tplayerMapService = source;\n\t}\n\n\tpublic static void registerPlantCommandService(PlantCommandService source) {\n\t\tlogger.debug(\"Registering plant command service {}\", source);\n\t\tplantCommandService = source;\n\t}\n\n\tpublic static void registerPlantInfoService(PlantInfoService source) {\n\t\tlogger.debug(\"Registering plant command service {}\", source);\n\t\tplantInfoService = source;\n\t}\n\n\tpublic static void registerLightService(LightService source) {\n\t\tlogger.debug(\"Registering light service {}\", source);\n\t\tlightService = source;\n\t}\n\n\tpublic static void registerInventoryDisplayManager(InventoryDisplayManager source) {\n\t\tlogger.debug(\"Registering inventory display manager {}\", source);\n\t\tinventoryDisplayManager = source;\n\t}\n\n\tpublic static void registerParticleService(ParticleService source) {\n\t\tparticleService = source;\n\t}\n\n\t/**\n\t * Registers the save/load service.\n\t *\n\t * @param source the service to register\n\t */\n\tpublic static void registerSaveLoadService(SaveLoadService source) {\n\t\tlogger.debug(\"Registering Save/Load service {}\", source);\n\t\tsaveLoadService = source;\n\t}\n\n\tpublic static void registerSoundService(SoundService source) {\n\t\tlogger.debug(\"Registering sound service {}\", source);\n\t\tsoundService = source;\n\t}\n\n\t/**\n\t * Clears all registered services.\n\t * Do not clear saveLoadService\n\t */\n\tpublic static void clear() {\n\t\tentityService = null;\n\t\trenderService = null;\n\t\tphysicsService = null;\n\t\ttimeSource = null;\n\t\tinputService = null;\n\t\tresourceService = null;\n\t\tgameArea = null;\n\t\tsoundService = null;\n\t\tlightService = null;\n\t\tparticleService = null;\n\t\ttimeService = null;\n\t\tuiService = null;\n\t}\n\n\tprivate ServiceLocator() {\n\t\tthrow new IllegalStateException(\"Instantiating static util class\");\n\t}\n\n\tpublic static void registerPauseArea(GameAreaDisplay area) {\n\t\tpauseMenuArea = area;\n\t}\n\n\tpublic static GameAreaDisplay getPauseMenuArea() {\n\t\treturn pauseMenuArea;\n\t}\n\n\tpublic static InventoryDisplayManager getInventoryDisplayManager() {\n\t\treturn inventoryDisplayManager;\n\t}\n\n\tpublic static void registerCraftArea(GameAreaDisplay area) {\n\t\tcraftArea = area;\n\t}\n\n\tpublic static GameAreaDisplay getCraftArea() {\n\t\treturn craftArea;\n\t}\n\n\tpublic static void registerGame(GdxGame gameVar) {\n\t\tgame = gameVar;\n\t}\n\n\tpublic static GdxGame getGame() {\n\t\treturn game;\n\t}\n\n\n}"
},
{
"identifier": "UIComponent",
"path": "source/core/src/main/com/csse3200/game/ui/UIComponent.java",
"snippet": "public abstract class UIComponent extends RenderComponent implements Renderable {\n\tprivate static final int UI_LAYER = 2;\n\tprotected static final Skin skin =\n\t\t\tnew Skin(Gdx.files.internal(\"gardens-of-the-galaxy-v3/gardens-of-the-galaxy-v3.json\"));\n\tprotected Stage stage;\n\n\t@Override\n\tpublic void create() {\n\t\tsuper.create();\n\t\tstage = ServiceLocator.getRenderService().getStage();\n\t}\n\n\t@Override\n\tpublic int getLayer() {\n\t\treturn UI_LAYER;\n\t}\n\n\t@Override\n\tpublic float getZIndex() {\n\t\treturn 1f;\n\t}\n}"
}
] | import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.scenes.scene2d.ui.Image;
import com.csse3200.game.components.CameraComponent;
import com.csse3200.game.services.ServiceLocator;
import com.csse3200.game.ui.UIComponent; | 3,515 | package com.csse3200.game.entities;
/**
* A UI component responsible for indicating the direction of an entity which is off-screen
*/
public class EntityIndicator extends UIComponent {
/**
* Indicator image
*/
private Image indicator;
/**
* Indicator asset path
*/
private String indicatorAssetPath;
/**
* The hostile entity being tracked
*/
private Entity entityToTractor;
/**
* The camera component of the game
*/
private CameraComponent cameraComponent;
/**
* Distance from center
*/
private static final float INDICATOR_DISTANCE = 175;
/**
* Initialise a new indicator for the given entity
*
* @param entity: the entity which will be tracked
*/
public EntityIndicator(Entity entity) {
this(entity, "images/hostile_indicator.png");
}
/**
* Initialise a new indicator for the given entity
*
* @param entity: the entity which will be tracked
* @param indicatorAssetPath: path for the indicator asset
*/
public EntityIndicator(Entity entity, String indicatorAssetPath) {
this.indicatorAssetPath = indicatorAssetPath;
this.entityToTractor = entity; | package com.csse3200.game.entities;
/**
* A UI component responsible for indicating the direction of an entity which is off-screen
*/
public class EntityIndicator extends UIComponent {
/**
* Indicator image
*/
private Image indicator;
/**
* Indicator asset path
*/
private String indicatorAssetPath;
/**
* The hostile entity being tracked
*/
private Entity entityToTractor;
/**
* The camera component of the game
*/
private CameraComponent cameraComponent;
/**
* Distance from center
*/
private static final float INDICATOR_DISTANCE = 175;
/**
* Initialise a new indicator for the given entity
*
* @param entity: the entity which will be tracked
*/
public EntityIndicator(Entity entity) {
this(entity, "images/hostile_indicator.png");
}
/**
* Initialise a new indicator for the given entity
*
* @param entity: the entity which will be tracked
* @param indicatorAssetPath: path for the indicator asset
*/
public EntityIndicator(Entity entity, String indicatorAssetPath) {
this.indicatorAssetPath = indicatorAssetPath;
this.entityToTractor = entity; | cameraComponent = ServiceLocator.getCameraComponent(); | 1 | 2023-10-17 22:34:04+00:00 | 4k |
moeinfatehi/PassiveDigger | src/PassiveDigger/vulnerability.java | [
{
"identifier": "BurpExtender",
"path": "src/burp/BurpExtender.java",
"snippet": "public class BurpExtender extends JPanel implements IBurpExtender\r\n{\r\n \r\n public static IBurpExtenderCallbacks callbacks;\r\n static JScrollPane frame;\r\n public static PrintWriter output;\r\n public static String project_Name=\"PassiveDigger\";\r\n private static final String project_Version=\"2.0.0\";\r\n \r\n public BurpExtender() {\r\n// this.historyModel = (DefaultTableModel)mainPanel.historyTable.getModel();\r\n }\r\n \r\n @Override\r\n public void registerExtenderCallbacks(final IBurpExtenderCallbacks callbacks)\r\n {\r\n // keep a reference to our callbacks object\r\n this.callbacks = callbacks;\r\n callbacks.registerHttpListener(new PassiveAnalyzer());\r\n output = new PrintWriter(callbacks.getStdout(), true);\r\n // create our UI\r\n SwingUtilities.invokeLater(new Runnable()\r\n {\r\n @Override\r\n public void run()\r\n {\r\n initComponents();\r\n // customize our UI components\r\n callbacks.customizeUiComponent(tab.panel);\r\n \r\n // add the custom tab to Burp's UI\r\n callbacks.addSuiteTab(tab.tb);\r\n callbacks.registerContextMenuFactory(new menuItem());\r\n \r\n }\r\n });\r\n }\r\n \r\n private void initComponents() {\r\n }// </editor-fold>\r\n \r\n public byte[] processProxyMessage(int messageReference, boolean messageIsRequest, String remoteHost, int remotePort, boolean serviceIsHttps, String httpMethod, String url,\r\n String resourceType, String statusCode, String responseContentType, byte message[], int action[])\r\n {\r\n return message;\r\n }\r\n \r\n public static String getProjectName(){\r\n return project_Name;\r\n }\r\n public static String getVersion(){\r\n return project_Version;\r\n }\r\n \r\n}"
},
{
"identifier": "IHttpRequestResponse",
"path": "src/burp/IHttpRequestResponse.java",
"snippet": "public interface IHttpRequestResponse\r\n{\r\n /**\r\n * This method is used to retrieve the request message.\r\n *\r\n * @return The request message.\r\n */\r\n byte[] getRequest();\r\n\r\n /**\r\n * This method is used to update the request message.\r\n *\r\n * @param message The new request message.\r\n */\r\n void setRequest(byte[] message);\r\n\r\n /**\r\n * This method is used to retrieve the response message.\r\n *\r\n * @return The response message.\r\n */\r\n byte[] getResponse();\r\n\r\n /**\r\n * This method is used to update the response message.\r\n *\r\n * @param message The new response message.\r\n */\r\n void setResponse(byte[] message);\r\n\r\n /**\r\n * This method is used to retrieve the user-annotated comment for this item,\r\n * if applicable.\r\n *\r\n * @return The user-annotated comment for this item, or null if none is set.\r\n */\r\n String getComment();\r\n\r\n /**\r\n * This method is used to update the user-annotated comment for this item.\r\n *\r\n * @param comment The comment to be assigned to this item.\r\n */\r\n void setComment(String comment);\r\n\r\n /**\r\n * This method is used to retrieve the user-annotated highlight for this\r\n * item, if applicable.\r\n *\r\n * @return The user-annotated highlight for this item, or null if none is\r\n * set.\r\n */\r\n String getHighlight();\r\n\r\n /**\r\n * This method is used to update the user-annotated highlight for this item.\r\n *\r\n * @param color The highlight color to be assigned to this item. Accepted\r\n * values are: red, orange, yellow, green, cyan, blue, pink, magenta, gray,\r\n * or a null String to clear any existing highlight.\r\n */\r\n void setHighlight(String color);\r\n\r\n /**\r\n * This method is used to retrieve the HTTP service for this request /\r\n * response.\r\n *\r\n * @return An\r\n * <code>IHttpService</code> object containing details of the HTTP service.\r\n */\r\n IHttpService getHttpService();\r\n\r\n /**\r\n * This method is used to update the HTTP service for this request /\r\n * response.\r\n *\r\n * @param httpService An\r\n * <code>IHttpService</code> object containing details of the new HTTP\r\n * service.\r\n */\r\n void setHttpService(IHttpService httpService);\r\n\r\n}\r"
},
{
"identifier": "IParameter",
"path": "src/burp/IParameter.java",
"snippet": "public interface IParameter\r\n{\r\n /**\r\n * Used to indicate a parameter within the URL query string.\r\n */\r\n static final byte PARAM_URL = 0;\r\n /**\r\n * Used to indicate a parameter within the message body.\r\n */\r\n static final byte PARAM_BODY = 1;\r\n /**\r\n * Used to indicate an HTTP cookie.\r\n */\r\n static final byte PARAM_COOKIE = 2;\r\n /**\r\n * Used to indicate an item of data within an XML structure.\r\n */\r\n static final byte PARAM_XML = 3;\r\n /**\r\n * Used to indicate the value of a tag attribute within an XML structure.\r\n */\r\n static final byte PARAM_XML_ATTR = 4;\r\n /**\r\n * Used to indicate the value of a parameter attribute within a multi-part\r\n * message body (such as the name of an uploaded file).\r\n */\r\n static final byte PARAM_MULTIPART_ATTR = 5;\r\n /**\r\n * Used to indicate an item of data within a JSON structure.\r\n */\r\n static final byte PARAM_JSON = 6;\r\n\r\n /**\r\n * This method is used to retrieve the parameter type.\r\n *\r\n * @return The parameter type. The available types are defined within this\r\n * interface.\r\n */\r\n byte getType();\r\n\r\n /**\r\n * This method is used to retrieve the parameter name.\r\n *\r\n * @return The parameter name.\r\n */\r\n String getName();\r\n\r\n /**\r\n * This method is used to retrieve the parameter value.\r\n *\r\n * @return The parameter value.\r\n */\r\n String getValue();\r\n\r\n /**\r\n * This method is used to retrieve the start offset of the parameter name\r\n * within the HTTP request.\r\n *\r\n * @return The start offset of the parameter name within the HTTP request,\r\n * or -1 if the parameter is not associated with a specific request.\r\n */\r\n int getNameStart();\r\n\r\n /**\r\n * This method is used to retrieve the end offset of the parameter name\r\n * within the HTTP request.\r\n *\r\n * @return The end offset of the parameter name within the HTTP request, or\r\n * -1 if the parameter is not associated with a specific request.\r\n */\r\n int getNameEnd();\r\n\r\n /**\r\n * This method is used to retrieve the start offset of the parameter value\r\n * within the HTTP request.\r\n *\r\n * @return The start offset of the parameter value within the HTTP request,\r\n * or -1 if the parameter is not associated with a specific request.\r\n */\r\n int getValueStart();\r\n\r\n /**\r\n * This method is used to retrieve the end offset of the parameter value\r\n * within the HTTP request.\r\n *\r\n * @return The end offset of the parameter value within the HTTP request, or\r\n * -1 if the parameter is not associated with a specific request.\r\n */\r\n int getValueEnd();\r\n}\r"
},
{
"identifier": "IRequestInfo",
"path": "src/burp/IRequestInfo.java",
"snippet": "public interface IRequestInfo\r\n{\r\n /**\r\n * Used to indicate that there is no content.\r\n */\r\n static final byte CONTENT_TYPE_NONE = 0;\r\n /**\r\n * Used to indicate URL-encoded content.\r\n */\r\n static final byte CONTENT_TYPE_URL_ENCODED = 1;\r\n /**\r\n * Used to indicate multi-part content.\r\n */\r\n static final byte CONTENT_TYPE_MULTIPART = 2;\r\n /**\r\n * Used to indicate XML content.\r\n */\r\n static final byte CONTENT_TYPE_XML = 3;\r\n /**\r\n * Used to indicate JSON content.\r\n */\r\n static final byte CONTENT_TYPE_JSON = 4;\r\n /**\r\n * Used to indicate AMF content.\r\n */\r\n static final byte CONTENT_TYPE_AMF = 5;\r\n /**\r\n * Used to indicate unknown content.\r\n */\r\n static final byte CONTENT_TYPE_UNKNOWN = -1;\r\n\r\n /**\r\n * This method is used to obtain the HTTP method used in the request.\r\n *\r\n * @return The HTTP method used in the request.\r\n */\r\n String getMethod();\r\n\r\n /**\r\n * This method is used to obtain the URL in the request.\r\n *\r\n * @return The URL in the request.\r\n */\r\n URL getUrl();\r\n\r\n /**\r\n * This method is used to obtain the HTTP headers contained in the request.\r\n *\r\n * @return The HTTP headers contained in the request.\r\n */\r\n List<String> getHeaders();\r\n\r\n /**\r\n * This method is used to obtain the parameters contained in the request.\r\n *\r\n * @return The parameters contained in the request.\r\n */\r\n List<IParameter> getParameters();\r\n\r\n /**\r\n * This method is used to obtain the offset within the request where the\r\n * message body begins.\r\n *\r\n * @return The offset within the request where the message body begins.\r\n */\r\n int getBodyOffset();\r\n\r\n /**\r\n * This method is used to obtain the content type of the message body.\r\n *\r\n * @return An indication of the content type of the message body. Available\r\n * types are defined within this interface.\r\n */\r\n byte getContentType();\r\n}\r"
}
] | import burp.IHttpRequestResponse;
import burp.IParameter;
import burp.IRequestInfo;
import burp.BurpExtender; | 2,354 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package PassiveDigger;
/**
*
* @author moein
*/
public class vulnerability {
IHttpRequestResponse reqResp; | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package PassiveDigger;
/**
*
* @author moein
*/
public class vulnerability {
IHttpRequestResponse reqResp; | IParameter param; | 2 | 2023-10-23 12:13:00+00:00 | 4k |
LuckPerms/rest-api-java-client | src/main/java/net/luckperms/rest/service/GroupService.java | [
{
"identifier": "CreateGroupRequest",
"path": "src/main/java/net/luckperms/rest/model/CreateGroupRequest.java",
"snippet": "public class CreateGroupRequest extends AbstractModel {\n private final String name;\n\n public CreateGroupRequest(String name) {\n this.name = name;\n }\n\n public String name() {\n return this.name;\n }\n}"
},
{
"identifier": "Group",
"path": "src/main/java/net/luckperms/rest/model/Group.java",
"snippet": "public class Group extends AbstractModel {\n private final String name;\n private final String displayName;\n private final int weight;\n private final Collection<Node> nodes;\n private final Metadata metadata;\n\n public Group(String name, String displayName, int weight, Collection<Node> nodes, Metadata metadata) {\n this.name = name;\n this.displayName = displayName;\n this.weight = weight;\n this.nodes = nodes;\n this.metadata = metadata;\n }\n\n public String name() {\n return this.name;\n }\n\n public int weight() {\n return this.weight;\n }\n\n public Collection<Node> nodes() {\n return this.nodes;\n }\n\n public String displayName() {\n return this.displayName;\n }\n\n public Metadata metadata() {\n return this.metadata;\n }\n}"
},
{
"identifier": "GroupSearchResult",
"path": "src/main/java/net/luckperms/rest/model/GroupSearchResult.java",
"snippet": "public class GroupSearchResult extends AbstractModel {\n private final String name;\n private final Collection<Node> results;\n\n public GroupSearchResult(String name, Collection<Node> results) {\n this.name = name;\n this.results = results;\n }\n\n public String name() {\n return this.name;\n }\n\n public Collection<Node> results() {\n return this.results;\n }\n}"
},
{
"identifier": "Metadata",
"path": "src/main/java/net/luckperms/rest/model/Metadata.java",
"snippet": "public class Metadata extends AbstractModel {\n private final Map<String, String> meta;\n private final String prefix; // nullable\n private final String suffix; // nullable\n private final String primaryGroup; // nullable\n\n public Metadata(Map<String, String> meta, String prefix, String suffix, String primaryGroup) {\n this.meta = meta;\n this.prefix = prefix;\n this.suffix = suffix;\n this.primaryGroup = primaryGroup;\n }\n\n public Map<String, String> meta() {\n return this.meta;\n }\n\n public String prefix() {\n return this.prefix;\n }\n\n public String suffix() {\n return this.suffix;\n }\n\n public String primaryGroup() {\n return this.primaryGroup;\n }\n}"
},
{
"identifier": "Node",
"path": "src/main/java/net/luckperms/rest/model/Node.java",
"snippet": "public class Node extends AbstractModel {\n private final String key;\n private final Boolean value;\n private final Set<Context> context;\n private final Long expiry;\n\n public Node(String key, Boolean value, Set<Context> context, Long expiry) {\n this.key = key;\n this.value = value;\n this.context = context;\n this.expiry = expiry;\n }\n\n public String key() {\n return this.key;\n }\n\n public Boolean value() {\n return this.value;\n }\n\n public Set<Context> context() {\n return this.context;\n }\n\n public Long expiry() {\n return this.expiry;\n }\n}"
},
{
"identifier": "NodeType",
"path": "src/main/java/net/luckperms/rest/model/NodeType.java",
"snippet": "public enum NodeType {\n\n @SerializedName(\"regex_permission\")\n REGEX_PERMISSION,\n\n @SerializedName(\"inheritance\")\n INHERITANCE,\n\n @SerializedName(\"prefix\")\n PREFIX,\n\n @SerializedName(\"suffix\")\n SUFFIX,\n\n @SerializedName(\"meta\")\n META,\n\n @SerializedName(\"weight\")\n WEIGHT,\n\n @SerializedName(\"display_name\")\n DISPLAY_NAME;\n\n @Override\n public String toString() {\n return this.name().toLowerCase(Locale.ROOT);\n }\n}"
},
{
"identifier": "PermissionCheckRequest",
"path": "src/main/java/net/luckperms/rest/model/PermissionCheckRequest.java",
"snippet": "public class PermissionCheckRequest extends AbstractModel {\n private final String permission;\n private final QueryOptions queryOptions; // nullable\n\n public PermissionCheckRequest(String permission, QueryOptions queryOptions) {\n this.permission = permission;\n this.queryOptions = queryOptions;\n }\n\n public String permission() {\n return this.permission;\n }\n\n public QueryOptions queryOptions() {\n return this.queryOptions;\n }\n}"
},
{
"identifier": "PermissionCheckResult",
"path": "src/main/java/net/luckperms/rest/model/PermissionCheckResult.java",
"snippet": "public class PermissionCheckResult extends AbstractModel {\n private final Tristate result;\n private final Node node;\n\n public PermissionCheckResult(Tristate result, Node node) {\n this.result = result;\n this.node = node;\n }\n\n public Tristate result() {\n return this.result;\n }\n\n public Node node() {\n return this.node;\n }\n\n public enum Tristate {\n\n @SerializedName(\"true\")\n TRUE,\n\n @SerializedName(\"false\")\n FALSE,\n\n @SerializedName(\"undefined\")\n UNDEFINED\n }\n}"
},
{
"identifier": "TemporaryNodeMergeStrategy",
"path": "src/main/java/net/luckperms/rest/model/TemporaryNodeMergeStrategy.java",
"snippet": "public enum TemporaryNodeMergeStrategy {\n\n @SerializedName(\"add_new_duration_to_existing\")\n ADD_NEW_DURATION_TO_EXISTING,\n\n @SerializedName(\"replace_existing_if_duration_longer\")\n REPLACE_EXISTING_IF_DURATION_LONGER,\n\n @SerializedName(\"none\")\n NONE\n\n}"
}
] | import net.luckperms.rest.model.CreateGroupRequest;
import net.luckperms.rest.model.Group;
import net.luckperms.rest.model.GroupSearchResult;
import net.luckperms.rest.model.Metadata;
import net.luckperms.rest.model.Node;
import net.luckperms.rest.model.NodeType;
import net.luckperms.rest.model.PermissionCheckRequest;
import net.luckperms.rest.model.PermissionCheckResult;
import net.luckperms.rest.model.TemporaryNodeMergeStrategy;
import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.DELETE;
import retrofit2.http.GET;
import retrofit2.http.HTTP;
import retrofit2.http.PATCH;
import retrofit2.http.POST;
import retrofit2.http.PUT;
import retrofit2.http.Path;
import retrofit2.http.Query;
import java.util.List;
import java.util.Set; | 1,835 | /*
* This file is part of LuckPerms, licensed under the MIT License.
*
* Copyright (c) lucko (Luck) <[email protected]>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.luckperms.rest.service;
public interface GroupService {
@GET("/group")
Call<Set<String>> list();
@POST("/group") | /*
* This file is part of LuckPerms, licensed under the MIT License.
*
* Copyright (c) lucko (Luck) <[email protected]>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.luckperms.rest.service;
public interface GroupService {
@GET("/group")
Call<Set<String>> list();
@POST("/group") | Call<Group> create(@Body CreateGroupRequest req); | 1 | 2023-10-22 16:07:30+00:00 | 4k |
EvanAatrox/hubbo | hubbo/src/test/java/cn/hubbo/unit/UtilsUnitTest.java | [
{
"identifier": "User",
"path": "hubbo-domain/src/main/java/cn/hubbo/domain/dos/User.java",
"snippet": "@Data\n@Accessors(chain = true)\n@Entity(name = \"t_user\")\n@Table(indexes = {@Index(name = \"user_name_index\", columnList = \"user_name\", unique = true),\n @Index(name = \"phone_index\", columnList = \"phone\", unique = true)})\npublic class User extends GsonEntity {\n\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n @Column(name = \"user_id\", columnDefinition = \"integer\", updatable = false)\n @Comment(\"用户ID,不对外暴露\")\n @Ignore\n private Integer userId;\n\n @Column(name = \"user_name\", columnDefinition = \"varchar(60) \", nullable = false)\n @Comment(\"用户名,允许用户使用用户名进行登录\")\n private String username;\n\n @Column(columnDefinition = \"char(11)\", nullable = false)\n @Comment(\"用户手机号,允许使用手机号进行登录操作\")\n private String phone;\n\n @Column(columnDefinition = \"char(60)\", nullable = false)\n @Comment(\"用户密码,固定60位\")\n @Ignore\n private String password;\n\n\n @Column(columnDefinition = \"varchar(30)\", nullable = false, unique = true)\n @Comment(\"用户邮箱\")\n private String email;\n\n @Column(name = \"register_date\", columnDefinition = \"timestamp default current_timestamp()\", nullable = false)\n @Comment(\"注册日期\")\n private Date registerDate;\n\n @Column(columnDefinition = \"bit(1) default 1\")\n @Comment(\"性别,1男,0女\")\n private GenderEnum gender;\n\n @Column(name = \"profile_url\", columnDefinition = \"varchar(255) default 'http://img.zhaogexing.com/2020/01/30/1580360931159906.jpg'\")\n @Comment(\"头像地址\")\n private String profileUrl;\n\n @Column(columnDefinition = \"varchar(255)\")\n @Comment(\"对用户的备注信息\")\n private String remark;\n\n // Spring Security相关的状态位\n\n @Column(name = \"account_status\", columnDefinition = \"bit(1) default 1\")\n @Comment(\"用户账户状态,0锁定,1正常\")\n private AccountStatusEnum accountStatus;\n\n\n @Column(name = \"update_time\", columnDefinition = \"timestamp\")\n @Comment(\"最近一次的更新时间\")\n private Date updateTime;\n\n\n @ManyToMany(fetch = FetchType.EAGER)\n @JoinTable(name = \"t_user_role\",\n joinColumns = {@JoinColumn(name = \"user_id\", nullable = false)},\n inverseJoinColumns = {@JoinColumn(name = \"role_id\", nullable = false)}\n )\n @Ignore\n private List<Role> roles;\n\n\n @Transient\n private Set<String> permissionCodes;\n\n\n public void setRoles(List<Role> roles) {\n getPermissionCodes();\n this.roles = roles;\n }\n\n public Set<String> getPermissionCodes() {\n if (!Objects.isNull(this.permissionCodes)) {\n return this.permissionCodes;\n }\n if (CollectionUtils.isEmpty(roles)) {\n return Sets.newHashSet();\n }\n Set<String> permissionCodes = roles.stream().map(Role::getPermissionCode).collect(Collectors.toSet());\n this.permissionCodes = permissionCodes;\n return permissionCodes;\n }\n\n\n}"
},
{
"identifier": "JsonUtils",
"path": "hubbo-utils/src/main/java/cn/hubbo/utils/common/base/JsonUtils.java",
"snippet": "public class JsonUtils {\n\n\n private static final Gson DEFAULT_GSON;\n\n private static final Gson STRATEGIES_GSON;\n\n\n private static final Map<FieldAttributes, Boolean> cache;\n\n static {\n DEFAULT_GSON = createGson(null);\n STRATEGIES_GSON = createGson(getExclusionStrategies());\n cache = new ConcurrentHashMap<>();\n }\n\n private static Gson createGson(List<ExclusionStrategy> exclusionStrategies) {\n return new GsonBuilder()\n .setDateFormat(\"yyyy-MM-dd HH:mm:ss\")\n .setPrettyPrinting()\n .disableInnerClassSerialization()\n .serializeNulls()\n .setExclusionStrategies(exclusionStrategies == null ? new ExclusionStrategy[]{} : exclusionStrategies.toArray(new ExclusionStrategy[]{}))\n .registerTypeAdapterFactory(new BasicEnumTypeAdapterFactory())\n .create();\n }\n\n\n /**\n * @return 只进行了格式化设置的gson对象\n */\n public static Gson getDefaultGson() {\n return DEFAULT_GSON;\n }\n\n /**\n * @return 指定的排除属性策略的Gson对象\n */\n public static Gson getStrategiesGson() {\n return STRATEGIES_GSON;\n }\n\n\n /**\n * @return 属性排除策略\n */\n private static List<ExclusionStrategy> getExclusionStrategies() {\n ArrayList<ExclusionStrategy> exclusionStrategies = new ArrayList<>();\n exclusionStrategies.add(new ExclusionStrategy() {\n\n @Override\n public boolean shouldSkipField(FieldAttributes f) {\n if (!cache.containsKey(f)) {\n Ignore annotation = f.getAnnotation(Ignore.class);\n cache.put(f, annotation != null);\n }\n return cache.get(f);\n }\n\n @Override\n public boolean shouldSkipClass(Class<?> clazz) {\n return false;\n }\n });\n return exclusionStrategies;\n }\n\n\n}"
},
{
"identifier": "JWTUtils",
"path": "hubbo-utils/src/main/java/cn/hubbo/utils/common/security/JWTUtils.java",
"snippet": "@Deprecated\npublic final class JWTUtils {\n\n private static final Algorithm ALGORITHM = Algorithm.HMAC256(\"123456\");\n\n private static final String ISSUER_INFO = \"https://hubbo.cn\";\n\n private static final Map<String, Object> HEADER = new HashMap<>();\n\n static {\n HEADER.put(\"alg\", \"HS256\");\n HEADER.put(\"typ\", \"JWT\");\n }\n\n /**\n * @param id 唯一ID,后期token续期可能会用到\n * @param claimInfo payLoad载荷信息\n * @return token\n */\n public static String generateToken(String id, String username) {\n Calendar calendar = Calendar.getInstance();\n calendar.add(Calendar.DAY_OF_MONTH, 1);\n return JWT.create()\n .withIssuer(ISSUER_INFO)\n .withJWTId(id)\n .withSubject(\"哈勃\")\n .withClaim(\"info\", username)\n .withIssuedAt(new Date())\n .withExpiresAt(calendar.toInstant())\n .withHeader(HEADER)\n .sign(ALGORITHM);\n }\n\n\n /**\n * @param token token信息\n * @param cla 期望的目标Class\n * @param <T> 期望的类型\n * @return 将token中的信息解析成对象\n */\n @SuppressWarnings({\"all\"})\n public static <T> T verifyToken(String token, Class cla) {\n try {\n DecodedJWT decodedJWT = JWT.require(ALGORITHM).build().verify(token);\n String payload = decodedJWT.getPayload();\n //return (T) JsonUtils.getDefaultGson().fromJson(\"\", cla);\n String info = String.valueOf(decodedJWT.getClaim(\"info\"));\n if (info.contains(\"\\\"\")) {\n info = info.replaceAll(\"\\\"\", \"\");\n }\n return (T) info;\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n\n }\n\n\n}"
}
] | import cn.hubbo.domain.dos.User;
import cn.hubbo.utils.common.base.JsonUtils;
import cn.hubbo.utils.common.security.JWTUtils;
import org.junit.jupiter.api.Test;
import java.util.UUID; | 2,006 | package cn.hubbo.unit;
/**
* @author 张晓华
* @version V1.0
* @Package cn.hubbo.unit
* @date 2023/10/18 22:05
* @Copyright © 2016-2017 版权所有,未经授权均为剽窃,作者保留一切权利
*/
public class UtilsUnitTest {
@Test
public void testGenerateToken() { | package cn.hubbo.unit;
/**
* @author 张晓华
* @version V1.0
* @Package cn.hubbo.unit
* @date 2023/10/18 22:05
* @Copyright © 2016-2017 版权所有,未经授权均为剽窃,作者保留一切权利
*/
public class UtilsUnitTest {
@Test
public void testGenerateToken() { | User user = new User().setUsername("user1"); | 0 | 2023-10-18 09:38:29+00:00 | 4k |
Xernas78/menu-lib | src/main/java/dev/xernas/menulib/utils/ItemBuilder.java | [
{
"identifier": "Menu",
"path": "src/main/java/dev/xernas/menulib/Menu.java",
"snippet": "public abstract class Menu implements InventoryHolder {\n\n private final Player owner;\n\n public Menu(Player owner) {\n this.owner = owner;\n }\n\n @NotNull\n public abstract String getName();\n @NotNull\n public abstract InventorySize getInventorySize();\n\n public String getPermission() {\n return null;\n }\n public String getNoPermissionMessage() {\n return \"\";\n }\n\n public abstract void onInventoryClick(InventoryClickEvent e);\n\n @NotNull\n public abstract Map<Integer, ItemStack> getContent();\n\n public final void open() {\n if (getPermission() != null && !getPermission().isEmpty()) {\n if (!owner.hasPermission(getPermission())) {\n owner.sendMessage(getNoPermissionMessage());\n return;\n }\n }\n Inventory inventory = getInventory();\n getContent().forEach(inventory::setItem);\n owner.openInventory(inventory);\n }\n\n public final Map<Integer, ItemStack> fill(Material material) {\n Map<Integer, ItemStack> map = new HashMap<>();\n for (int i = 0; i < getInventorySize().getSize(); i++) {\n ItemStack filler = ItemUtils.createItem(\" \", material);\n map.put(i, filler);\n }\n return map;\n }\n\n public final boolean isItem(ItemStack item, String itemId) {\n PersistentDataContainer dataContainer = Objects.requireNonNull(item.getItemMeta()).getPersistentDataContainer();\n if (dataContainer.has(MenuLib.getItemIdKey(), PersistentDataType.STRING)) {\n return Objects.equals(dataContainer.get(MenuLib.getItemIdKey(), PersistentDataType.STRING), itemId);\n }\n return false;\n }\n\n public final void back() {\n Menu lastMenu = MenuLib.getLastMenu(owner);\n lastMenu.open();\n }\n\n @NotNull\n @Override\n public final Inventory getInventory() {\n return Bukkit.createInventory(this, getInventorySize().getSize(), getName());\n }\n\n public final Player getOwner() {\n return owner;\n }\n}"
},
{
"identifier": "MenuLib",
"path": "src/main/java/dev/xernas/menulib/MenuLib.java",
"snippet": "public final class MenuLib implements Listener {\n\n private static NamespacedKey itemIdKey;\n private static final Map<Player, Menu> lastMenu = new HashMap<>();\n private static final Map<Menu, Map<ItemStack, Consumer<InventoryClickEvent>>> itemClickEvents = new HashMap<>();\n\n private MenuLib(JavaPlugin plugin) {\n Bukkit.getPluginManager().registerEvents(this, plugin);\n itemIdKey = new NamespacedKey(plugin, \"itemId\");\n }\n\n public static void init(JavaPlugin plugin) {\n new MenuLib(plugin);\n }\n\n @EventHandler\n public void onInventoryClick(InventoryClickEvent e) {\n if (e.getInventory().getHolder() instanceof Menu menu) {\n e.setCancelled(true);\n if (e.getCurrentItem() == null) {\n return;\n }\n\n menu.onInventoryClick(e);\n\n try {\n itemClickEvents.forEach((menu1, itemStackConsumerMap) -> {\n if (menu1.equals(menu)) {\n itemStackConsumerMap.forEach((itemStack, inventoryClickEventConsumer) -> {\n if (itemStack.equals(e.getCurrentItem())) {\n inventoryClickEventConsumer.accept(e);\n }\n });\n }\n });\n } catch (Exception ignore) {\n\n }\n }\n }\n\n public static void setItemClickEvent(Menu menu, ItemStack itemStack, Consumer<InventoryClickEvent> e) {\n Map<ItemStack, Consumer<InventoryClickEvent>> itemEvents = itemClickEvents.get(menu);\n if (itemEvents == null) {\n itemEvents = new HashMap<>();\n }\n itemEvents.put(itemStack, e);\n itemClickEvents.put(menu, itemEvents);\n }\n\n public static NamespacedKey getItemIdKey() {\n return itemIdKey;\n }\n\n public static void setLastMenu(Player player, Menu menu) {\n lastMenu.put(player, menu);\n }\n\n public static Menu getLastMenu(Player player) {\n return lastMenu.get(player);\n }\n}"
},
{
"identifier": "PaginatedMenu",
"path": "src/main/java/dev/xernas/menulib/PaginatedMenu.java",
"snippet": "public abstract class PaginatedMenu extends Menu {\n private int page = 0;\n private int numberOfPages;\n\n public PaginatedMenu(Player owner) {\n super(owner);\n }\n\n @Nullable\n public abstract Material getBorderMaterial();\n\n @NotNull\n public abstract List<Integer> getStaticSlots();\n\n @NotNull\n public abstract List<ItemStack> getItems();\n\n public abstract Map<Integer, ItemStack> getButtons();\n\n @Override\n @NotNull\n public final Map<Integer, ItemStack> getContent() {\n Map<Integer, ItemStack> map = new HashMap<>();\n for (Integer staticSlot : getStaticSlots()) {\n map.put(staticSlot, ItemUtils.createItem(\" \", getBorderMaterial() == null ? Material.AIR : getBorderMaterial()));\n }\n List<Integer> staticSlots = removeRecurringIntegers(getStaticSlots());\n int maxItems = getInventorySize().getSize() - staticSlots.size();\n numberOfPages = (int) Math.ceil((double) getItems().size() / maxItems) - 1;\n\n // Pagination\n int index = 0;\n for (int i = 0; i < getInventory().getSize(); i++) {\n if (!staticSlots.contains(i)) {\n if (index + maxItems * page < getItems().size()) {\n map.put(i, getItems().get(index + maxItems * page));\n index++;\n }\n }\n }\n // Pagination\n\n if (getButtons() != null) {\n getButtons().forEach((integer, itemStack) -> {\n if (staticSlots.contains(integer)) {\n map.put(integer, itemStack);\n }\n });\n }\n return map;\n }\n\n @Override\n public final @NotNull InventorySize getInventorySize() {\n return InventorySize.LARGEST;\n }\n public final void setPage(int page) {\n this.page = page;\n }\n public final int getPage() {\n return page;\n }\n\n public final boolean isLastPage() {\n return page == numberOfPages;\n }\n}"
}
] | import dev.xernas.menulib.Menu;
import dev.xernas.menulib.MenuLib;
import dev.xernas.menulib.PaginatedMenu;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.inventory.ItemFlag;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.persistence.PersistentDataContainer;
import org.bukkit.persistence.PersistentDataType;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer; | 1,846 | package dev.xernas.menulib.utils;
public class ItemBuilder extends ItemStack {
private final Menu itemMenu;
private ItemMeta meta;
public ItemBuilder(Menu itemMenu, Material material) {
this(itemMenu, material, null);
}
public ItemBuilder(Menu itemMenu, ItemStack item) {
this(itemMenu, item, null);
}
public ItemBuilder(Menu itemMenu, Material material, Consumer<ItemMeta> itemMeta) {
this(itemMenu, new ItemStack(material), itemMeta);
}
public ItemBuilder(Menu itemMenu, ItemStack item, Consumer<ItemMeta> itemMeta) {
super(item);
this.itemMenu = itemMenu;
meta = getItemMeta();
if (itemMeta != null) {
itemMeta.accept(meta);
}
setItemMeta(meta);
}
public ItemBuilder setItemId(String itemId) {
PersistentDataContainer dataContainer = meta.getPersistentDataContainer(); | package dev.xernas.menulib.utils;
public class ItemBuilder extends ItemStack {
private final Menu itemMenu;
private ItemMeta meta;
public ItemBuilder(Menu itemMenu, Material material) {
this(itemMenu, material, null);
}
public ItemBuilder(Menu itemMenu, ItemStack item) {
this(itemMenu, item, null);
}
public ItemBuilder(Menu itemMenu, Material material, Consumer<ItemMeta> itemMeta) {
this(itemMenu, new ItemStack(material), itemMeta);
}
public ItemBuilder(Menu itemMenu, ItemStack item, Consumer<ItemMeta> itemMeta) {
super(item);
this.itemMenu = itemMenu;
meta = getItemMeta();
if (itemMeta != null) {
itemMeta.accept(meta);
}
setItemMeta(meta);
}
public ItemBuilder setItemId(String itemId) {
PersistentDataContainer dataContainer = meta.getPersistentDataContainer(); | dataContainer.set(MenuLib.getItemIdKey(), PersistentDataType.STRING, itemId.toLowerCase()); | 1 | 2023-10-23 16:02:26+00:00 | 4k |
samdsk/lab-sweng | e03-2023giu/src/main/java/it/unimi/di/sweng/esame/Main.java | [
{
"identifier": "ObservableModel",
"path": "e01-2023gen/src/main/java/it/unimi/di/sweng/esame/model/ObservableModel.java",
"snippet": "public class ObservableModel extends Model implements Observable<List<Partenza>> {\n\tprivate final List<Observer<List<Partenza>>> observers = new ArrayList<>();\n\n\tpublic ObservableModel() {\n\t\tsuper();\n\t}\n\n\t@Override\n\tpublic void addObserver(@NotNull Observer<@NotNull List<Partenza>> observer) {\n\t\tobservers.add(observer);\n\t}\n\n\t@Override\n\tpublic void removeObserver(@NotNull Observer<@NotNull List<Partenza>> observer) {\n\t\tobservers.remove(observer);\n\t}\n\t@Override\n\tpublic void removeTrain(@NotNull Treno treno) {\n\t\tsuper.removeTrain(treno);\n\t\tnotifyObservers();\n\t}\n\t@Override\n\tpublic @NotNull List<Partenza> getState() {\n\t\treturn new ArrayList<>(partenze.values());\n\t}\n\n\t@Override\n\tpublic void notifyObservers() {\n\t\tfor (Observer<List<Partenza>> o : observers) {\n\t\t\to.update(this,getState());\n\t\t}\n\t}\n\n\t@Override\n\tpublic void setDelay(@NotNull Treno treno, int delay) {\n\t\tsuper.setDelay(treno, delay);\n\t\tnotifyObservers();\n\t}\n}"
},
{
"identifier": "InputPresenter",
"path": "e02-2023feb/src/main/java/it/unimi/di/sweng/esame/presenters/InputPresenter.java",
"snippet": "public class InputPresenter implements Presenter {\n\tprivate final Model model;\n\tprivate final NextNationView view;\n\n\tprivate final List<String> countries;\n\n\tpublic InputPresenter(@NotNull Model model, @NotNull NextNationView view) {\n\t\tthis.model = model;\n\t\tthis.view = view;\n\n\t\tview.addHandlers(this);\n\n\t\tcountries = model.getCountries();\n\t\tcountries.sort(String::compareTo);\n\n\t\tsetCountryNextName(\"\");\n\t}\n\n\t@Override\n\tpublic void action(String country, String voteString) {\n\t\ttry {\n\t\t\tString[] votes = voteString.split(\" \");\n\n\t\t\tif(votes.length != 5)\n\t\t\t\tthrow new IllegalArgumentException(\"Invalid number of votes\");\n\n\t\t\tString votingCountryCode = model.getCodeFromCountryName(country);\n\n\t\t\tif(voteString.contains(votingCountryCode))\n\t\t\t\tthrow new IllegalArgumentException(\"You cannot vote for yourself\");\n\n\t\t\tfindDuplicates(votes);\n\t\t\tcheckForInvalidCodes(votes);\n\n\t\t\tint size = votes.length;\n\n\t\t\tfor (int i = 0; i < votes.length; i++) {\n\t\t\t\tmodel.vote(votes[i], size - i);\n\t\t\t}\n\n\t\t\tview.showSuccess();\n\t\t}catch (IllegalArgumentException e){\n\t\t\tview.showError(e.getMessage());\n\t\t\treturn;\n\t\t}\n\n\n\t\tsetCountryNextName(country);\n\n\t}\n\n\tprivate void checkForInvalidCodes(String[] codes){\n\t\tfor (String code : codes) {\n\t\t\tif(!model.containsCanzone(code))\n\t\t\t\tthrow new IllegalArgumentException(\"Invalid vote code: \"+code);\n\t\t}\n\t}\n\n\tprivate static void findDuplicates(String[] votes)\n\t\t\tthrows IllegalArgumentException {\n\t\tMap<String,Integer> countVotes = new HashMap<>();\n\n\t\tfor (String vote : votes) {\n\t\t\tcountVotes.put(vote,countVotes.getOrDefault(vote,0)+1);\n\t\t}\n\n\t\tfor (Integer value : countVotes.values()) {\n\t\t\tif(value>1)\n\t\t\t\tthrow new IllegalArgumentException(\"Duplicated votes\");\n\t\t}\n\t}\n\n\tpublic void setCountryNextName(@NotNull String currentCountry){\n\t\tif(currentCountry.length()<1){\n\t\t\tview.setName(countries.get(0));\n\t\t\treturn;\n\t\t}\n\n\t\tint index = countries.indexOf(currentCountry);\n\n\t\tif(index<countries.size() - 1){\n\t\t\tview.setName(countries.get(index+1));\n\t\t}else{\n\t\t\tview.setName(\"END OF VOTES\");\n\t\t}\n\t}\n\n}"
},
{
"identifier": "SegnalazioniAperte",
"path": "e03-2023giu/src/main/java/it/unimi/di/sweng/esame/presenters/SegnalazioniAperte.java",
"snippet": "public class SegnalazioniAperte extends DisplayPresenter {\n\tprivate final ObservableModel model;\n\tprivate final DisplayView view;\n\n\tpublic SegnalazioniAperte(@NotNull ObservableModel model, @NotNull DisplayView view) {\n\t\tsuper();\n\t\tthis.model = model;\n\t\tthis.view = view;\n\n\t\tmodel.addObserver(this);\n\t}\n\n\t@Override\n\tpublic void update(@NotNull Observable<List<Segnalazione>> observable, @NotNull List<Segnalazione> state) {\n\t\tIterator<Segnalazione> it = state.iterator();\n\t\tint counter = 0;\n\t\twhile(it.hasNext() && counter<Main.PANEL_SIZE){\n\t\t\tSegnalazione s = it.next();\n\t\t\tif(!s.isRisolto()){\n\t\t\t\tview.set(counter++,s.formatDisplay());\n\t\t\t}\n\t\t}\n\n\t\tfor(int i = counter;i<Main.PANEL_SIZE;i++){\n\t\t\tview.set(i,\"\");\n\t\t}\n\t}\n}"
},
{
"identifier": "SegnalazioniRisolte",
"path": "e03-2023giu/src/main/java/it/unimi/di/sweng/esame/presenters/SegnalazioniRisolte.java",
"snippet": "public class SegnalazioniRisolte extends DisplayPresenter {\n\tprivate final ObservableModel model;\n\tprivate final DisplayView view;\n\n\tpublic SegnalazioniRisolte(@NotNull ObservableModel model, @NotNull DisplayView view) {\n\t\tsuper();\n\t\tthis.model = model;\n\t\tthis.view = view;\n\n\t\tmodel.addObserver(this);\n\t}\n\n\t@Override\n\tpublic void update(@NotNull Observable<List<Segnalazione>> observable, @NotNull List<Segnalazione> state) {\n\t\tIterator<Segnalazione> it = state.iterator();\n\t\tint counter = 0;\n\t\twhile(it.hasNext() && counter< Main.PANEL_SIZE){\n\t\t\tSegnalazione s = it.next();\n\t\t\tif(s.isRisolto()){\n\t\t\t\tview.set(counter++,s.formatDisplay());\n\t\t\t}\n\t\t}\n\n\t\tfor (int i = counter; i < Main.PANEL_SIZE; i++) {\n\t\t\tview.set(i,\"\");\n\t\t}\n\t}\n}"
},
{
"identifier": "CentralStationView",
"path": "e03-2023giu/src/main/java/it/unimi/di/sweng/esame/views/CentralStationView.java",
"snippet": "public class CentralStationView extends Region {\n @NotNull private final TextField textField;\n @NotNull private final Label error;\n @NotNull private final Button button;\n @NotNull private final Button button2;\n\n public CentralStationView() {\n button = new Button(\"Segnala\");\n button2 = new Button(\"Risolto\");\n textField = new TextField();\n error = new Label(\"\");\n textField.setFont(Font.font(\"sans\", 20));\n button.setFont(Font.font(\"sans\", 20));\n button2.setFont(Font.font(\"sans\", 20));\n setBackground(new Background(\n new BackgroundFill(Color.LIGHTGRAY, new CornerRadii(5.0), Insets.EMPTY)));\n setBorder(new Border(\n new BorderStroke(null, BorderStrokeStyle.SOLID, new CornerRadii(5.0), new BorderWidths(2))));\n\n GridPane grid = new GridPane();\n grid.setPadding(new Insets(10, 10, 10, 10));\n\n grid.add(textField, 0, 0);\n grid.add(button, 1, 0);\n grid.add(button2, 2, 0);\n grid.add(error, 0, 1, 3, 1);\n\n this.getChildren().add(grid);\n }\n\n public void addHandlers(@NotNull Presenter presenter) {\n button.setOnAction(eh -> presenter.action(button.getText(), textField.getText()));\n button2.setOnAction(eh -> presenter.action(button2.getText(), textField.getText()));\n }\n\n\n public void showError(@NotNull String s) {\n error.setText(s);\n setBackground(new Background(\n new BackgroundFill(Color.YELLOW, new CornerRadii(5.0), Insets.EMPTY)));\n }\n\n\n public void showSuccess() {\n error.setText(\"\");\n setBackground(new Background(\n new BackgroundFill(Color.LIGHTGRAY, new CornerRadii(5.0), Insets.EMPTY)));\n }\n}"
},
{
"identifier": "DisplayView",
"path": "e02-2023feb/src/main/java/it/unimi/di/sweng/esame/views/DisplayView.java",
"snippet": "public class DisplayView extends Region {\n @NotNull\n private final Label[] rows;\n\n public DisplayView(@NotNull String title, int rows) {\n this.rows = new Label[rows];\n setBackground(new Background(\n new BackgroundFill(Color.LIGHTBLUE, new CornerRadii(5.0), Insets.EMPTY)));\n setBorder(new Border(\n new BorderStroke(null, BorderStrokeStyle.SOLID, new CornerRadii(5.0), new BorderWidths(2))));\n\n GridPane grid = new GridPane();\n grid.setPadding(new Insets(10, 10, 10, 10));\n Label title1 = new Label(title);\n title1.setFont(Font.font(\"sans\", 20));\n grid.add(title1, 0, 0);\n for (int i = 0; i < rows; i++) {\n this.rows[i] = new Label(String.format(\"%-35s\",\"Row #\" + i));\n this.rows[i].setPadding(new Insets(10, 10, 10, 10));\n this.rows[i].setFont(Font.font(\"monospace\", 14));\n grid.add(this.rows[i], 0, i + 1);\n }\n this.getChildren().add(grid);\n }\n\n public void set(int i, @NotNull String s) {\n rows[i].setText(s);\n }\n\n public int size() {\n return rows.length;\n }\n\n\n}"
}
] | import it.unimi.di.sweng.esame.model.ObservableModel;
import it.unimi.di.sweng.esame.presenters.InputPresenter;
import it.unimi.di.sweng.esame.presenters.SegnalazioniAperte;
import it.unimi.di.sweng.esame.presenters.SegnalazioniRisolte;
import it.unimi.di.sweng.esame.views.CentralStationView;
import it.unimi.di.sweng.esame.views.DisplayView;
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.layout.Background;
import javafx.scene.layout.BackgroundFill;
import javafx.scene.layout.CornerRadii;
import javafx.scene.layout.GridPane;
import javafx.scene.paint.Color;
import javafx.stage.Stage; | 2,724 | package it.unimi.di.sweng.esame;
public class Main extends Application {
final public static int PANEL_SIZE = 8;
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) {
primaryStage.setTitle("Autostrade");
CentralStationView stationView = new CentralStationView();
DisplayView leftSideView = new DisplayView("Segnalazioni Attive", PANEL_SIZE);
DisplayView rightSideView = new DisplayView("Segnalazioni Chiuse", PANEL_SIZE);
GridPane gridPane = new GridPane();
gridPane.setBackground(new Background(new BackgroundFill(Color.DARKOLIVEGREEN, CornerRadii.EMPTY, Insets.EMPTY)));
gridPane.setPadding(new Insets(10, 10, 10, 10));
gridPane.add(stationView, 0, 0);
GridPane.setColumnSpan(stationView, GridPane.REMAINING);
gridPane.add(leftSideView, 0, 1);
gridPane.add(rightSideView, 1, 1);
//TODO creare presenters e connettere model e view
ObservableModel model = new ObservableModel();
new SegnalazioniAperte(model,leftSideView); | package it.unimi.di.sweng.esame;
public class Main extends Application {
final public static int PANEL_SIZE = 8;
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) {
primaryStage.setTitle("Autostrade");
CentralStationView stationView = new CentralStationView();
DisplayView leftSideView = new DisplayView("Segnalazioni Attive", PANEL_SIZE);
DisplayView rightSideView = new DisplayView("Segnalazioni Chiuse", PANEL_SIZE);
GridPane gridPane = new GridPane();
gridPane.setBackground(new Background(new BackgroundFill(Color.DARKOLIVEGREEN, CornerRadii.EMPTY, Insets.EMPTY)));
gridPane.setPadding(new Insets(10, 10, 10, 10));
gridPane.add(stationView, 0, 0);
GridPane.setColumnSpan(stationView, GridPane.REMAINING);
gridPane.add(leftSideView, 0, 1);
gridPane.add(rightSideView, 1, 1);
//TODO creare presenters e connettere model e view
ObservableModel model = new ObservableModel();
new SegnalazioniAperte(model,leftSideView); | new SegnalazioniRisolte(model,rightSideView); | 3 | 2023-10-19 06:28:13+00:00 | 4k |
RoessinghResearch/senseeact | ExampleSenSeeActClient/src/main/java/nl/rrd/senseeact/exampleclient/project/ExampleProjectRepository.java | [
{
"identifier": "BaseProject",
"path": "SenSeeActClient/src/main/java/nl/rrd/senseeact/client/project/BaseProject.java",
"snippet": "public abstract class BaseProject {\n\tprivate final String code;\n\tprivate final String name;\n\n\t/**\n\t * Constructs a new project.\n\t * \n\t * @param code the project code\n\t * @param name the default name (this is used if no locale-dependent name\n\t * is defined)\n\t */\n\tpublic BaseProject(String code, String name) {\n\t\tthis.code = code;\n\t\tthis.name = name;\n\t}\n\n\t/**\n\t * Returns the project code.\n\t * \n\t * @return the project code\n\t */\n\tpublic String getCode() {\n\t\treturn code;\n\t}\n\t\n\t/**\n\t * Returns the project name to present to the user.\n\t * \n\t * @return the project name to present to the user\n\t */\n\tpublic String getName() {\n\t\treturn name;\n\t}\n\t\n\t/**\n\t * If this project supports logins by username (only the local part of an\n\t * email address), then this method should return the domain. For example\n\t * if this method returns \"myproject.example.com\", then user\n\t * [email protected] can log in with myprojectuser01.\n\t * The default implementation returns null.\n\t * \n\t * @return the username domain or null\n\t */\n\tpublic String getUsernameDomain() {\n\t\treturn null;\n\t}\n\n\t/**\n\t * Finds the table with the specified name and returns the table definition.\n\t * If the table doesn't exist, this method returns null.\n\t * \n\t * @param name the table name\n\t * @return the table definition or null\n\t */\n\tpublic DatabaseTableDef<?> findTable(String name) {\n\t\tList<DatabaseTableDef<?>> tables = getDatabaseTables();\n\t\tif (tables == null)\n\t\t\treturn null;\n\t\tfor (DatabaseTableDef<?> table : tables) {\n\t\t\tif (table.getName().equals(name))\n\t\t\t\treturn table;\n\t\t}\n\t\treturn null;\n\t}\n\n\t/**\n\t * Returns the sensors that are used in this project.\n\t *\n\t * @return the sensors (can be empty or null)\n\t */\n\tpublic abstract List<BaseSensor> getSensors();\n\t\n\t/**\n\t * Tries to find the sensor details for the specified product. If this\n\t * project does not support the product, then this method returns null.\n\t * \n\t * @param product the sensor product ID. For example \"FITBIT\".\n\t * @return the sensor or null\n\t */\n\tpublic BaseSensor findSensor(String product) {\n\t\tfor (BaseSensor sensor : getSensors()) {\n\t\t\tif (sensor.getProduct().equals(product))\n\t\t\t\treturn sensor;\n\t\t}\n\t\treturn null;\n\t}\n\n\t/**\n\t * Returns the sensors that are used in this project for the specified\n\t * user. By default it returns the same list as {@link #getSensors()\n\t * getSensors()}. This method may remove sensors if the user has simulated\n\t * data for example.\n\t *\n\t * @param user the user\n\t * @return the sensors (can be empty or null)\n\t */\n\tpublic List<BaseSensor> getUserSensors(String user) {\n\t\treturn getSensors();\n\t}\n\n\t/**\n\t * Returns the database tables. An implementation of this method can call\n\t * {@link #getSensorDatabaseTables() getSensorDatabaseTables()} and then add\n\t * any additional tables for this project.\n\t * \n\t * @return the database tables (can be empty or null)\n\t */\n\tpublic abstract List<DatabaseTableDef<?>> getDatabaseTables();\n\t\n\t/**\n\t * Returns the tables that are needed for the sensors returned by\n\t * {@link #getSensors() getSensors()}. This can be useful for the\n\t * implementation of {@link #getDatabaseTables() getDatabaseTables()}.\n\t * \n\t * @return the sensor database tables\n\t */\n\tprotected List<DatabaseTableDef<?>> getSensorDatabaseTables() {\n\t\tList<DatabaseTableDef<?>> tables = new ArrayList<>();\n\t\tList<String> tableNames = new ArrayList<>();\n\t\tfor (BaseSensor product : getSensors()) {\n\t\t\tfor (DatabaseTableDef<?> table : product.getTables()) {\n\t\t\t\tif (!tableNames.contains(table.getName())) {\n\t\t\t\t\ttables.add(table);\n\t\t\t\t\ttableNames.add(table.getName());\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn tables;\n\t}\n\n\t/**\n\t * Returns the names of the tables.\n\t *\n\t * @return the names of the tables (can be empty)\n\t */\n\tpublic List<String> getDatabaseTableNames() {\n\t\tList<String> result = new ArrayList<>();\n\t\tList<? extends DatabaseTableDef<?>> tables = getDatabaseTables();\n\t\tif (tables == null)\n\t\t\treturn result;\n\t\tfor (DatabaseTableDef<?> table : tables) {\n\t\t\tresult.add(table.getName());\n\t\t}\n\t\treturn result;\n\t}\n\n\t/**\n\t * Returns a map with all data modules supported by this project. Each value\n\t * is a list of database tables that belong to the module. This can be used\n\t * for access control by module.\n\t *\n\t * @return the modules\n\t */\n\tpublic Map<String,List<DatabaseTableDef<?>>> getModuleTables() {\n\t\treturn new LinkedHashMap<>();\n\t}\n\n\t/**\n\t * Finds the names of the modules that contain the specified table.\n\t *\n\t * @param table the table name\n\t * @return the module names\n\t */\n\tpublic Set<String> findModulesForTable(String table) {\n\t\tSet<String> modules = new HashSet<>();\n\t\tMap<String,List<DatabaseTableDef<?>>> moduleTables = getModuleTables();\n\t\tfor (String module : moduleTables.keySet()) {\n\t\t\tList<DatabaseTableDef<?>> tables = moduleTables.get(module);\n\t\t\tfor (DatabaseTableDef<?> moduleTable : tables) {\n\t\t\t\tif (moduleTable.getName().equals(table)) {\n\t\t\t\t\tmodules.add(module);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn modules;\n\t}\n}"
},
{
"identifier": "ProjectRepository",
"path": "SenSeeActClient/src/main/java/nl/rrd/senseeact/client/project/ProjectRepository.java",
"snippet": "@AppComponent\npublic abstract class ProjectRepository {\n\tprivate final Object lock = new Object();\n\tprivate List<BaseProject> projects = null;\n\n\t/**\n\t * Returns all projects. Note that a user may not be allowed to access\n\t * every project on the server. See also {@link\n\t * SenSeeActClient#getProjectList() getProjectList()}.\n\t * \n\t * @return the projects\n\t */\n\tpublic List<BaseProject> getProjects() {\n\t\tsynchronized (lock) {\n\t\t\tif (projects != null)\n\t\t\t\treturn projects;\n\t\t\tprojects = createProjects();\n\t\t\treturn projects;\n\t\t}\n\t}\n\n\tprotected abstract List<BaseProject> createProjects();\n\n\t/**\n\t * Finds the project with the specified code. If no such project exists,\n\t * this method returns null. Note that a user may not be allowed to access\n\t * the project on the server. See also {@link\n\t * SenSeeActClient#getProjectList() RRDSenSeeActClient.getProjectList()}.\n\t * \n\t * @param code the project code\n\t * @return the project or null\n\t */\n\tpublic BaseProject findProjectByCode(String code) {\n\t\tList<BaseProject> projects = getProjects();\n\t\tfor (BaseProject project : projects) {\n\t\t\tif (project.getCode().equals(code))\n\t\t\t\treturn project;\n\t\t}\n\t\treturn null;\n\t}\n}"
},
{
"identifier": "DefaultProject",
"path": "ExampleSenSeeActClient/src/main/java/nl/rrd/senseeact/exampleclient/project/defaultproject/DefaultProject.java",
"snippet": "public class DefaultProject extends BaseProject {\n\tpublic DefaultProject() {\n\t\tsuper(\"default\", \"Default\");\n\t}\n\n\t@Override\n\tpublic List<BaseSensor> getSensors() {\n\t\tList<BaseSensor> sensors = new ArrayList<>();\n\t\tsensors.add(new ExampleStepCounterSensor());\n\t\treturn sensors;\n\t}\n\n\t@Override\n\tpublic List<DatabaseTableDef<?>> getDatabaseTables() {\n\t\tList<DatabaseTableDef<?>> result = new ArrayList<>();\n\t\tresult.addAll(getSensorDatabaseTables());\n\t\tresult.add(new QuestionnaireDataTable());\n\t\tresult.add(new LinkedSensorTable());\n\t\tresult.add(new AppNotificationTable());\n\t\treturn result;\n\t}\n}"
}
] | import nl.rrd.senseeact.client.project.BaseProject;
import nl.rrd.senseeact.client.project.ProjectRepository;
import nl.rrd.senseeact.exampleclient.project.defaultproject.DefaultProject;
import java.util.List; | 2,117 | package nl.rrd.senseeact.exampleclient.project;
public class ExampleProjectRepository extends ProjectRepository {
@Override | package nl.rrd.senseeact.exampleclient.project;
public class ExampleProjectRepository extends ProjectRepository {
@Override | protected List<BaseProject> createProjects() { | 0 | 2023-10-24 09:36:50+00:00 | 4k |
Spectrum3847/SpectrumTraining | src/main/java/frc/spectrumLib/swerve/SimDrivetrain.java | [
{
"identifier": "ModuleConfig",
"path": "src/main/java/frc/spectrumLib/swerve/config/ModuleConfig.java",
"snippet": "public class ModuleConfig {\n public enum SwerveModuleSteerFeedbackType {\n RemoteCANcoder,\n FusedCANcoder,\n SyncCANcoder,\n }\n\n /** CAN ID of the drive motor */\n public int DriveMotorId = 0;\n /** CAN ID of the steer motor */\n public int SteerMotorId = 0;\n /** CAN ID of the CANcoder used for azimuth or RIO AnalogInput ID of the Analog Sensor used */\n public int AngleEncoderId = 0;\n /** Offset of the CANcoder in degrees */\n public double CANcoderOffset = 0;\n /** Gear ratio between drive motor and wheel */\n public double DriveMotorGearRatio = 0;\n /** Gear ratio between steer motor and CANcoder An example ratio for the SDS Mk4: 12.8 */\n public double SteerMotorGearRatio = 0;\n /** Coupled gear ratio between the CANcoder and the drive motor */\n public double CouplingGearRatio = 0;\n /** Wheel radius of the driving wheel in inches */\n public double WheelRadius = 0;\n /**\n * The location of this module's wheels relative to the physical center of the robot in meters\n * along the X axis of the robot\n */\n public double LocationX = 0;\n /**\n * The location of this module's wheels relative to the physical center of the robot in meters\n * along the Y axis of the robot\n */\n public double LocationY = 0;\n\n /** The steer motor gains */\n public Slot0Configs SteerMotorGains = new Slot0Configs();\n /** The drive motor gains */\n public Slot0Configs DriveMotorGains = new Slot0Configs();\n\n /** The maximum amount of current the drive motors can apply without slippage */\n public double SlipCurrent = 400;\n\n /** True if the steering motor is reversed from the CANcoder */\n public boolean SteerMotorInverted = false;\n /** True if the driving motor is reversed */\n public boolean DriveMotorInverted = false;\n\n /** Sim-specific constants * */\n /** Azimuthal inertia in kilogram meters squared */\n public double SteerInertia = 0.001;\n /** Drive inertia in kilogram meters squared */\n public double DriveInertia = 0.001;\n\n /**\n * When using open-loop drive control, this specifies the speed the robot travels at when driven\n * with 12 volts in meters per second. This is used to approximate the output for a desired\n * velocity. If using closed loop control, this value is ignored\n */\n public double SpeedAt12VoltsMps = 0;\n\n /**\n * Choose how the feedback sensors should be configured\n *\n * <p>If the robot does not support Pro, then this should remain as RemoteCANcoder. Otherwise,\n * users have the option to use either FusedCANcoder or SyncCANcoder depending on if there is\n * risk that the CANcoder can fail in a way to provide \"good\" data.\n */\n public SwerveModuleSteerFeedbackType FeedbackSource =\n SwerveModuleSteerFeedbackType.RemoteCANcoder;\n\n public double MotionMagicAcceleration = 100.0;\n public double MotionMagicCruiseVelocity = 10;\n\n public ModuleConfig withDriveMotorId(int id) {\n this.DriveMotorId = id;\n return this;\n }\n\n public ModuleConfig withSteerMotorId(int id) {\n this.SteerMotorId = id;\n return this;\n }\n\n public ModuleConfig withCANcoderId(int id) {\n this.AngleEncoderId = id;\n return this;\n }\n\n public ModuleConfig withCANcoderOffset(double offset) {\n this.CANcoderOffset = offset;\n return this;\n }\n\n public ModuleConfig withDriveMotorGearRatio(double ratio) {\n this.DriveMotorGearRatio = ratio;\n return this;\n }\n\n public ModuleConfig withSteerMotorGearRatio(double ratio) {\n this.SteerMotorGearRatio = ratio;\n return this;\n }\n\n public ModuleConfig withCouplingGearRatio(double ratio) {\n this.CouplingGearRatio = ratio;\n return this;\n }\n\n public ModuleConfig withWheelRadius(double radius) {\n this.WheelRadius = radius;\n return this;\n }\n\n public ModuleConfig withLocationX(double locationXMeters) {\n this.LocationX = locationXMeters;\n return this;\n }\n\n public ModuleConfig withLocationY(double locationYMeters) {\n this.LocationY = locationYMeters;\n return this;\n }\n\n public ModuleConfig withSteerMotorGains(Slot0Configs gains) {\n this.SteerMotorGains = gains;\n return this;\n }\n\n public ModuleConfig withDriveMotorGains(Slot0Configs gains) {\n this.DriveMotorGains = gains;\n return this;\n }\n\n public ModuleConfig withSlipCurrent(double slipCurrent) {\n this.SlipCurrent = slipCurrent;\n return this;\n }\n\n public ModuleConfig withSteerMotorInverted(boolean SteerMotorInverted) {\n this.SteerMotorInverted = SteerMotorInverted;\n return this;\n }\n\n public ModuleConfig withDriveMotorInverted(boolean DriveMotorInverted) {\n this.DriveMotorInverted = DriveMotorInverted;\n return this;\n }\n\n public ModuleConfig withSpeedAt12VoltsMps(double speedAt12VoltsMps) {\n this.SpeedAt12VoltsMps = speedAt12VoltsMps;\n return this;\n }\n\n public ModuleConfig withSimulationSteerInertia(double steerInertia) {\n this.SteerInertia = steerInertia;\n return this;\n }\n\n public ModuleConfig withSimulationDriveInertia(double driveInertia) {\n this.DriveInertia = driveInertia;\n return this;\n }\n\n public ModuleConfig withFeedbackSource(SwerveModuleSteerFeedbackType source) {\n this.FeedbackSource = source;\n return this;\n }\n\n public ModuleConfig withMotionMagicAcceleration(double acceleration) {\n this.MotionMagicAcceleration = acceleration;\n return this;\n }\n\n public ModuleConfig withMotionMagicCruiseVelocity(double cruiseVelocity) {\n this.MotionMagicCruiseVelocity = cruiseVelocity;\n return this;\n }\n}"
},
{
"identifier": "SwerveConfig",
"path": "src/main/java/frc/spectrumLib/swerve/config/SwerveConfig.java",
"snippet": "public class SwerveConfig {\n /** CAN ID of the Pigeon2 on the drivetrain */\n public int Pigeon2Id = 0;\n /** Name of CANivore the swerve drive is on */\n public String CANbusName = \"rio\";\n\n /** If using Pro, specify this as true to make use of all the Pro features */\n public boolean SupportsPro = false;\n\n public ModuleConfig[] modules = new ModuleConfig[0];\n\n /*Rotation Controller*/\n public double kPRotationController = 0.0;\n public double kIRotationController = 0.0;\n public double kDRotationController = 0.0;\n\n /*Profiling Configs*/\n public double maxVelocity = 0;\n public double maxAccel = maxVelocity * 1.5; // take 1/2 sec to get to max speed.\n public double maxAngularVelocity = Math.PI * 2;\n public double maxAngularAcceleration = Math.pow(maxAngularVelocity, 2);\n\n public SwerveConfig withPigeon2Id(int id) {\n this.Pigeon2Id = id;\n return this;\n }\n\n public SwerveConfig withCANbusName(String name) {\n this.CANbusName = name;\n return this;\n }\n\n public SwerveConfig withSupportsPro(boolean supportsPro) {\n this.SupportsPro = supportsPro;\n return this;\n }\n\n public SwerveConfig withModules(ModuleConfig[] modules) {\n this.modules = modules;\n return this;\n }\n\n public SwerveConfig withRotationGains(double kP, double kI, double kD) {\n this.kPRotationController = kP;\n this.kIRotationController = kI;\n this.kDRotationController = kD;\n return this;\n }\n\n public SwerveConfig withProfilingConfigs(\n double maxVelocity,\n double maxAccel,\n double maxAngularVelocity,\n double maxAngularAcceleration) {\n this.maxVelocity = maxVelocity;\n this.maxAccel = maxAccel;\n this.maxAngularVelocity = maxAngularVelocity;\n this.maxAngularAcceleration = maxAngularAcceleration;\n return this;\n }\n}"
}
] | import com.ctre.phoenix6.hardware.Pigeon2;
import com.ctre.phoenix6.sim.CANcoderSimState;
import com.ctre.phoenix6.sim.Pigeon2SimState;
import com.ctre.phoenix6.sim.TalonFXSimState;
import edu.wpi.first.math.geometry.Rotation2d;
import edu.wpi.first.math.geometry.Translation2d;
import edu.wpi.first.math.geometry.Twist2d;
import edu.wpi.first.math.kinematics.SwerveDriveKinematics;
import edu.wpi.first.math.kinematics.SwerveModulePosition;
import edu.wpi.first.math.system.plant.DCMotor;
import edu.wpi.first.wpilibj.simulation.DCMotorSim;
import frc.spectrumLib.swerve.config.ModuleConfig;
import frc.spectrumLib.swerve.config.SwerveConfig; | 2,761 | package frc.spectrumLib.swerve;
/**
* Extremely simplified swerve drive simulation class.
*
* <p>This class assumes that the swerve drive is perfect, meaning that there is no scrub and the
* wheels do not slip.
*
* <p>In addition, it assumes the inertia of the robot is governed only by the inertia of the steer
* module and the individual drive wheels. Robot-wide inertia is not accounted for, and neither is
* translational vs rotational inertia of the robot.
*
* <p>These assumptions provide a simplified example that can demonstrate the behavior of a swerve
* drive in simulation. Users are encouraged to expand this model for their own use.
*/
public class SimDrivetrain {
public class SimSwerveModule {
/* Reference to motor simulation for the steer motor */
public final DCMotorSim SteerMotor;
/* Reference to motor simulation for drive motor */
public final DCMotorSim DriveMotor;
/* Refernece to steer gearing for updating CANcoder */
public final double SteerGearing;
/* Refernece to steer gearing for updating CANcoder */
public final double DriveGearing;
public SimSwerveModule(
double steerGearing,
double steerInertia,
double driveGearing,
double driveInertia) {
SteerMotor = new DCMotorSim(DCMotor.getFalcon500(1), steerGearing, steerInertia);
DriveMotor = new DCMotorSim(DCMotor.getFalcon500(1), driveGearing, driveInertia);
SteerGearing = steerGearing;
DriveGearing = driveGearing;
}
}
public final Pigeon2SimState PigeonSim;
protected final SimSwerveModule[] m_modules;
protected final SwerveModulePosition[] m_lastPositions;
private final int ModuleCount;
public final SwerveDriveKinematics Kinem;
public Rotation2d LastAngle = new Rotation2d();
public SimDrivetrain(
Translation2d[] wheelLocations,
Pigeon2 pigeon, | package frc.spectrumLib.swerve;
/**
* Extremely simplified swerve drive simulation class.
*
* <p>This class assumes that the swerve drive is perfect, meaning that there is no scrub and the
* wheels do not slip.
*
* <p>In addition, it assumes the inertia of the robot is governed only by the inertia of the steer
* module and the individual drive wheels. Robot-wide inertia is not accounted for, and neither is
* translational vs rotational inertia of the robot.
*
* <p>These assumptions provide a simplified example that can demonstrate the behavior of a swerve
* drive in simulation. Users are encouraged to expand this model for their own use.
*/
public class SimDrivetrain {
public class SimSwerveModule {
/* Reference to motor simulation for the steer motor */
public final DCMotorSim SteerMotor;
/* Reference to motor simulation for drive motor */
public final DCMotorSim DriveMotor;
/* Refernece to steer gearing for updating CANcoder */
public final double SteerGearing;
/* Refernece to steer gearing for updating CANcoder */
public final double DriveGearing;
public SimSwerveModule(
double steerGearing,
double steerInertia,
double driveGearing,
double driveInertia) {
SteerMotor = new DCMotorSim(DCMotor.getFalcon500(1), steerGearing, steerInertia);
DriveMotor = new DCMotorSim(DCMotor.getFalcon500(1), driveGearing, driveInertia);
SteerGearing = steerGearing;
DriveGearing = driveGearing;
}
}
public final Pigeon2SimState PigeonSim;
protected final SimSwerveModule[] m_modules;
protected final SwerveModulePosition[] m_lastPositions;
private final int ModuleCount;
public final SwerveDriveKinematics Kinem;
public Rotation2d LastAngle = new Rotation2d();
public SimDrivetrain(
Translation2d[] wheelLocations,
Pigeon2 pigeon, | SwerveConfig swerveConfig, | 1 | 2023-10-23 17:01:53+00:00 | 4k |
imart302/DulceNectar-BE | src/main/java/com/dulcenectar/java/controllers/ProductController.java | [
{
"identifier": "CreateProductRequestDto",
"path": "src/main/java/com/dulcenectar/java/dtos/product/CreateProductRequestDto.java",
"snippet": "public class CreateProductRequestDto implements RequestDto <Product>{\n\t\n\tprivate String name;\n\tprivate String info;\n\tprivate Float gram;\n\tprivate String imgUrl;\n\tprivate Double price;\n\tprivate Long stock;\n\tprivate String typeGram;\n\tprivate String category;\n\n\n\t//Constructor\n\tpublic CreateProductRequestDto(String name, String info, Float gram, String imgUrl, Double price, Long stock,\n\t\t\tString typeGram, String category) {\n\t\tsuper();\n\t\tthis.name = name;\n\t\tthis.info = info;\n\t\tthis.gram = gram;\n\t\tthis.imgUrl = imgUrl;\n\t\tthis.price = price;\n\t\tthis.stock = stock;\n\t\tthis.typeGram = typeGram;\n\t}\n\t\n\t//Void constructor\n\tpublic CreateProductRequestDto() {\n\t\t\n\t}\n\n\t//Getters and setters\n\tpublic String getName() {\n\t\treturn name;\n\t}\n\n\tpublic void setName(String name) {\n\t\tthis.name = name;\n\t}\n\n\tpublic String getInfo() {\n\t\treturn info;\n\t}\n\n\tpublic void setInfo(String info) {\n\t\tthis.info = info;\n\t}\n\n\tpublic Float getGram() {\n\t\treturn gram;\n\t}\n\n\tpublic void setGram(Float gram) {\n\t\tthis.gram = gram;\n\t}\n\n\tpublic String getImgUrl() {\n\t\treturn imgUrl;\n\t}\n\n\tpublic void setImgUrl(String imgUrl) {\n\t\tthis.imgUrl = imgUrl;\n\t}\n\n\tpublic Double getPrice() {\n\t\treturn price;\n\t}\n\n\tpublic void setPrice(Double price) {\n\t\tthis.price = price;\n\t}\n\n\tpublic Long getStock() {\n\t\treturn stock;\n\t}\n\n\tpublic void setStock(Long stock) {\n\t\tthis.stock = stock;\n\t}\n\n\tpublic String getTypeGram() {\n\t\treturn typeGram;\n\t}\n\n\tpublic void setTypeGram(String typeGram) {\n\t\tthis.typeGram = typeGram;\n\t}\n\t\n\tpublic String getCategory() {\n\t\treturn category;\n\t}\n\n\tpublic void setCategory(String category) {\n\t\tthis.category = category;\n\t}\n\t\n\t@Override\n\tpublic Product toEntity() {\n\t\tProduct product = new Product();\n\t\tproduct.setName(this.name);\n\t\tproduct.setInfo(this.info);\n\t\tproduct.setGram(this.gram);\n\t\tproduct.setImgUrl(this.imgUrl);\n\t\tproduct.setPrice(this.price);\n\t\tproduct.setStock(this.stock);\n\t\tproduct.setTypeGram(this.typeGram);\n\t\t\n\t\treturn product;\n\t}\n\t\n}"
},
{
"identifier": "CreateProductResponseDto",
"path": "src/main/java/com/dulcenectar/java/dtos/product/CreateProductResponseDto.java",
"snippet": "public class CreateProductResponseDto implements ResponseDto<Product> {\n\n\tprivate Integer id;\n\tprivate String name;\n\tprivate String info;\n\tprivate Float gram;\n\tprivate String imgUrl;\n\tprivate Double price;\n\tprivate Long stock;\n\tprivate String typeGram;\n\tprivate Category category;\n\t\n\t//Constructor\n\tpublic CreateProductResponseDto(Integer id, String name, String info, Float gram, String imgUrl, Double price,\n\t\t\tLong stock, String typeGram, Category category) {\n\t\tsuper();\n\t\tthis.id = id;\n\t\tthis.name = name;\n\t\tthis.info = info;\n\t\tthis.gram = gram;\n\t\tthis.imgUrl = imgUrl;\n\t\tthis.price = price;\n\t\tthis.stock = stock;\n\t\tthis.typeGram = typeGram;\n\t\tthis.category = category;\n\t}\n\t\n\t//Void Constructor\n\tpublic CreateProductResponseDto() {\n\t\t\n\t}\n\t\n\t//Getters and Setters\n\tpublic long getId() {\n\t\treturn id;\n\t}\n\n\tpublic void setId(Integer id) {\n\t\tthis.id = id;\n\t}\n\n\tpublic String getName() {\n\t\treturn name;\n\t}\n\n\tpublic void setName(String name) {\n\t\tthis.name = name;\n\t}\n\n\tpublic String getInfo() {\n\t\treturn info;\n\t}\n\n\tpublic void setInfo(String info) {\n\t\tthis.info = info;\n\t}\n\n\tpublic Float getGram() {\n\t\treturn gram;\n\t}\n\n\tpublic void setGram(Float gram) {\n\t\tthis.gram = gram;\n\t}\n\n\tpublic String getImgUrl() {\n\t\treturn imgUrl;\n\t}\n\n\tpublic void setImgUrl(String imgUrl) {\n\t\tthis.imgUrl = imgUrl;\n\t}\n\n\tpublic Double getPrice() {\n\t\treturn price;\n\t}\n\n\tpublic void setPrice(Double price) {\n\t\tthis.price = price;\n\t}\n\n\tpublic Long getStock() {\n\t\treturn stock;\n\t}\n\n\tpublic void setStock(Long stock) {\n\t\tthis.stock = stock;\n\t}\n\n\tpublic String getTypeGram() {\n\t\treturn typeGram;\n\t}\n\n\tpublic void setTypeGram(String typeGram) {\n\t\tthis.typeGram = typeGram;\n\t}\n\t\n\t\n\tpublic Category getCategory() {\n\t\treturn category;\n\t}\n\n\tpublic void setCategory(Category category) {\n\t\tthis.category = category;\n\t}\n\n\t@Override\n\tpublic CreateProductResponseDto fromEntity(Product entity) {\n\t\tthis.id = entity.getId();\n\t\tthis.name = entity.getName();\n\t\tthis.info = entity.getInfo();\n\t\tthis.gram = entity.getGram();\n\t\tthis.imgUrl = entity.getImgUrl();\n\t\tthis.price = entity.getPrice();\n\t\tthis.stock = entity.getStock();\n\t\tthis.typeGram = entity.getTypeGram();\n\t\tthis.category = entity.getCategory();\n\t\t\n\t\treturn this;\n\t}\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n}"
},
{
"identifier": "ProductService",
"path": "src/main/java/com/dulcenectar/java/services/interfaces/ProductService.java",
"snippet": " public interface ProductService {\n\tpublic CreateProductResponseDto createProduct(CreateProductRequestDto product);\n\tpublic ArrayList <CreateProductResponseDto> getProductsList();\n\tpublic CreateProductResponseDto updateProduct(Integer id, CreateProductRequestDto productModifyRequest);\n\tpublic void deleteProduct(Integer id);\n\t\n\t\n\n}"
}
] | import java.util.ArrayList;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
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 com.dulcenectar.java.dtos.product.CreateProductRequestDto;
import com.dulcenectar.java.dtos.product.CreateProductResponseDto;
import com.dulcenectar.java.services.interfaces.ProductService; | 1,702 | package com.dulcenectar.java.controllers;
@RestController
@RequestMapping(path = "/product")
public class ProductController {
private final ProductService productServices;
public ProductController(ProductService productServices) {
super();
this.productServices = productServices;
}
@GetMapping() | package com.dulcenectar.java.controllers;
@RestController
@RequestMapping(path = "/product")
public class ProductController {
private final ProductService productServices;
public ProductController(ProductService productServices) {
super();
this.productServices = productServices;
}
@GetMapping() | public ResponseEntity< ArrayList <CreateProductResponseDto>> getProductsList(){ | 1 | 2023-10-24 00:07:39+00:00 | 4k |
CMarcoo/RuntimeLib | src/main/java/top/cmarco/runtimelib/RuntimeLib.java | [
{
"identifier": "RuntimeLibConfig",
"path": "src/main/java/top/cmarco/runtimelib/config/RuntimeLibConfig.java",
"snippet": "@RequiredArgsConstructor\npublic final class RuntimeLibConfig {\n\n private final RuntimeLib runtimeLib;\n private FileConfiguration configuration = null;\n\n public void saveDefaultConfig() {\n runtimeLib.saveDefaultConfig();\n this.configuration = runtimeLib.getConfig();\n }\n\n public boolean getFullDebug() {\n return configuration.getBoolean(\"full-debug\");\n }\n}"
},
{
"identifier": "RuntimePluginDiscovery",
"path": "src/main/java/top/cmarco/runtimelib/loader/RuntimePluginDiscovery.java",
"snippet": "@RequiredArgsConstructor\npublic final class RuntimePluginDiscovery {\n\n private final RuntimeLib runtimeLib;\n private final List<RuntimePlugin> runtimePlugins = new ArrayList<>();\n private URLClassLoader runtimePluginClassLoader;\n\n /**\n * Load runtime plugins from the designated folder .../RuntimeLib/runtime-plugins/.\n * It searches for JAR files, validates them,\n * and loads suitable classes that implement the `RuntimePlugin` interface.\n * Loaded runtime plugins are stored in the `runtimePlugins` list.\n */\n public void loadRuntimePlugins() {\n boolean fullLog = runtimeLib.getRuntimeLibConfig().getFullDebug();\n Logger logger = runtimeLib.getLogger();\n List<RuntimePlugin> runtimePlugins = new ArrayList<>();\n File pluginsFolder = new File(runtimeLib.getDataFolder().getAbsolutePath() + File.separator + \"runtime-plugins\");\n\n if (!pluginsFolder.exists()) {\n if (fullLog) {\n logger.info(\"The runtime-plugins folder didn't exist, we created one. \\n\" +\n \"Please, remember to add your Runtime Plugins here, and not in the parent folder!\\n\" +\n \"Thanks for choosing RuntimeLib!\");\n }\n boolean result = pluginsFolder.mkdirs();\n return;\n }\n\n if (!pluginsFolder.exists()) {\n logger.warning(\"ERROR: The plugin folder was not found.\");\n return;\n }\n\n File[] jarFiles = pluginsFolder.listFiles();\n\n if (jarFiles == null) {\n logger.warning(\"ERROR: No JAR files were found in the plugins directory!\");\n return;\n } else if (fullLog) {\n logger.info(\"Found following JARs to load:\" + Arrays.stream(jarFiles).map(File::getName).collect(Collectors.joining(\", \")));\n } else if (jarFiles.length == 0) {\n logger.info(\"No Runtime JARs were found!\");\n return;\n }\n\n List<File> jarFilesList = Arrays.asList(jarFiles);\n\n if (fullLog) logger.info(\"Starting JAR files URL validation phase.\");\n\n List<URL> urlsList = jarFilesList.stream().map(file -> {\n try {\n return file.toURI().toURL();\n } catch (MalformedURLException e) {\n logger.warning(\"ERROR: List getting URL for \" + file.getName());\n return null;\n }\n }).filter(Objects::nonNull).collect(Collectors.toList());\n\n if (fullLog) logger.info(\"Successfully found and validated \" + urlsList.size() + \" JAR URLs.\");\n\n URL[] urls = new URL[urlsList.size()];\n urls = urlsList.toArray(urls);\n\n URLClassLoader classLoader = new URLClassLoader(urls, getClass().getClassLoader());\n this.runtimePluginClassLoader = classLoader;\n\n label:\n for (File candidate : jarFilesList) {\n List<String> classNames = new ArrayList<>();\n try {\n ZipInputStream zip = new ZipInputStream(java.nio.file.Files.newInputStream(candidate.toPath()));\n for (ZipEntry entry = zip.getNextEntry(); entry != null; entry = zip.getNextEntry()) {\n if (!entry.isDirectory() && entry.getName().endsWith(\".class\")) {\n // This ZipEntry represents a class. Now, what class does it represent?\n String className = entry.getName().replace('/', '.'); // including \".class\"\n if (fullLog)\n logger.info(\"Discovered class content \\\"\" + className + \"\\\" of \" + candidate.getName());\n String addClassName = className.substring(0, className.length() - \".class\".length());\n classNames.add(addClassName);\n }\n }\n zip.close();\n } catch (IOException e) {\n logger.warning(\"ERROR: problem during jar zip reading phase!\");\n logger.warning(e.getLocalizedMessage());\n }\n\n for (String className : classNames) {\n try {\n if (fullLog) logger.info(\"Attempting to load class \\\"\" + className + \"\\\".\");\n Class<?> tempClass = Class.forName(className, true, classLoader);\n if (RuntimePlugin.class.isAssignableFrom(tempClass)) {\n logger.info(\"Found suitable plugin candidate class: \" + className);\n logger.info(\"Attempting to load . . .\");\n // assume safe constructor cast\n Constructor<? extends RuntimePlugin> tempConstructor = (Constructor<? extends RuntimePlugin>) tempClass.getConstructor();\n RuntimePlugin instance = tempConstructor.newInstance();\n this.runtimePlugins.add(instance);\n continue label;\n }\n } catch (ClassNotFoundException e) {\n logger.warning(\"ERROR: problem during class forName search phase!\");\n logger.warning(e.getLocalizedMessage());\n } catch (NoSuchMethodException e) {\n logger.warning(\"ERROR: could not find standard constructor for \" + className);\n logger.warning(e.getLocalizedMessage());\n } catch (InvocationTargetException | InstantiationException | IllegalAccessException e) {\n logger.warning(\"ERROR: Could not create new instance for \" + className);\n logger.warning(e.getLocalizedMessage());\n }\n }\n }\n\n }\n\n /**\n * Start all loaded runtime plugins. This method invokes the `onEnable` method\n * on each loaded plugin.\n */\n public void startAll() {\n this.runtimePlugins.forEach(rp -> {\n runtimeLib.getLogger().info(\"Enabling runtime plugin \" + rp.getClass().getSimpleName());\n rp.onEnable();\n });\n }\n\n /**\n * Stop all loaded runtime plugins. This method invokes the `onDisable` method\n * on each loaded plugin.\n */\n public void stopAll() {\n this.runtimePlugins.forEach(rp -> {\n runtimeLib.getLogger().info(\"Disabling runtime plugin \" + rp.getClass().getSimpleName());\n rp.onDisable();\n });\n }\n\n}"
}
] | import lombok.Getter;
import org.bukkit.plugin.java.JavaPlugin;
import top.cmarco.runtimelib.config.RuntimeLibConfig;
import top.cmarco.runtimelib.loader.RuntimePluginDiscovery; | 1,605 | package top.cmarco.runtimelib;
/**
* The `RuntimeLib` class is a Minecraft plugin that manages the discovery, loading, and operation
* of runtime plugins within the server. It extends the `JavaPlugin` class and provides methods to
* load and manage runtime plugins, along with loading and managing its own configuration.
*
* @author Marco C.
* @version 1.0.0
* @since 15 Oct. 2023
*/
public final class RuntimeLib extends JavaPlugin {
private RuntimePluginDiscovery pluginDiscovery = null; | package top.cmarco.runtimelib;
/**
* The `RuntimeLib` class is a Minecraft plugin that manages the discovery, loading, and operation
* of runtime plugins within the server. It extends the `JavaPlugin` class and provides methods to
* load and manage runtime plugins, along with loading and managing its own configuration.
*
* @author Marco C.
* @version 1.0.0
* @since 15 Oct. 2023
*/
public final class RuntimeLib extends JavaPlugin {
private RuntimePluginDiscovery pluginDiscovery = null; | @Getter private RuntimeLibConfig runtimeLibConfig; | 0 | 2023-10-17 17:41:29+00:00 | 4k |
DaveScott99/ToyStore-JSP | src/main/java/br/com/toyStore/dao/ProductDAO.java | [
{
"identifier": "DbException",
"path": "src/main/java/br/com/toyStore/exception/DbException.java",
"snippet": "public class DbException extends RuntimeException {\n\n\tprivate static final long serialVersionUID = 1L;\n\n\tpublic DbException(String msg) {\n\t\tsuper(msg);\n\t}\n\t\n}"
},
{
"identifier": "Category",
"path": "src/main/java/br/com/toyStore/model/Category.java",
"snippet": "public class Category {\n\n\tprivate Long id;\n\tprivate String name;\n\tprivate String imageName;\n\t\t\n\tpublic Category() {\n\t}\n\n\tpublic Category(Long id, String name, String imageName) {\n\t\tthis.id = id;\n\t\tthis.name = name;\n\t\tthis.imageName = imageName;\n\t}\n\n\tpublic Long getId() {\n\t\treturn id;\n\t}\n\n\tpublic void setId(Long id) {\n\t\tthis.id = id;\n\t}\n\n\tpublic String getName() {\n\t\treturn name;\n\t}\n\n\tpublic void setName(String name) {\n\t\tthis.name = name;\n\t}\n\n\tpublic String getImageName() {\n\t\treturn imageName;\n\t}\n\n\tpublic void setImageName(String imageName) {\n\t\tthis.imageName = imageName;\n\t}\n\t\n}"
},
{
"identifier": "Product",
"path": "src/main/java/br/com/toyStore/model/Product.java",
"snippet": "public class Product implements Serializable {\n\n\tprivate static final long serialVersionUID = 1L;\n\t\n\tprivate Long id;\n\tprivate String name;\n\tprivate Double price;\n\tprivate String imageName;\n\tprivate String brand;\n\tprivate String description;\n\t\n\tprivate Category category;\n\t\n\tpublic Product() {\n\t}\n\n\tpublic Product(Long id, String name, Double price, String imageName, String brand, String description,\n\t\t\tCategory category) {\n\t\tthis.id = id;\n\t\tthis.name = name;\n\t\tthis.price = price;\n\t\tthis.imageName = imageName;\n\t\tthis.brand = brand;\n\t\tthis.description = description;\n\t\tthis.category = category;\n\t}\n\n\tpublic Long getId() {\n\t\treturn id;\n\t}\n\n\tpublic void setId(Long id) {\n\t\tthis.id = id;\n\t}\n\n\tpublic String getName() {\n\t\treturn name;\n\t}\n\n\tpublic void setName(String name) {\n\t\tthis.name = name;\n\t}\n\n\tpublic Double getPrice() {\n\t\treturn price;\n\t}\n\n\tpublic void setPrice(Double price) {\n\t\tthis.price = price;\n\t}\n\n\tpublic String getDescription() {\n\t\treturn description;\n\t}\n\n\tpublic void setDescription(String description) {\n\t\tthis.description = description;\n\t}\n\n\tpublic Category getCategory() {\n\t\treturn category;\n\t}\n\n\tpublic void setCategory(Category category) {\n\t\tthis.category = category;\n\t}\n\n\tpublic String getImageName() {\n\t\treturn imageName;\n\t}\n\n\tpublic void setImageName(String imageName) {\n\t\tthis.imageName = imageName;\n\t}\n\n\tpublic String getBrand() {\n\t\treturn brand;\n\t}\n\n\tpublic void setBrand(String brand) {\n\t\tthis.brand = brand;\n\t}\n\t\n}"
},
{
"identifier": "ConnectionFactory",
"path": "src/main/java/br/com/toyStore/util/ConnectionFactory.java",
"snippet": "public class ConnectionFactory {\n\nprivate static Connection conn = null;\n\t\n\tpublic static Connection getConnection() {\n\t\tif (conn == null) {\n\t\t\ttry {\n\t\t\t\t\n\t\t\t\tClass.forName(\"com.mysql.jdbc.Driver\");\n\t\t\t\t\n\t\t\t\tString login = \"root\";\n\t\t\t\tString senha = \"1305\";\n\t\t\t\tString url = \"jdbc:mysql://localhost:3306/TOY_STORE?useUnicode=true&characterEncoding=UTF-8\";\n\t\t\t\tconn = DriverManager.getConnection(url,login,senha);\n\t\t\t}\n\t\t\tcatch(SQLException e) {\n\t\t\t\tthrow new DbException(e.getMessage());\n\t\t\t} \n\t\t\tcatch (ClassNotFoundException e) {\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t}\n\t\treturn conn;\n\t}\n\t\n\tpublic static void closeConnection() {\n\t\tif (conn != null) {\n\t\t\ttry {\n\t\t\t\tconn.close();\n\t\t\t}\n\t\t\tcatch (SQLException e) {\n\t\t\t\tthrow new DbException(e.getMessage());\n\t\t\t}\n\t\t}\n\t}\n\t\n\tpublic static void closeStatement(Statement st) {\n\t\tif (st != null) {\n\t\t\ttry {\n\t\t\t\tst.close();\n\t\t\t} catch (SQLException e) {\n\t\t\t\tthrow new DbException(e.getMessage());\n\t\t\t}\n\t\t}\n\t}\n\t\n\tpublic static void closeResultSet(ResultSet rs) {\n\t\tif (rs != null) {\n\t\t\ttry {\n\t\t\t\trs.close();\n\t\t\t} catch (SQLException e) {\n\t\t\t\tthrow new DbException(e.getMessage());\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic static void closeConnection(Connection conn, Statement stmt,\n\t\t\tResultSet rs) throws Exception {\n\t\tclose(conn, stmt, rs);\n\t}\n\n\tpublic static void closeConnection(Connection conn, Statement stmt)\n\t\t\tthrows Exception {\n\t\tclose(conn, stmt, null);\n\t}\n\n\tpublic static void closeConnection(Connection conn) throws Exception {\n\t\tclose(conn, null, null);\n\t}\n\n\tprivate static void close(Connection conn, Statement stmt, ResultSet rs)\n\t\t\tthrows Exception {\n\t\ttry {\n\t\t\tif (rs != null)\n\t\t\t\trs.close();\n\t\t\tif (stmt != null)\n\t\t\t\tstmt.close();\n\t\t\tif (conn != null)\n\t\t\t\tconn.close();\n\t\t} catch (Exception e) {\n\t\t\tthrow new Exception(e.getMessage());\n\t\t}\n\t}\n\t\n}"
}
] | import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import br.com.toyStore.exception.DbException;
import br.com.toyStore.model.Category;
import br.com.toyStore.model.Product;
import br.com.toyStore.util.ConnectionFactory; | 2,128 | package br.com.toyStore.dao;
public class ProductDAO {
private Connection conn;
private PreparedStatement ps;
private ResultSet rs;
private Product product;
public ProductDAO(Connection conn) {
this.conn = conn;
}
public void insert(Product product) {
try {
if (product != null) {
String SQL = "INSERT INTO TOY_STORE.PRODUCT (NAME_PRODUCT, PRICE_PRODUCT, DESCRIPTION_PRODUCT, IMAGE_NAME_PRODUCT, BRAND_PRODUCT, ID_CATEGORY) values "
+ "(?, ?, ?, ?, ?, ?)";
ps = conn.prepareStatement(SQL);
ps.setString(1, product.getName());
ps.setDouble(2, product.getPrice());
ps.setString(3, product.getDescription());
ps.setString(4, product.getImageName());
ps.setString(5, product.getBrand());
ps.setLong(6, product.getCategory().getId());
ps.executeUpdate();
}
} catch (SQLException sqle) {
throw new DbException("Erro ao inserir dados " + sqle);
} finally {
ConnectionFactory.closeStatement(ps);
}
}
public void update(Product product) {
try {
if (product != null) {
String SQL = "UPDATE TOY_STORE.PRODUCT set NAME_PRODUCT=?, PRICE_PRODUCT=?, DESCRIPTION_PRODUCT=?, IMAGE_NAME_PRODUCT=?, ID_CATEGORY=?, BRAND_PRODUCT=? WHERE ID_PRODUCT=?";
ps = conn.prepareStatement(SQL);
ps.setString(1, product.getName());
ps.setDouble(2, product.getPrice());
ps.setString(3, product.getDescription());
ps.setString(4, product.getImageName());
ps.setLong(5, product.getCategory().getId());
ps.setString(6, product.getBrand());
ps.setLong(7, product.getId());
ps.executeUpdate();
}
} catch (SQLException sqle) {
throw new DbException("Erro ao alterar dados " + sqle);
} finally {
ConnectionFactory.closeStatement(ps);
}
}
public void delete(Integer idProduct) {
try {
String SQL = "DELETE FROM TOY_STORE.PRODUCT AS PROD WHERE PROD.ID_PRODUCT =?";
ps = conn.prepareStatement(SQL);
ps.setInt(1, idProduct);
ps.executeUpdate();
} catch (SQLException sqle) {
throw new DbException("Erro ao excluir dados " + sqle);
} finally {
ConnectionFactory.closeStatement(ps);
}
}
public Product findById(int idProduct) {
try {
String SQL = "SELECT * FROM TOY_STORE.PRODUCT AS PROD INNER JOIN TOY_STORE.CATEGORY AS CAT ON PROD.ID_CATEGORY = CAT.ID_CATEGORY WHERE PROD.ID_PRODUCT =?";
ps = conn.prepareStatement(SQL);
ps.setInt(1, idProduct);
rs = ps.executeQuery();
if (rs.next()) {
long id = rs.getInt("id_product");
String name = rs.getString("name_product");
String description = rs.getString("description_product");
double price = rs.getDouble("price_product");
String image = rs.getString("image_name_product");
String brand = rs.getString("brand_product");
long idCategory = rs.getInt("id_category");
String nameCategory = rs.getString("name_category");
String imageCategory = rs.getString("image_name_category");
product = new Product();
product.setId(id);
product.setName(name);
product.setPrice(price);
product.setDescription(description);
product.setImageName(image);
product.setBrand(brand);
| package br.com.toyStore.dao;
public class ProductDAO {
private Connection conn;
private PreparedStatement ps;
private ResultSet rs;
private Product product;
public ProductDAO(Connection conn) {
this.conn = conn;
}
public void insert(Product product) {
try {
if (product != null) {
String SQL = "INSERT INTO TOY_STORE.PRODUCT (NAME_PRODUCT, PRICE_PRODUCT, DESCRIPTION_PRODUCT, IMAGE_NAME_PRODUCT, BRAND_PRODUCT, ID_CATEGORY) values "
+ "(?, ?, ?, ?, ?, ?)";
ps = conn.prepareStatement(SQL);
ps.setString(1, product.getName());
ps.setDouble(2, product.getPrice());
ps.setString(3, product.getDescription());
ps.setString(4, product.getImageName());
ps.setString(5, product.getBrand());
ps.setLong(6, product.getCategory().getId());
ps.executeUpdate();
}
} catch (SQLException sqle) {
throw new DbException("Erro ao inserir dados " + sqle);
} finally {
ConnectionFactory.closeStatement(ps);
}
}
public void update(Product product) {
try {
if (product != null) {
String SQL = "UPDATE TOY_STORE.PRODUCT set NAME_PRODUCT=?, PRICE_PRODUCT=?, DESCRIPTION_PRODUCT=?, IMAGE_NAME_PRODUCT=?, ID_CATEGORY=?, BRAND_PRODUCT=? WHERE ID_PRODUCT=?";
ps = conn.prepareStatement(SQL);
ps.setString(1, product.getName());
ps.setDouble(2, product.getPrice());
ps.setString(3, product.getDescription());
ps.setString(4, product.getImageName());
ps.setLong(5, product.getCategory().getId());
ps.setString(6, product.getBrand());
ps.setLong(7, product.getId());
ps.executeUpdate();
}
} catch (SQLException sqle) {
throw new DbException("Erro ao alterar dados " + sqle);
} finally {
ConnectionFactory.closeStatement(ps);
}
}
public void delete(Integer idProduct) {
try {
String SQL = "DELETE FROM TOY_STORE.PRODUCT AS PROD WHERE PROD.ID_PRODUCT =?";
ps = conn.prepareStatement(SQL);
ps.setInt(1, idProduct);
ps.executeUpdate();
} catch (SQLException sqle) {
throw new DbException("Erro ao excluir dados " + sqle);
} finally {
ConnectionFactory.closeStatement(ps);
}
}
public Product findById(int idProduct) {
try {
String SQL = "SELECT * FROM TOY_STORE.PRODUCT AS PROD INNER JOIN TOY_STORE.CATEGORY AS CAT ON PROD.ID_CATEGORY = CAT.ID_CATEGORY WHERE PROD.ID_PRODUCT =?";
ps = conn.prepareStatement(SQL);
ps.setInt(1, idProduct);
rs = ps.executeQuery();
if (rs.next()) {
long id = rs.getInt("id_product");
String name = rs.getString("name_product");
String description = rs.getString("description_product");
double price = rs.getDouble("price_product");
String image = rs.getString("image_name_product");
String brand = rs.getString("brand_product");
long idCategory = rs.getInt("id_category");
String nameCategory = rs.getString("name_category");
String imageCategory = rs.getString("image_name_category");
product = new Product();
product.setId(id);
product.setName(name);
product.setPrice(price);
product.setDescription(description);
product.setImageName(image);
product.setBrand(brand);
| product.setCategory(new Category(idCategory, nameCategory, imageCategory)); | 1 | 2023-10-20 02:51:14+00:00 | 4k |
Lewoaragao/filetransfer | src/main/java/com/filetransfer/controller/FileController.java | [
{
"identifier": "FileResponse",
"path": "src/main/java/com/filetransfer/response/FileResponse.java",
"snippet": "@Data\n@Builder\n@NoArgsConstructor\n@AllArgsConstructor\npublic class FileResponse {\n\n\tprivate Integer index;\n\tprivate String message;\n\tprivate String fileName;\n\n\tpublic FileResponse(String message) {\n\t\tthis.message = message;\n\t}\n}"
},
{
"identifier": "FilesResponse",
"path": "src/main/java/com/filetransfer/response/FilesResponse.java",
"snippet": "@Data\n@Builder\n@NoArgsConstructor\n@AllArgsConstructor\npublic class FilesResponse {\n\n\tprivate String message;\n\tprivate List<String> fileNames;\n\tprivate List<FileVO> files;\n\n\tpublic FilesResponse(String message) {\n\t\tthis.message = message;\n\t}\n}"
},
{
"identifier": "FileService",
"path": "src/main/java/com/filetransfer/service/FileService.java",
"snippet": "@Service\npublic class FileService {\n\n\tpublic static final String uploadDir = \"src/main/resources/static/uploads\";\n\n\tpublic String saveFile(MultipartFile file, Integer index) throws IOException {\n\t\tLocalDateTime currentTime = LocalDateTime.now();\n\t\tDateTimeFormatter formatter = DateTimeFormatter.ofPattern(\"yyyyMMddHHmmss\");\n\t\tString formattedDateTime = currentTime.format(formatter);\n\n\t\t// Obtenha o nome original do arquivo\n\t\tString fileExtension = this.getFileExtension(file);\n\n\t\t// Remova espaços e substitua por underline\n\t\tString sanitizedFileName = this.getSanitizedFileName(file);\n\n\t\t// Combine o nome sanitizado com a data/hora formatada e a extensão do arquivo\n\t\tString fileName = sanitizedFileName + \"_\" + formattedDateTime + index + fileExtension;\n\n\t\tPath uploadPath = Paths.get(uploadDir);\n\t\tFiles.createDirectories(uploadPath);\n\t\tPath destinationPath = uploadPath.resolve(fileName);\n\n\t\tFiles.copy(file.getInputStream(), destinationPath, StandardCopyOption.REPLACE_EXISTING);\n\n\t\treturn fileName;\n\t}\n\n\tpublic String getFileNameWithoutExtension(MultipartFile file) {\n\t\t// Obtenha o nome original do arquivo\n\t\tString originalFileName = file.getOriginalFilename();\n\n\t\t// Verifique se o nome original do arquivo contém uma extensão\n\t\tint lastIndex = originalFileName.lastIndexOf('.');\n\n\t\tif (lastIndex >= 0) {\n\t\t\t// Remova a extensão do nome original\n\t\t\treturn originalFileName.substring(0, lastIndex);\n\t\t} else {\n\t\t\t// Se não houver extensão, retorne o nome original completo\n\t\t\treturn originalFileName;\n\t\t}\n\t}\n\n\tpublic String getSanitizedFileName(MultipartFile file) {\n\t\t// Obtenha o nome original do arquivo\n\t\tString originalFileName = this.getFileNameWithoutExtension(file);\n\n\t\t// Remova a acentuação substituindo caracteres acentuados por não acentuados\n\t\toriginalFileName = removeAccents(originalFileName);\n\t\t\n\t\t// Remove todos os pontos de interrogação por underline, \n\t\t// geralmente ocorre por erro de encoding, por isso vem esses\n\t\t// pontos de interrogação\n\t\toriginalFileName = originalFileName.replace(\"?\", \"_\");\n\n\t\t// Substitua espaços por underscores\n\t\tString sanitizedFileName = originalFileName.replaceAll(\" \", \"_\");\n\n\t\treturn sanitizedFileName;\n\t}\n\n\tprivate String removeAccents(String input) {\n\t\t// Use Normalizer para remover a acentuação\n\t\tString normalizedString = Normalizer.normalize(input, Normalizer.Form.NFD);\n\t\t// Substitua caracteres acentuados por não acentuados\n\t\treturn normalizedString.replaceAll(\"[^\\\\p{ASCII}]\", \"\");\n\t}\n\n\tpublic String getFileExtension(MultipartFile file) {\n\t\t// Obtenha o nome original do arquivo\n\t\tString originalFileName = file.getOriginalFilename();\n\n\t\t// Obtenha a extensão do arquivo\n\t\tString fileExtension = originalFileName.substring(originalFileName.lastIndexOf(\".\"));\n\n\t\treturn fileExtension;\n\t}\n\n}"
},
{
"identifier": "Util",
"path": "src/main/java/com/filetransfer/util/Util.java",
"snippet": "public class Util {\n\n\tpublic static MediaType getMediaTypeForFile(String filename) {\n\t\tString extension = filename.substring(filename.lastIndexOf(\".\")).toLowerCase();\n\t\textension = extension.replace(\".\", \"\");\n\n\t\tswitch (extension) {\n\n\t\tcase \"pdf\":\n\t\t\treturn MediaType.APPLICATION_PDF;\n\t\tcase \"jpg\":\n\t\tcase \"jpeg\":\n\t\t\treturn MediaType.IMAGE_JPEG;\n\t\tcase \"png\":\n\t\t\treturn MediaType.IMAGE_PNG;\n\t\tcase \"gif\":\n\t\t\treturn MediaType.IMAGE_GIF;\n\t\tcase \"bmp\":\n\t\t\treturn MediaType.valueOf(\"image/bmp\");\n\t\tcase \"svg\":\n\t\t\treturn MediaType.valueOf(\"image/svg+xml\");\n\t\tcase \"webp\":\n\t\t\treturn MediaType.valueOf(\"image/webp\");\n\t\tcase \"mp3\":\n\t\t\treturn MediaType.valueOf(\"audio/mpeg\");\n\t\tcase \"wav\":\n\t\t\treturn MediaType.valueOf(\"audio/wav\");\n\t\tcase \"ogg\":\n\t\t\treturn MediaType.valueOf(\"audio/ogg\");\n\t\tcase \"flac\":\n\t\t\treturn MediaType.valueOf(\"audio/flac\");\n\t\tdefault:\n\t\t\treturn MediaType.APPLICATION_OCTET_STREAM;\n\t\t}\n\t}\n\t\n}"
},
{
"identifier": "FileVO",
"path": "src/main/java/com/filetransfer/vo/FileVO.java",
"snippet": "@Data\n@Builder\n@NoArgsConstructor\n@AllArgsConstructor\npublic class FileVO {\n\n\tprivate Integer index;\n\tprivate String originalFilename;\n\tprivate String downloadFilename;\n\tprivate String filename;\n\tprivate String extension;\n\n}"
}
] | import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.filetransfer.response.FileResponse;
import com.filetransfer.response.FilesResponse;
import com.filetransfer.service.FileService;
import com.filetransfer.util.Util;
import com.filetransfer.vo.FileVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor; | 1,610 | package com.filetransfer.controller;
@RestController
@CrossOrigin("*")
@RequestMapping("/api/file")
@RequiredArgsConstructor
@Api(tags = "Operações com arquivo do tipo File")
public class FileController {
@Autowired
FileService service;
public int index = 0;
@GetMapping("/")
@ApiOperation(value = "Verificação de funcionamento do Controller")
public ResponseEntity<String> verificacaoController() {
return ResponseEntity.ok("Conferindo se o FileController está configurado corretamente!");
}
@PostMapping("/upload")
@ApiOperation(value = "Upload de um único arquivo") | package com.filetransfer.controller;
@RestController
@CrossOrigin("*")
@RequestMapping("/api/file")
@RequiredArgsConstructor
@Api(tags = "Operações com arquivo do tipo File")
public class FileController {
@Autowired
FileService service;
public int index = 0;
@GetMapping("/")
@ApiOperation(value = "Verificação de funcionamento do Controller")
public ResponseEntity<String> verificacaoController() {
return ResponseEntity.ok("Conferindo se o FileController está configurado corretamente!");
}
@PostMapping("/upload")
@ApiOperation(value = "Upload de um único arquivo") | public ResponseEntity<FileResponse> uploadFile(@RequestParam("file") MultipartFile file) throws IOException { | 0 | 2023-10-24 11:43:46+00:00 | 4k |
yallerocha/Estruturas-de-Dados-e-Algoritmos | src/main/java/com/dataStructures/avltree/countAndFill/AVLCountAndFillImpl.java | [
{
"identifier": "AVLTreeImpl",
"path": "src/main/java/com/dataStructures/avltree/AVLTreeImpl.java",
"snippet": "public class AVLTreeImpl<T extends Comparable<T>> extends BSTImpl<T> implements AVLTree<T> {\n\n\t// TODO Do not forget: you must override the methods insert and remove\n\t// conveniently.\n\n\t// AUXILIARY\n\tpublic int calculateBalance (BSTNode<T> node) {\n\t\tint resp = 0;\n\n\t\tif (!node.isEmpty()) {\n\t\t\tresp = this.heightRecursive((BSTNode<T>) node.getLeft())\n\t\t\t\t\t- this.heightRecursive((BSTNode<T>) node.getRight());\n\t\t}\n\t\treturn resp;\n\t}\n\n\t// AUXILIARY\n\tprotected void rebalance (BSTNode<T> node) {\n\t\tBSTNode<T> newRoot = null;\n\t\tint balance = this.calculateBalance(node);\n\n\t\tif (Math.abs(balance) > 1) {\n\t\t\tif (balance > 1) {\n\t\t\t\tif (this.calculateBalance((BSTNode<T>) node.getLeft()) >= 0) {\n\t\t\t\t\tnewRoot = UtilRotation.rightRotation(node);\n\t\t\t\t} else {\n\t\t\t\t\tnewRoot = UtilRotation.doubleRightRotation(node);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif (this.calculateBalance((BSTNode<T>) node.getRight()) <= 0) {\n\t\t\t\t\tnewRoot = UtilRotation.leftRotation(node);\n\t\t\t\t} else {\n\t\t\t\t\tnewRoot = UtilRotation.doubleLeftRotation(node);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (this.getRoot().equals(node) && newRoot != null) {\n\t\t\tthis.root = newRoot;\n\t\t}\n\t}\n\n\t// AUXILIARY\n\tprotected void rebalanceUp (BSTNode<T> node) {\n\t\tif (!node.getParent().isEmpty()) {\n\t\t\tthis.rebalance((BSTNode<T>) node.getParent());\n\t\t\tthis.rebalanceUp((BSTNode<T>) node.getParent());\n\t\t}\n\t}\n\n\t@Override\n\tpublic void insert (T element) {\n\t\tif (element != null)\n\t\t\tthis.insertRecursive(this.root, element);\n\t}\n\n\t@SuppressWarnings(\"unchecked\")\n\tprivate void insertRecursive (BSTNode<T> currentNode, T element) {\n\t\tif (currentNode.isEmpty()) {\n\t\t\tcurrentNode.setData(element);\n\t\t\tcurrentNode.setRight(new BSTNode.Builder<T>().parent(currentNode).build());\n\t\t\tcurrentNode.setLeft(new BSTNode.Builder<T>().parent(currentNode).build());\n\t\t} else {\n\t\t\tif (element.compareTo(currentNode.getData()) > 0) {\n\t\t\t\tthis.insertRecursive((BSTNode<T>) currentNode.getRight(), element);\n\t\t\t} else {\n\t\t\t\tthis.insertRecursive((BSTNode<T>) currentNode.getLeft(), element);\n\t\t\t}\n\t\t\trebalance(currentNode);\n\t\t}\n\t}\n\n\t@Override\n\tpublic void remove (T element) {\n\t\tif (element != null) {\n\t\t\tBSTNode<T> node = this.search(element);\n\n\t\t\tif (!node.isEmpty()) {\n\t\t\t\tif (node.isLeaf()) { \n\t\t\t\t\tnode.setData(null);\n\t\t\t\t\tnode.setLeft(null);\n\t\t\t\t\tnode.setRight(null);\n\t\t\t\t\trebalanceUp(node);\n\t\t\t\t} else if (node.getRight().isEmpty() || node.getLeft().isEmpty()) {\n\t\t\t\t\tBSTNode<T> childNode = null;\n\t\t\t\t\t\n\t\t\t\t\tif(node.getRight().isEmpty()) {\n\t\t\t\t\t\tchildNode = (BSTNode<T>) node.getLeft();\n\t\t\t\t\t} else {\n\t\t\t\t\t\tchildNode = (BSTNode<T>) node.getRight();\n\t\t\t\t\t}\n\t\t\t\t\tif (this.root.equals(node)) {\n\t\t\t\t\t\tthis.root = childNode;\n\t\t\t\t\t\tthis.root.setParent(null);\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tchildNode.setParent(node.getParent());\n\t\t\t\t\t\tif (node.getParent().getLeft().equals(node)) {\n\t\t\t\t\t\t\tnode.getParent().setLeft(childNode);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tnode.getParent().setRight(childNode);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\trebalanceUp(node);\n\t\t\t\t} else { \n\t\t\t\t\tT sucessor = this.sucessor(node.getData()).getData();\n\t\t\t\t\tthis.remove(sucessor);\n\t\t\t\t\tnode.setData(sucessor);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n}"
},
{
"identifier": "BSTNode",
"path": "src/main/java/com/dataStructures/binarySearchTree/BSTNode.java",
"snippet": "public class BSTNode<T extends Comparable<T>> extends BTNode<T> {\n\t\n\tpublic BSTNode() {\n\t\tsuper();\n\t}\n\n\t//código abaixo é um exempo de uso do padrão Builder para construir\n\t//objetos do tipo BSTNode sem usar construtor diretamente.\n\t//o código cliente desse padrao, criando o no vazio seria:\n\t// \t\tBSTNode<Integer> node = (BSTNode<Integer>) new BSTNode.Builder<Integer>()\n\t//\t\t\t.data(null)\n\t//\t\t\t.left(null)\n\t//\t\t\t.right(null)\n\t//\t\t\t.parent(null)\n\t//\t\t\t.build();\n\t\n\tpublic static class Builder<T>{\n\t\tT data;\n\t\tBTNode<T> left;\n\t\tBTNode<T> right;\n\t\tBTNode<T> parent;\n\t \n\t public BSTNode.Builder<T> data(T data){\n\t this.data = data;\n\t return this;\n\t }\n\t \n\t public BSTNode.Builder<T> left(BTNode<T> left){\n\t this.left = left;\n\t return this;\n\t }\n\t \n\t public BSTNode.Builder<T> right(BTNode<T> right){\n\t\t this.right = right;\n\t\t return this;\n\t\t}\n\t \n\t public BSTNode.Builder<T> parent(BTNode<T> parent){\n\t\t this.parent = parent;\n\t\t return this;\n\t\t}\n\t \n\t public BSTNode build(){\n\t \treturn new BSTNode(this);\n\t }\n\t }\n\tprivate BSTNode(BSTNode.Builder<T> builder){\n\t this.data = builder.data;\n\t this.left = builder.left;\n\t this.right = builder.right;\n\t this.parent = builder.parent;\n\t \n\t}\n}"
},
{
"identifier": "UtilRotation",
"path": "src/main/java/com/dataStructures/binarySearchTree/binaryTree/UtilRotation.java",
"snippet": "public class UtilRotation {\n\n\t/**\n\t * A rotacao a esquerda em node deve subir e retornar seu filho a direita\n\t * @param node\n\t * @return - noh que se tornou a nova raiz\n\t */\n\tpublic static <T extends Comparable<T>> BSTNode<T> leftRotation (BSTNode<T> node) {\n\t\tBSTNode<T> pivot = (BSTNode<T>) node.getRight();\n\t\n\t\tnode.setRight(pivot.getLeft());\n\t\tpivot.setLeft(node);\n\t\n\t\tpivot.setParent(node.getParent());\n\t\tnode.setParent(pivot);\n\t\tif (node.getRight() != null) {\n\t\t\tnode.getRight().setParent(node);\n\t\t}\n\t\n\t\tif (pivot.getParent() != null) {\n\t\t\tif (pivot.getParent().getRight() != null && pivot.getParent().getRight().equals(node)) {\n\t\t\t\tpivot.getParent().setRight(pivot);\n\t\t\t} else {\n\t\t\t\tpivot.getParent().setLeft(pivot);\n\t\t\t}\n\t\t}\n\t\treturn pivot;\n\t}\n\t\n\n\t/**\n\t * A rotacao a direita em node deve subir e retornar seu filho a esquerda\n\t * @param node\n\t * @return noh que se tornou a nova raiz\n\t */\n\tpublic static <T extends Comparable<T>> BSTNode<T> rightRotation (BSTNode<T> node) {\n\t\tBSTNode<T> pivot = (BSTNode<T>) node.getLeft();\n\t\n\t\tif (pivot != null) {\n\t\t\tnode.setLeft(pivot.getRight());\n\t\t\tif (pivot.getRight() != null) {\n\t\t\t\tpivot.getRight().setParent(node);\n\t\t\t}\n\t\t\tpivot.setRight(node);\n\t\n\t\t\tpivot.setParent(node.getParent());\n\t\t\tnode.setParent(pivot);\n\t\t\tif (node.getLeft() != null) {\n\t\t\t\tnode.getLeft().setParent(node);\n\t\t\t}\n\t\n\t\t\tif (pivot.getParent() != null) {\n\t\t\t\tif (pivot.getParent().getLeft() != null && pivot.getParent().getLeft().equals(node)) {\n\t\t\t\t\tpivot.getParent().setLeft(pivot);\n\t\t\t\t} else if (pivot.getParent().getRight() != null) {\n\t\t\t\t\tpivot.getParent().setRight(pivot);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn pivot;\n\t}\n\t\n\t\n\tpublic static <T extends Comparable<T>> BSTNode<T> doubleLeftRotation (BSTNode<T> node) {\n\t\trightRotation((BSTNode<T>) node.getRight());\n\t\treturn leftRotation(node);\n\t}\n\n\tpublic static <T extends Comparable<T>> BSTNode<T> doubleRightRotation (BSTNode<T> node) {\n\t\tleftRotation((BSTNode<T>) node.getLeft());\n\t\treturn rightRotation(node);\n\t}\n\n\tpublic static <T extends Comparable<T>> T[] makeArrayOfComparable (int size) {\n\t\t@SuppressWarnings(\"unchecked\")\n\t\tT[] array = (T[]) new Comparable[size];\n\t\treturn array;\n\t}\n}"
}
] | import java.util.*;
import com.dataStructures.avltree.AVLTreeImpl;
import com.dataStructures.binarySearchTree.BSTNode;
import com.dataStructures.binarySearchTree.binaryTree.UtilRotation; | 2,424 | package com.dataStructures.avltree.countAndFill;
public class AVLCountAndFillImpl<T extends Comparable<T>> extends AVLTreeImpl<T> implements AVLCountAndFill<T> {
private int LLcounter;
private int LRcounter;
private int RRcounter;
private int RLcounter;
public AVLCountAndFillImpl() {
this.LLcounter = 0;
this.LRcounter = 0;
this.RRcounter = 0;
this.RLcounter = 0;
}
@Override
public int LLcount() {
return LLcounter;
}
@Override
public int LRcount() {
return LRcounter;
}
@Override
public int RRcount() {
return RRcounter;
}
@Override
public int RLcount() {
return RLcounter;
}
@Override
protected void rebalance (BSTNode<T> node) {
BSTNode<T> newRoot = null;
int balance = this.calculateBalance(node);
if (Math.abs(balance) > 1) {
if (balance > 1) {
if (this.calculateBalance((BSTNode<T>) node.getLeft()) >= 0) { | package com.dataStructures.avltree.countAndFill;
public class AVLCountAndFillImpl<T extends Comparable<T>> extends AVLTreeImpl<T> implements AVLCountAndFill<T> {
private int LLcounter;
private int LRcounter;
private int RRcounter;
private int RLcounter;
public AVLCountAndFillImpl() {
this.LLcounter = 0;
this.LRcounter = 0;
this.RRcounter = 0;
this.RLcounter = 0;
}
@Override
public int LLcount() {
return LLcounter;
}
@Override
public int LRcount() {
return LRcounter;
}
@Override
public int RRcount() {
return RRcounter;
}
@Override
public int RLcount() {
return RLcounter;
}
@Override
protected void rebalance (BSTNode<T> node) {
BSTNode<T> newRoot = null;
int balance = this.calculateBalance(node);
if (Math.abs(balance) > 1) {
if (balance > 1) {
if (this.calculateBalance((BSTNode<T>) node.getLeft()) >= 0) { | newRoot = UtilRotation.rightRotation(node); | 2 | 2023-10-21 21:39:25+00:00 | 4k |
MYSTD/BigDataApiTest | data-governance-assessment/src/main/java/com/std/dga/governance/bean/AssessParam.java | [
{
"identifier": "TDsTaskDefinition",
"path": "data-governance-assessment/src/main/java/com/std/dga/dolphinscheduler/bean/TDsTaskDefinition.java",
"snippet": "@Data\n@TableName(\"t_ds_task_definition\")\npublic class TDsTaskDefinition implements Serializable {\n\n private static final long serialVersionUID = 1L;\n\n /**\n * self-increasing id\n */\n @TableId(value = \"id\", type = IdType.AUTO)\n private Integer id;\n\n /**\n * encoding\n */\n private Long code;\n\n /**\n * task definition name\n */\n private String name;\n\n /**\n * task definition version\n */\n private Integer version;\n\n /**\n * description\n */\n private String description;\n\n /**\n * project code\n */\n private Long projectCode;\n\n /**\n * task definition creator id\n */\n private Integer userId;\n\n /**\n * task type\n */\n private String taskType;\n\n /**\n * job custom parameters\n */\n private String taskParams;\n\n /**\n * 0 not available, 1 available\n */\n private Byte flag;\n\n /**\n * job priority\n */\n private Byte taskPriority;\n\n /**\n * worker grouping\n */\n private String workerGroup;\n\n /**\n * environment code\n */\n private Long environmentCode;\n\n /**\n * number of failed retries\n */\n private Integer failRetryTimes;\n\n /**\n * failed retry interval\n */\n private Integer failRetryInterval;\n\n /**\n * timeout flag:0 close, 1 open\n */\n private Byte timeoutFlag;\n\n /**\n * timeout notification policy: 0 warning, 1 fail\n */\n private Byte timeoutNotifyStrategy;\n\n /**\n * timeout length,unit: minute\n */\n private Integer timeout;\n\n /**\n * delay execution time,unit: minute\n */\n private Integer delayTime;\n\n /**\n * resource id, separated by comma\n */\n private String resourceIds;\n\n /**\n * create time\n */\n private Date createTime;\n\n /**\n * update time\n */\n private Date updateTime;\n\n @TableField(exist = false)\n private String taskSql; // 任务SQL\n}"
},
{
"identifier": "TDsTaskInstance",
"path": "data-governance-assessment/src/main/java/com/std/dga/dolphinscheduler/bean/TDsTaskInstance.java",
"snippet": "@Data\n@TableName(\"t_ds_task_instance\")\npublic class TDsTaskInstance implements Serializable {\n\n private static final long serialVersionUID = 1L;\n\n /**\n * key\n */\n @TableId(value = \"id\", type = IdType.AUTO)\n private Integer id;\n\n /**\n * task name\n */\n private String name;\n\n /**\n * task type\n */\n private String taskType;\n\n /**\n * task definition code\n */\n private Long taskCode;\n\n /**\n * task definition version\n */\n private Integer taskDefinitionVersion;\n\n /**\n * process instance id\n */\n private Integer processInstanceId;\n\n /**\n * Status: 0 commit succeeded, 1 running, 2 prepare to pause, 3 pause, 4 prepare to stop, 5 stop, 6 fail, 7 succeed, 8 need fault tolerance, 9 kill, 10 wait for thread, 11 wait for dependency to complete\n */\n private Byte state;\n\n /**\n * task submit time\n */\n private Date submitTime;\n\n /**\n * task start time\n */\n private Date startTime;\n\n /**\n * task end time\n */\n private Date endTime;\n\n /**\n * host of task running on\n */\n private String host;\n\n /**\n * task execute path in the host\n */\n private String executePath;\n\n /**\n * task log path\n */\n private String logPath;\n\n /**\n * whether alert\n */\n private Byte alertFlag;\n\n /**\n * task retry times\n */\n private Integer retryTimes;\n\n /**\n * pid of task\n */\n private Integer pid;\n\n /**\n * yarn app id\n */\n private String appLink;\n\n /**\n * job custom parameters\n */\n private String taskParams;\n\n /**\n * 0 not available, 1 available\n */\n private Byte flag;\n\n /**\n * retry interval when task failed \n */\n private Integer retryInterval;\n\n /**\n * max retry times\n */\n private Integer maxRetryTimes;\n\n /**\n * task instance priority:0 Highest,1 High,2 Medium,3 Low,4 Lowest\n */\n private Integer taskInstancePriority;\n\n /**\n * worker group id\n */\n private String workerGroup;\n\n /**\n * environment code\n */\n private Long environmentCode;\n\n /**\n * this config contains many environment variables config\n */\n private String environmentConfig;\n\n private Integer executorId;\n\n /**\n * task first submit time\n */\n private Date firstSubmitTime;\n\n /**\n * task delay execution time\n */\n private Integer delayTime;\n\n /**\n * var_pool\n */\n private String varPool;\n\n /**\n * dry run flag: 0 normal, 1 dry run\n */\n private Byte dryRun;\n}"
},
{
"identifier": "TableMetaInfo",
"path": "data-governance-assessment/src/main/java/com/std/dga/meta/bean/TableMetaInfo.java",
"snippet": "@Data\n@TableName(\"table_meta_info\")\npublic class TableMetaInfo implements Serializable {\n\n private static final long serialVersionUID = 1L;\n\n /**\n * 表id\n */\n @TableId(value = \"id\", type = IdType.AUTO)\n private Long id;\n\n /**\n * 表名\n */\n private String tableName;\n\n /**\n * 库名\n */\n private String schemaName;\n\n /**\n * 字段名json ( 来源:hive)\n */\n private String colNameJson;\n\n /**\n * 分区字段名json( 来源:hive)\n */\n private String partitionColNameJson;\n\n /**\n * hdfs所属人 ( 来源:hive)\n */\n private String tableFsOwner;\n\n /**\n * 参数信息 ( 来源:hive)\n */\n private String tableParametersJson;\n\n /**\n * 表备注 ( 来源:hive)\n */\n private String tableComment;\n\n /**\n * hdfs路径 ( 来源:hive)\n */\n private String tableFsPath;\n\n /**\n * 输入格式( 来源:hive)\n */\n private String tableInputFormat;\n\n /**\n * 输出格式 ( 来源:hive)\n */\n private String tableOutputFormat;\n\n /**\n * 行格式 ( 来源:hive)\n */\n private String tableRowFormatSerde;\n\n /**\n * 表创建时间 ( 来源:hive)\n */\n private Date tableCreateTime;\n\n /**\n * 表类型 ( 来源:hive)\n */\n private String tableType;\n\n /**\n * 分桶列 ( 来源:hive)\n */\n private String tableBucketColsJson;\n\n /**\n * 分桶个数 ( 来源:hive)\n */\n private Long tableBucketNum;\n\n /**\n * 排序列 ( 来源:hive)\n */\n private String tableSortColsJson;\n\n /**\n * 数据量大小 ( 来源:hdfs)\n */\n private Long tableSize=0L;\n\n /**\n * 所有副本数据总量大小 ( 来源:hdfs)\n */\n private Long tableTotalSize=0L;\n\n /**\n * 最后修改时间 ( 来源:hdfs)\n */\n private Date tableLastModifyTime;\n\n /**\n * 最后访问时间 ( 来源:hdfs)\n */\n private Date tableLastAccessTime;\n\n /**\n * 当前文件系统容量 ( 来源:hdfs)\n */\n private Long fsCapcitySize;\n\n /**\n * 当前文件系统使用量 ( 来源:hdfs)\n */\n private Long fsUsedSize;\n\n /**\n * 当前文件系统剩余量 ( 来源:hdfs)\n */\n private Long fsRemainSize;\n\n /**\n * 考评日期 \n */\n private String assessDate;\n\n /**\n * 创建时间 (自动生成)\n */\n private Date createTime;\n\n /**\n * 更新时间 (自动生成)\n */\n private Date updateTime;\n\n\n /**\n * 额外辅助信息\n */\n @TableField(exist = false)\n private TableMetaInfoExtra tableMetaInfoExtra;\n\n}"
}
] | import com.std.dga.dolphinscheduler.bean.TDsTaskDefinition;
import com.std.dga.dolphinscheduler.bean.TDsTaskInstance;
import com.std.dga.meta.bean.TableMetaInfo;
import lombok.Data;
import java.util.List;
import java.util.Map; | 2,478 | package com.std.dga.governance.bean;
/**
* ClassName:AssessParam
* Description:
*
* @date:2023/10/10 16:31
* @author:STD
*/
@Data
public class AssessParam {
private String assessDate ; | package com.std.dga.governance.bean;
/**
* ClassName:AssessParam
* Description:
*
* @date:2023/10/10 16:31
* @author:STD
*/
@Data
public class AssessParam {
private String assessDate ; | private TableMetaInfo tableMetaInfo ; | 2 | 2023-10-20 10:13:43+00:00 | 4k |
Jirkaach1/WooMinecraft-offline-support | src/main/java/com/plugish/woominecraft/WooMinecraft.java | [
{
"identifier": "Order",
"path": "src/main/java/com/plugish/woominecraft/pojo/Order.java",
"snippet": "public class Order {\r\n\r\n\t@SerializedName(\"player\")\r\n\t@Expose\r\n\tprivate String player;\r\n\t@SerializedName(\"order_id\")\r\n\t@Expose\r\n\tprivate Integer orderId;\r\n\t@SerializedName(\"commands\")\r\n\t@Expose\r\n\tprivate List<String> commands = null;\r\n\r\n\tpublic String getPlayer() {\r\n\t\treturn player;\r\n\t}\r\n\r\n\tpublic void setPlayer(String player) {\r\n\t\tthis.player = player;\r\n\t}\r\n\r\n\tpublic Order withPlayer(String player) {\r\n\t\tthis.player = player;\r\n\t\treturn this;\r\n\t}\r\n\r\n\tpublic Integer getOrderId() {\r\n\t\treturn orderId;\r\n\t}\r\n\r\n\tpublic void setOrderId(Integer orderId) {\r\n\t\tthis.orderId = orderId;\r\n\t}\r\n\r\n\tpublic Order withOrderId(Integer orderId) {\r\n\t\tthis.orderId = orderId;\r\n\t\treturn this;\r\n\t}\r\n\r\n\tpublic List<String> getCommands() {\r\n\t\treturn commands;\r\n\t}\r\n\r\n\tpublic void setCommands(List<String> commands) {\r\n\t\tthis.commands = commands;\r\n\t}\r\n\r\n\tpublic Order withCommands(List<String> commands) {\r\n\t\tthis.commands = commands;\r\n\t\treturn this;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic String toString() {\r\n\t\treturn new ToStringBuilder(this).append(\"player\", player).append(\"orderId\", orderId).append(\"commands\", commands).toString();\r\n\t}\r\n\r\n}"
},
{
"identifier": "WMCPojo",
"path": "src/main/java/com/plugish/woominecraft/pojo/WMCPojo.java",
"snippet": "public class WMCPojo {\r\n\r\n\t@SerializedName(\"code\")\r\n\t@Expose\r\n\tprivate String code;\r\n\t@SerializedName(\"message\")\r\n\t@Expose\r\n\tprivate String message;\r\n\t@SerializedName(\"data\")\r\n\t@Expose\r\n\tprivate Data data;\r\n\t@SerializedName(\"orders\")\r\n\t@Expose\r\n\tprivate List<Order> orders = null;\r\n\r\n\tpublic String getCode() {\r\n\t\treturn code;\r\n\t}\r\n\r\n\tpublic void setCode(String code) {\r\n\t\tthis.code = code;\r\n\t}\r\n\r\n\tpublic WMCPojo withCode(String code) {\r\n\t\tthis.code = code;\r\n\t\treturn this;\r\n\t}\r\n\r\n\tpublic String getMessage() {\r\n\t\treturn message;\r\n\t}\r\n\r\n\tpublic void setMessage(String message) {\r\n\t\tthis.message = message;\r\n\t}\r\n\r\n\tpublic WMCPojo withMessage(String message) {\r\n\t\tthis.message = message;\r\n\t\treturn this;\r\n\t}\r\n\r\n\tpublic Data getData() {\r\n\t\treturn data;\r\n\t}\r\n\r\n\tpublic void setData(Data data) {\r\n\t\tthis.data = data;\r\n\t}\r\n\r\n\tpublic WMCPojo withData(Data data) {\r\n\t\tthis.data = data;\r\n\t\treturn this;\r\n\t}\r\n\r\n\tpublic List<Order> getOrders() {\r\n\t\treturn orders;\r\n\t}\r\n\r\n\tpublic void setOrders(List<Order> orders) {\r\n\t\tthis.orders = orders;\r\n\t}\r\n\r\n\tpublic WMCPojo withOrders(List<Order> orders) {\r\n\t\tthis.orders = orders;\r\n\t\treturn this;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic String toString() {\r\n\t\treturn new ToStringBuilder(this).append(\"code\", code).append(\"message\", message).append(\"data\", data).append(\"orders\", orders).toString();\r\n\t}\r\n\r\n}"
},
{
"identifier": "WMCProcessedOrders",
"path": "src/main/java/com/plugish/woominecraft/pojo/WMCProcessedOrders.java",
"snippet": "public class WMCProcessedOrders {\r\n\r\n\t@SerializedName(\"processedOrders\")\r\n\t@Expose\r\n\tprivate List<Integer> processedOrders = null;\r\n\r\n\tpublic List<Integer> getProcessedOrders() {\r\n\t\treturn processedOrders;\r\n\t}\r\n\r\n\tpublic void setProcessedOrders(List<Integer> processedOrders) {\r\n\t\tthis.processedOrders = processedOrders;\r\n\t}\r\n\r\n\tpublic WMCProcessedOrders withProcessedOrders(List<Integer> processedOrders) {\r\n\t\tthis.processedOrders = processedOrders;\r\n\t\treturn this;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic String toString() {\r\n\t\treturn new ToStringBuilder(this).append(\"processedOrders\", processedOrders).toString();\r\n\t}\r\n\r\n}"
}
] | import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.plugish.woominecraft.pojo.Order;
import com.plugish.woominecraft.pojo.WMCPojo;
import com.plugish.woominecraft.pojo.WMCProcessedOrders;
import okhttp3.*;
import org.bukkit.Bukkit;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitScheduler;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.io.*;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import org.bukkit.ChatColor;
import org.bukkit.Sound;
| 2,395 |
package com.plugish.woominecraft;
public final class WooMinecraft extends JavaPlugin {
static WooMinecraft instance;
private YamlConfiguration l10n;
public YamlConfiguration logConfig;
private File logFile;
public static final String NL = System.getProperty("line.separator");
/**
* Stores the player data to prevent double checks.
* <p>
* i.e. name:true|false
*/
private List<String> PlayersMap = new ArrayList<>();
@Override
public void onEnable() {
instance = this;
String asciiArt =
" \n" +
" \n" +
" \n" +
" _ __ __ __ ______ ____ ____ ______\n" +
" | | / / ____ ____ / // / / ____/ __ __ ____ / __ \\ / __ \\ / ____/\n" +
" | | /| / / / __ \\ / __ \\ / // /_ / /_ / / / / / __ \\ / /_/ / / /_/ / / / __ \n" +
" | |/ |/ / / /_/ // /_/ //__ __/ / __/ / /_/ / / / / / / _, _/ / ____/ / /_/ / \n" +
" |__/|__/ \\____/ \\____/ /_/ /_/ \\__,_/ /_/ /_/ /_/ |_| /_/ \\____/\n"
+ " \n"
+ " \n"
+ " \n";
getLogger().info(asciiArt);
this.logFile = new File(this.getDataFolder(), "log.yml");
this.logConfig = YamlConfiguration.loadConfiguration(logFile);
if (this.logConfig != null) {
this.logConfig.set("loggingEnabled", true);
try {
this.logConfig.save(this.logFile);
} catch (IOException e) {
e.printStackTrace();
}
}
YamlConfiguration config = (YamlConfiguration) getConfig();
try {
saveDefaultConfig();
} catch (IllegalArgumentException e) {
getLogger().warning(e.getMessage());
}
String lang = getConfig().getString("lang");
if (lang == null) {
getLogger().warning("No default l10n set, setting to English.");
}
// Load the commands.
getCommand("woo").setExecutor(new WooCommand());
// Log when the plugin is initialized.
getLogger().info(this.getLang("log.com_init"));
BukkitRunner scheduler = new BukkitRunner(instance);
scheduler.runTaskTimerAsynchronously(instance, config.getInt( "update_interval" ) * 20, config.getInt( "update_interval" ) * 20 );
// Log when the plugin is fully enabled (setup complete).
getLogger().info(this.getLang("log.enabled"));
}
@Override
public void onDisable() {
// Disable logging on plugin shutdown
if (this.logConfig != null) {
this.logConfig.set("loggingEnabled", false);
try {
this.logConfig.save(this.logFile);
} catch (IOException e) {
e.printStackTrace();
}
}
// Log when the plugin is fully shut down.
getLogger().info(this.getLang("log.com_init"));
}
// Helper method to get localized strings
String getLang(String path) {
if (null == this.l10n) {
LangSetup lang = new LangSetup(instance);
l10n = lang.loadConfig();
}
return this.l10n.getString(path);
}
// Validates the basics needed in the config.yml file.
private void validateConfig() throws Exception {
if (1 > this.getConfig().getString("url").length()) {
throw new Exception("Server URL is empty, check config.");
} else if (this.getConfig().getString("url").equals("http://playground.dev")) {
throw new Exception("URL is still the default URL, check config.");
} else if (1 > this.getConfig().getString("key").length()) {
throw new Exception("Server Key is empty, this is insecure, check config.");
}
}
// Gets the site URL
public URL getSiteURL() throws Exception {
boolean usePrettyPermalinks = this.getConfig().getBoolean("prettyPermalinks");
String baseUrl = getConfig().getString("url") + "/wp-json/wmc/v1/server/";
if (!usePrettyPermalinks) {
baseUrl = getConfig().getString("url") + "/index.php?rest_route=/wmc/v1/server/";
String customRestUrl = this.getConfig().getString("restBasePath");
if (!customRestUrl.isEmpty()) {
baseUrl = customRestUrl;
}
}
debug_log("Checking base URL: " + baseUrl);
return new URL(baseUrl + getConfig().getString("key"));
}
// Checks all online players against the website's database looking for pending donation deliveries
boolean check() throws Exception {
// Make 100% sure the config has at least a key and url
this.validateConfig();
// Contact the server.
String pendingOrders = getPendingOrders();
debug_log("Logging website reply" + NL + pendingOrders.substring(0, Math.min(pendingOrders.length(), 64)) + "...");
// Server returned an empty response, bail here.
if (pendingOrders.isEmpty()) {
debug_log("Pending orders are completely empty", 2);
return false;
}
// Create a new object from JSON response.
Gson gson = new GsonBuilder().create();
|
package com.plugish.woominecraft;
public final class WooMinecraft extends JavaPlugin {
static WooMinecraft instance;
private YamlConfiguration l10n;
public YamlConfiguration logConfig;
private File logFile;
public static final String NL = System.getProperty("line.separator");
/**
* Stores the player data to prevent double checks.
* <p>
* i.e. name:true|false
*/
private List<String> PlayersMap = new ArrayList<>();
@Override
public void onEnable() {
instance = this;
String asciiArt =
" \n" +
" \n" +
" \n" +
" _ __ __ __ ______ ____ ____ ______\n" +
" | | / / ____ ____ / // / / ____/ __ __ ____ / __ \\ / __ \\ / ____/\n" +
" | | /| / / / __ \\ / __ \\ / // /_ / /_ / / / / / __ \\ / /_/ / / /_/ / / / __ \n" +
" | |/ |/ / / /_/ // /_/ //__ __/ / __/ / /_/ / / / / / / _, _/ / ____/ / /_/ / \n" +
" |__/|__/ \\____/ \\____/ /_/ /_/ \\__,_/ /_/ /_/ /_/ |_| /_/ \\____/\n"
+ " \n"
+ " \n"
+ " \n";
getLogger().info(asciiArt);
this.logFile = new File(this.getDataFolder(), "log.yml");
this.logConfig = YamlConfiguration.loadConfiguration(logFile);
if (this.logConfig != null) {
this.logConfig.set("loggingEnabled", true);
try {
this.logConfig.save(this.logFile);
} catch (IOException e) {
e.printStackTrace();
}
}
YamlConfiguration config = (YamlConfiguration) getConfig();
try {
saveDefaultConfig();
} catch (IllegalArgumentException e) {
getLogger().warning(e.getMessage());
}
String lang = getConfig().getString("lang");
if (lang == null) {
getLogger().warning("No default l10n set, setting to English.");
}
// Load the commands.
getCommand("woo").setExecutor(new WooCommand());
// Log when the plugin is initialized.
getLogger().info(this.getLang("log.com_init"));
BukkitRunner scheduler = new BukkitRunner(instance);
scheduler.runTaskTimerAsynchronously(instance, config.getInt( "update_interval" ) * 20, config.getInt( "update_interval" ) * 20 );
// Log when the plugin is fully enabled (setup complete).
getLogger().info(this.getLang("log.enabled"));
}
@Override
public void onDisable() {
// Disable logging on plugin shutdown
if (this.logConfig != null) {
this.logConfig.set("loggingEnabled", false);
try {
this.logConfig.save(this.logFile);
} catch (IOException e) {
e.printStackTrace();
}
}
// Log when the plugin is fully shut down.
getLogger().info(this.getLang("log.com_init"));
}
// Helper method to get localized strings
String getLang(String path) {
if (null == this.l10n) {
LangSetup lang = new LangSetup(instance);
l10n = lang.loadConfig();
}
return this.l10n.getString(path);
}
// Validates the basics needed in the config.yml file.
private void validateConfig() throws Exception {
if (1 > this.getConfig().getString("url").length()) {
throw new Exception("Server URL is empty, check config.");
} else if (this.getConfig().getString("url").equals("http://playground.dev")) {
throw new Exception("URL is still the default URL, check config.");
} else if (1 > this.getConfig().getString("key").length()) {
throw new Exception("Server Key is empty, this is insecure, check config.");
}
}
// Gets the site URL
public URL getSiteURL() throws Exception {
boolean usePrettyPermalinks = this.getConfig().getBoolean("prettyPermalinks");
String baseUrl = getConfig().getString("url") + "/wp-json/wmc/v1/server/";
if (!usePrettyPermalinks) {
baseUrl = getConfig().getString("url") + "/index.php?rest_route=/wmc/v1/server/";
String customRestUrl = this.getConfig().getString("restBasePath");
if (!customRestUrl.isEmpty()) {
baseUrl = customRestUrl;
}
}
debug_log("Checking base URL: " + baseUrl);
return new URL(baseUrl + getConfig().getString("key"));
}
// Checks all online players against the website's database looking for pending donation deliveries
boolean check() throws Exception {
// Make 100% sure the config has at least a key and url
this.validateConfig();
// Contact the server.
String pendingOrders = getPendingOrders();
debug_log("Logging website reply" + NL + pendingOrders.substring(0, Math.min(pendingOrders.length(), 64)) + "...");
// Server returned an empty response, bail here.
if (pendingOrders.isEmpty()) {
debug_log("Pending orders are completely empty", 2);
return false;
}
// Create a new object from JSON response.
Gson gson = new GsonBuilder().create();
| WMCPojo wmcPojo = gson.fromJson(pendingOrders, WMCPojo.class);
| 1 | 2023-10-17 12:56:44+00:00 | 4k |
RaulGB88/MOD-034-Microservicios-con-Java | REM20231023/demo/src/main/java/com/example/application/resources/CotillaResource.java | [
{
"identifier": "ActoresProxy",
"path": "REM20231023/demo/src/main/java/com/example/application/proxies/ActoresProxy.java",
"snippet": "public interface ActoresProxy {\n\tpublic record ActorShort(@JsonProperty(\"actorId\") int id, @Schema(description = \"Nombre del actor\") String nombre) {}\n\tpublic record ActorEdit(int id, String nombre, String apellidos) {}\n\t\n\t@GetExchange\n\tList<ActorShort> getAll();\n\t@GetExchange(\"/{id}\")\n\tActorEdit getOne(@PathVariable int id);\n\t@PostExchange\n\tResponseEntity<ActorEdit> add(@RequestBody ActorEdit item);\n\t@PutExchange(\"/{id}\")\n\tvoid change(@PathVariable int id, @RequestBody ActorEdit item);\n\t@DeleteExchange(\"/{id}\")\n\tvoid delete(@PathVariable int id);\n}"
},
{
"identifier": "CatalogoProxy",
"path": "REM20231023/demo/src/main/java/com/example/application/proxies/CatalogoProxy.java",
"snippet": "@FeignClient(name = \"CATALOGO-SERVICE\" /*, url = \"http://localhost:8010\"*/)\npublic interface CatalogoProxy {\n\t@GetMapping(path = \"/\")\n\tString getCatalogo();\n\t\n\t@GetMapping(path = \"/actuator/info\")\n\tString getInfo();\n\t\n\t@GetMapping(path = \"/peliculas/v1?mode=short\")\n\tList<PelisDto> getPelis();\n\t@GetMapping(path = \"/peliculas/v1?mode=details\")\n\tList<PelisDto> getPelisConDetalle();\n\t\n\t@GetMapping(path = \"/peliculas/v1/{id}?mode=short\")\n\tPelisDto getPeli(@PathVariable int id);\n\t\n\t@PostMapping(path = \"/peliculas/v1/{id}/like\")\n\tString meGusta(@PathVariable int id);\n\t@PostMapping(path = \"/peliculas/v1/{id}/like\")\n\tString meGusta(@PathVariable int id, @RequestHeader(value = \"Authorization\", required = true) String authorization);\n}"
},
{
"identifier": "PhotoProxy",
"path": "REM20231023/demo/src/main/java/com/example/application/proxies/PhotoProxy.java",
"snippet": "@FeignClient(name=\"photos\", url=\"https://picsum.photos\")\npublic interface PhotoProxy {\n @GetMapping(value = \"/v2/list?limit=1000\", consumes = {\"application/json\"})\n List<PhotoDTO> getAll();\n @GetMapping(\"/id/{id}/info\")\n PhotoDTO getOne(@PathVariable int id);\n \n @PostMapping(path = \"/photos\", consumes = { \"application/json\"} )\n void send(@RequestBody PhotoDTO item);\n}"
},
{
"identifier": "PelisDto",
"path": "REM20231023/demo/src/main/java/com/example/domains/entities/dtos/PelisDto.java",
"snippet": "@Data\npublic class PelisDto {\n private int filmId;\n private String title;\n}"
},
{
"identifier": "PhotoDTO",
"path": "REM20231023/demo/src/main/java/com/example/domains/entities/dtos/PhotoDTO.java",
"snippet": "@Data\npublic class PhotoDTO {\n\tprivate String id, author, url, download_url;\n\tprivate int width, height;\n}"
}
] | import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.circuitbreaker.CircuitBreakerFactory;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
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.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.HttpServerErrorException;
import org.springframework.web.client.RestTemplate;
import com.example.application.proxies.ActoresProxy;
import com.example.application.proxies.ActoresProxy.ActorEdit;
import com.example.application.proxies.ActoresProxy.ActorShort;
import com.example.application.proxies.CatalogoProxy;
import com.example.application.proxies.PhotoProxy;
import com.example.domains.entities.dtos.PelisDto;
import com.example.domains.entities.dtos.PhotoDTO;
import com.netflix.appinfo.InstanceInfo;
import com.netflix.discovery.EurekaClient;
import io.github.resilience4j.bulkhead.annotation.Bulkhead;
import io.github.resilience4j.circuitbreaker.CallNotPermittedException;
import io.github.resilience4j.circuitbreaker.annotation.CircuitBreaker;
import io.micrometer.observation.annotation.Observed;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.security.SecurityRequirement; | 2,640 | rslt.add("Final: " + fin + " (" + inicio.until(fin, ChronoUnit.MILLIS) + " ms)");
return rslt;
}
@GetMapping(path = "/pelis/rt")
public List<PelisDto> getPelisRT() {
// ResponseEntity<List<PelisDto>> response = srv.exchange(
// "http://localhost:8010/peliculas/v1?mode=short",
ResponseEntity<List<PelisDto>> response = srvLB.exchange(
"lb://CATALOGO-SERVICE/peliculas/v1?mode=short",
HttpMethod.GET,
HttpEntity.EMPTY,
new ParameterizedTypeReference<List<PelisDto>>() {}
);
return response.getBody();
}
@GetMapping(path = "/pelis/{id}/rt")
public PelisDto getPelisRT(@PathVariable int id) {
return srvLB.getForObject("lb://CATALOGO-SERVICE/peliculas/v1/{key}?mode=short", PelisDto.class, id);
// return srv.getForObject("http://localhost:8010/peliculas/v1/{key}?mode=short", PelisDto.class, id);
}
@Autowired
CatalogoProxy proxy;
@GetMapping(path = "/balancea/proxy")
public List<String> getBalanceoProxy() {
List<String> rslt = new ArrayList<>();
for(int i = 0; i < 11; i++)
try {
rslt.add(proxy.getInfo());
} catch (Exception e) {
rslt.add(e.getMessage());
}
return rslt;
}
@GetMapping(path = "/pelis/proxy")
public List<PelisDto> getPelisProxy() {
return proxy.getPelis();
}
// @PreAuthorize("hasRole('ADMINISTRADORES')")
@SecurityRequirement(name = "bearerAuth")
@GetMapping(path = "/pelis/{id}/proxy")
public PelisDto getPelisProxy(@PathVariable int id) {
return proxy.getPeli(id);
}
@Autowired
private CircuitBreakerFactory cbFactory;
@GetMapping(path = "/circuit-breaker/factory")
public List<String> getCircuitBreakerFactory() {
List<String> rslt = new ArrayList<>();
LocalDateTime inicio = LocalDateTime.now();
rslt.add("Inicio: " + inicio);
for(int i = 0; i < 100; i++) {
LocalTime ini = LocalTime.now();
rslt.add(cbFactory.create("slow").run(
() -> srvLB.getForObject("lb://CATALOGO-SERVICE/actuator/info", String.class),
throwable -> "fallback: circuito abierto")
+ " (" + ini.until(LocalTime.now(), ChronoUnit.MILLIS) + " .ms)" );
}
LocalDateTime fin = LocalDateTime.now();
rslt.add("Final: " + fin + " (" + inicio.until(fin, ChronoUnit.MILLIS) + " ms)");
return rslt;
}
@GetMapping(path = "/circuit-breaker/anota")
@CircuitBreaker(name = "default", fallbackMethod = "fallback")
public List<String> getCircuitBreakerAnota() {
List<String> rslt = new ArrayList<>();
LocalDateTime inicio = LocalDateTime.now();
rslt.add("Inicio: " + inicio);
for(int i = 0; i < 100; i++)
rslt.add(getInfo(LocalTime.now()));
LocalDateTime fin = LocalDateTime.now();
rslt.add("Final: " + fin + " (" + inicio.until(fin, ChronoUnit.MILLIS) + " ms)");
return rslt;
}
@CircuitBreaker(name = "default", fallbackMethod = "fallback")
private String getInfo(LocalTime ini) {
return srvLB.getForObject("lb://CATALOGO-SERVICE/loteria", String.class)
+ " (" + ini.until(LocalTime.now(), ChronoUnit.MILLIS) + " ms)";
// return srv.getForObject("http://localhost:8010/actuator/info", String.class)
// + " (" + ini.until(LocalTime.now(), ChronoUnit.MILLIS) + " ms)";
// return srvLB.getForObject("lb://CATALOGO-SERVICE/actuator/info", String.class)
// + " (" + ini.until(LocalTime.now(), ChronoUnit.MILLIS) + " ms)";
}
private List<String> fallback(CallNotPermittedException e) {
return List.of("CircuitBreaker is open", e.getCausingCircuitBreakerName(), e.getLocalizedMessage());
}
private String fallback(LocalTime ini, CallNotPermittedException e) {
return "CircuitBreaker is open";
}
private String fallback(LocalTime ini, Exception e) {
return "Fallback: " + e.getMessage()
+ " (" + ini.until(LocalTime.now(), ChronoUnit.MILLIS) + " ms)";
}
// @org.springframework.beans.factory.annotation.Value("${server.port}")
// int port;
//
// @GetMapping(path = "/loteria", produces = {"text/plain"})
// public String getIntento() {
// if(port == 8011)
// throw new HttpServerErrorException(HttpStatusCode.valueOf(500));
// return "OK " + port;
// }
@Value("${valor.ejemplo:Valor por defecto}")
String config;
@GetMapping(path = "/config", produces = {"text/plain"})
public String getConfig() {
return config;
}
@Autowired | package com.example.application.resources;
/**
* Ejemplos de conexiones
* @author Javier
*
*/
@Observed
@RefreshScope
@RestController
@RequestMapping(path = "/cotilla")
public class CotillaResource {
@Autowired
RestTemplate srv;
@Autowired
@LoadBalanced
RestTemplate srvLB;
@Autowired
private EurekaClient discoveryEurekaClient;
@GetMapping(path = "/descubre/eureka/{nombre}")
public InstanceInfo serviceEurekaUrl(String nombre) {
InstanceInfo instance = discoveryEurekaClient.getNextServerFromEureka(nombre, false);
return instance; //.getHomePageUrl();
}
@Autowired
private DiscoveryClient discoveryClient;
@GetMapping(path = "/descubre/cloud/{nombre}")
public List<ServiceInstance> serviceUrl(String nombre) {
return discoveryClient.getInstances(nombre);
}
@GetMapping(path = "/balancea/rt")
@SecurityRequirement(name = "bearerAuth")
// @PreAuthorize("hasRole('ROLE_ADMINISTRADORES')")
public List<String> getBalanceoRT() {
List<String> rslt = new ArrayList<>();
LocalDateTime inicio = LocalDateTime.now();
rslt.add("Inicio: " + inicio);
for(int i = 0; i < 11; i++)
try {
LocalTime ini = LocalTime.now();
rslt.add(srvLB.getForObject("lb://CATALOGO-SERVICE/actuator/info", String.class)
+ " (" + ini.until(LocalTime.now(), ChronoUnit.MILLIS) + " ms)" );
} catch (Exception e) {
rslt.add(e.getMessage());
}
LocalDateTime fin = LocalDateTime.now();
rslt.add("Final: " + fin + " (" + inicio.until(fin, ChronoUnit.MILLIS) + " ms)");
return rslt;
}
@GetMapping(path = "/pelis/rt")
public List<PelisDto> getPelisRT() {
// ResponseEntity<List<PelisDto>> response = srv.exchange(
// "http://localhost:8010/peliculas/v1?mode=short",
ResponseEntity<List<PelisDto>> response = srvLB.exchange(
"lb://CATALOGO-SERVICE/peliculas/v1?mode=short",
HttpMethod.GET,
HttpEntity.EMPTY,
new ParameterizedTypeReference<List<PelisDto>>() {}
);
return response.getBody();
}
@GetMapping(path = "/pelis/{id}/rt")
public PelisDto getPelisRT(@PathVariable int id) {
return srvLB.getForObject("lb://CATALOGO-SERVICE/peliculas/v1/{key}?mode=short", PelisDto.class, id);
// return srv.getForObject("http://localhost:8010/peliculas/v1/{key}?mode=short", PelisDto.class, id);
}
@Autowired
CatalogoProxy proxy;
@GetMapping(path = "/balancea/proxy")
public List<String> getBalanceoProxy() {
List<String> rslt = new ArrayList<>();
for(int i = 0; i < 11; i++)
try {
rslt.add(proxy.getInfo());
} catch (Exception e) {
rslt.add(e.getMessage());
}
return rslt;
}
@GetMapping(path = "/pelis/proxy")
public List<PelisDto> getPelisProxy() {
return proxy.getPelis();
}
// @PreAuthorize("hasRole('ADMINISTRADORES')")
@SecurityRequirement(name = "bearerAuth")
@GetMapping(path = "/pelis/{id}/proxy")
public PelisDto getPelisProxy(@PathVariable int id) {
return proxy.getPeli(id);
}
@Autowired
private CircuitBreakerFactory cbFactory;
@GetMapping(path = "/circuit-breaker/factory")
public List<String> getCircuitBreakerFactory() {
List<String> rslt = new ArrayList<>();
LocalDateTime inicio = LocalDateTime.now();
rslt.add("Inicio: " + inicio);
for(int i = 0; i < 100; i++) {
LocalTime ini = LocalTime.now();
rslt.add(cbFactory.create("slow").run(
() -> srvLB.getForObject("lb://CATALOGO-SERVICE/actuator/info", String.class),
throwable -> "fallback: circuito abierto")
+ " (" + ini.until(LocalTime.now(), ChronoUnit.MILLIS) + " .ms)" );
}
LocalDateTime fin = LocalDateTime.now();
rslt.add("Final: " + fin + " (" + inicio.until(fin, ChronoUnit.MILLIS) + " ms)");
return rslt;
}
@GetMapping(path = "/circuit-breaker/anota")
@CircuitBreaker(name = "default", fallbackMethod = "fallback")
public List<String> getCircuitBreakerAnota() {
List<String> rslt = new ArrayList<>();
LocalDateTime inicio = LocalDateTime.now();
rslt.add("Inicio: " + inicio);
for(int i = 0; i < 100; i++)
rslt.add(getInfo(LocalTime.now()));
LocalDateTime fin = LocalDateTime.now();
rslt.add("Final: " + fin + " (" + inicio.until(fin, ChronoUnit.MILLIS) + " ms)");
return rslt;
}
@CircuitBreaker(name = "default", fallbackMethod = "fallback")
private String getInfo(LocalTime ini) {
return srvLB.getForObject("lb://CATALOGO-SERVICE/loteria", String.class)
+ " (" + ini.until(LocalTime.now(), ChronoUnit.MILLIS) + " ms)";
// return srv.getForObject("http://localhost:8010/actuator/info", String.class)
// + " (" + ini.until(LocalTime.now(), ChronoUnit.MILLIS) + " ms)";
// return srvLB.getForObject("lb://CATALOGO-SERVICE/actuator/info", String.class)
// + " (" + ini.until(LocalTime.now(), ChronoUnit.MILLIS) + " ms)";
}
private List<String> fallback(CallNotPermittedException e) {
return List.of("CircuitBreaker is open", e.getCausingCircuitBreakerName(), e.getLocalizedMessage());
}
private String fallback(LocalTime ini, CallNotPermittedException e) {
return "CircuitBreaker is open";
}
private String fallback(LocalTime ini, Exception e) {
return "Fallback: " + e.getMessage()
+ " (" + ini.until(LocalTime.now(), ChronoUnit.MILLIS) + " ms)";
}
// @org.springframework.beans.factory.annotation.Value("${server.port}")
// int port;
//
// @GetMapping(path = "/loteria", produces = {"text/plain"})
// public String getIntento() {
// if(port == 8011)
// throw new HttpServerErrorException(HttpStatusCode.valueOf(500));
// return "OK " + port;
// }
@Value("${valor.ejemplo:Valor por defecto}")
String config;
@GetMapping(path = "/config", produces = {"text/plain"})
public String getConfig() {
return config;
}
@Autowired | PhotoProxy proxyExterno; | 2 | 2023-10-24 14:35:15+00:00 | 4k |
Amir-UL-Islam/eTBManager3-Backend | src/main/java/org/msh/etbm/web/api/exceptions/ExceptionHandlingController.java | [
{
"identifier": "InvalidArgumentException",
"path": "src/main/java/org/msh/etbm/commons/InvalidArgumentException.java",
"snippet": "public class InvalidArgumentException extends RuntimeException {\n private final String property;\n private final String code;\n\n\n public InvalidArgumentException(String message) {\n super(message);\n this.property = null;\n this.code = null;\n }\n\n /**\n * Default constructor\n *\n * @param property invalid property name\n * @param message message to the user\n * @param code message error code, if available\n */\n public InvalidArgumentException(String property, String message, String code) {\n super(message);\n this.property = property;\n this.code = code;\n }\n\n /**\n * The invalid property name\n *\n * @return string value\n */\n public String getProperty() {\n return property;\n }\n\n /**\n * The error code, if available\n *\n * @return string value\n */\n public String getCode() {\n return code;\n }\n}"
},
{
"identifier": "Messages",
"path": "src/main/java/org/msh/etbm/commons/Messages.java",
"snippet": "@Component\npublic class Messages {\n\n private static final Logger LOGGER = LoggerFactory.getLogger(Messages.class);\n\n public static final String NOT_UNIQUE = \"NotUnique\";\n public static final String REQUIRED = \"NotNull\";\n public static final String NOT_NULL = \"NotNull\";\n public static final String NOT_VALID = \"NotValid\";\n public static final String NOT_VALID_EMAIL = \"NotValidEmail\";\n public static final String NOT_VALID_WORKSPACE = \"NotValidWorkspace\";\n public static final String NOT_UNIQUE_USER = \"NotUniqueUser\";\n public static final String NOT_VALID_OPTION = \"NotValidOption\";\n\n public static final String MAX_SIZE = \"javax.validation.constraints.Max.message\";\n public static final String MIN_SIZE = \"javax.validation.constraints.Min.message\";\n\n public static final String PERIOD_INIDATE_BEFORE = \"period.msgdt1\";\n\n public static final String UNDEFINED = \"global.notdef\";\n\n /**\n * keys in the message bundle to get information about date format in the selected locale\n */\n // convert from string to date\n public static final String LOCALE_DATE_FORMAT = \"locale.dateFormat\";\n // mask in editing control\n public static final String LOCALE_DATE_MASK = \"locale.dateMask\";\n // hint to be displayed as a place holder in date controls\n public static final String LOCALE_DATE_HINT = \"locale.dateHint\";\n // convert a date to a displayable string\n public static final String LOCALE_DISPLAY_DATE_FORMAT = \"locale.displayDateFormat\";\n\n\n /**\n * The pattern to get the keys to be replaced inside the string\n */\n public static final Pattern EXP_PATTERN = Pattern.compile(\"\\\\$\\\\{(.*?)\\\\}\");\n\n\n @Resource\n MessageSource messageSource;\n\n /**\n * Get the message by its key\n *\n * @param key the message key\n * @return the message to be displayed to the user\n */\n public String get(String key) {\n Locale locale = LocaleContextHolder.getLocale();\n try {\n return messageSource.getMessage(key, null, locale);\n } catch (NoSuchMessageException e) {\n LOGGER.info(\"No message found for \" + key + \" in the locale \" + locale.getDisplayName());\n return key;\n }\n }\n\n\n /**\n * Get the message using a message source resolvable object\n *\n * @param res instance of the MessageSourceResolvable interface containing the message\n * @return the string message\n */\n public String get(MessageSourceResolvable res) {\n Locale locale = LocaleContextHolder.getLocale();\n try {\n return messageSource.getMessage(res, locale);\n } catch (NoSuchMessageException e) {\n LOGGER.info(\"No message found for \" + res.getDefaultMessage() + \" in the locale \" + locale.getDisplayName());\n }\n return res.getDefaultMessage();\n }\n\n\n /**\n * Evaluate a string and replace message keys between ${key} by the message in the resource bundle file\n * @param text the string to be evaluated\n * @return the new evaluated string\n */\n public String eval(String text) {\n Matcher matcher = EXP_PATTERN.matcher(text);\n while (matcher.find()) {\n String s = matcher.group();\n String key = s.substring(2, s.length() - 1);\n\n text = text.replace(s, get(key));\n }\n\n return text;\n }\n\n\n /**\n * Get the message from the given key and process the arguments inside the message\n * @param msg\n * @param args\n * @return\n */\n public String format(String msg, Object... args) {\n Object[] dest = new Object[args.length];\n int index = 0;\n for (Object obj: args) {\n Object obj2 = obj instanceof Date ? dateToDisplay((Date)obj) : obj;\n dest[index++] = obj2;\n }\n\n return MessageFormat.format(msg, dest);\n }\n\n\n /**\n * Convert a date object to a displayable string\n * @param dt the date to be displayed\n * @return\n */\n public String dateToDisplay(Date dt) {\n Locale locale = LocaleContextHolder.getLocale();\n String pattern;\n try {\n pattern = messageSource.getMessage(LOCALE_DISPLAY_DATE_FORMAT, null, locale);\n } catch (NoSuchMessageException e) {\n LOGGER.info(\"Date format key in message bunldle not found for key \" + LOCALE_DISPLAY_DATE_FORMAT +\n \" in locale \" + locale.getDisplayName());\n pattern = \"dd-MMM-yyyy\";\n }\n\n SimpleDateFormat format = new SimpleDateFormat(pattern);\n return format.format(dt);\n }\n}"
},
{
"identifier": "ValidationException",
"path": "src/main/java/org/msh/etbm/commons/ValidationException.java",
"snippet": "public class ValidationException extends RuntimeException {\n\n private String code;\n private String message;\n\n /**\n * Constructor when there is just one single validation error message\n *\n * @param message\n * @param code\n */\n public ValidationException(String message, String code) {\n super(message);\n\n this.message = message;\n this.code = code;\n }\n\n @Override\n public String getMessage() {\n return message;\n }\n\n public String getCode() {\n return code;\n }\n}"
},
{
"identifier": "EntityValidationException",
"path": "src/main/java/org/msh/etbm/commons/entities/EntityValidationException.java",
"snippet": "public class EntityValidationException extends RuntimeException {\n\n private transient final Errors bindingResult;\n\n /**\n * Constructor when there is just one single validation error message\n *\n * @param field\n * @param message\n * @param code\n */\n public EntityValidationException(Object entity, String field, String message, String code) {\n super(message);\n\n this.bindingResult = new BeanPropertyBindingResult(entity, entity.getClass().getSimpleName());\n if (message != null) {\n this.bindingResult.reject(field, message);\n } else {\n this.bindingResult.rejectValue(field, code);\n }\n }\n\n /**\n * Constructor when there is just one single validation error message\n *\n * @param field\n * @param message\n * @param code\n */\n public EntityValidationException(Map entity, String field, String message, String code) {\n super(message);\n\n this.bindingResult = new MapBindingResult(entity, \"target\");\n if (message != null) {\n this.bindingResult.reject(field, message);\n } else {\n this.bindingResult.rejectValue(field, code);\n }\n }\n\n /**\n * Constructor when validation messages are already in the binding result object\n *\n * @param bindingResult instance of BindingResult object containing validation messages\n */\n public EntityValidationException(Errors bindingResult) {\n super();\n this.bindingResult = bindingResult;\n }\n\n public Errors getBindingResult() {\n return bindingResult;\n }\n\n @Override\n public String getMessage() {\n if (bindingResult == null) {\n return super.getMessage();\n }\n\n return bindingResult.toString();\n }\n}"
},
{
"identifier": "FormException",
"path": "src/main/java/org/msh/etbm/commons/forms/FormException.java",
"snippet": "public class FormException extends RuntimeException {\n\n public FormException(String message) {\n super(message);\n }\n\n public FormException(Throwable cause) {\n super(cause);\n }\n}"
},
{
"identifier": "ForbiddenException",
"path": "src/main/java/org/msh/etbm/services/security/ForbiddenException.java",
"snippet": "@ResponseStatus(HttpStatus.UNAUTHORIZED)\npublic class ForbiddenException extends RuntimeException {\n\n /**\n * Constructor where a message can be specified\n *\n * @param msg\n */\n public ForbiddenException(String msg) {\n super(msg);\n }\n\n /**\n * Default constructor\n */\n public ForbiddenException() {\n super();\n }\n}"
},
{
"identifier": "Message",
"path": "src/main/java/org/msh/etbm/web/api/Message.java",
"snippet": "public class Message {\n\n @JsonInclude(JsonInclude.Include.NON_NULL)\n private String field;\n\n @JsonInclude(JsonInclude.Include.NON_NULL)\n @JsonProperty(\"msg\")\n private String message;\n\n @JsonInclude(JsonInclude.Include.NON_NULL)\n private String code;\n\n\n public Message() {\n super();\n }\n\n public Message(String field, String message, String code) {\n this.field = field;\n this.message = message;\n this.code = code;\n }\n\n public Message(String message, String code) {\n this.message = message;\n this.code = code;\n }\n\n public String getField() {\n return field;\n }\n\n public void setField(String field) {\n this.field = field;\n }\n\n public String getMessage() {\n return message;\n }\n\n public void setMessage(String message) {\n this.message = message;\n }\n\n public String getCode() {\n return code;\n }\n\n public void setCode(String code) {\n this.code = code;\n }\n}"
},
{
"identifier": "StandardResult",
"path": "src/main/java/org/msh/etbm/web/api/StandardResult.java",
"snippet": "public class StandardResult {\n /**\n * Indicate if the request was succeeded (true) or failed (false)\n */\n private boolean success;\n\n /**\n * The specific result to be sent back (serialized) to the client\n */\n @JsonInclude(JsonInclude.Include.NON_NULL)\n private Object result;\n\n /**\n * The list of error messages, in case validation fails\n */\n @JsonInclude(JsonInclude.Include.NON_NULL)\n private List<Message> errors;\n\n\n public StandardResult() {\n super();\n }\n\n public StandardResult(ServiceResult res) {\n this.success = true;\n this.result = res.getId();\n }\n\n public StandardResult(Object res, List<Message> errors, boolean success) {\n this.result = res;\n this.errors = errors;\n this.success = success;\n }\n\n public boolean isSuccess() {\n return success;\n }\n\n public void setSuccess(boolean success) {\n this.success = success;\n }\n\n public Object getResult() {\n return result;\n }\n\n public void setResult(Object result) {\n this.result = result;\n }\n\n public List<Message> getErrors() {\n return errors;\n }\n\n public void setErrors(List<Message> errors) {\n this.errors = errors;\n }\n\n public static StandardResult createSuccessResult() {\n return new StandardResult(null, null, true);\n }\n}"
}
] | import org.msh.etbm.commons.InvalidArgumentException;
import org.msh.etbm.commons.Messages;
import org.msh.etbm.commons.ValidationException;
import org.msh.etbm.commons.entities.EntityValidationException;
import org.msh.etbm.commons.forms.FormException;
import org.msh.etbm.services.security.ForbiddenException;
import org.msh.etbm.web.api.Message;
import org.msh.etbm.web.api.StandardResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.Errors;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import javax.persistence.EntityNotFoundException;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List; | 3,092 | package org.msh.etbm.web.api.exceptions;
/**
* Exception handlers to display friendly and standard messages to the client
* <p>
* Created by rmemoria on 22/8/15.
*/
@ControllerAdvice
public class ExceptionHandlingController {
@Autowired | package org.msh.etbm.web.api.exceptions;
/**
* Exception handlers to display friendly and standard messages to the client
* <p>
* Created by rmemoria on 22/8/15.
*/
@ControllerAdvice
public class ExceptionHandlingController {
@Autowired | Messages messages; | 1 | 2023-10-23 13:47:54+00:00 | 4k |
2357457057/qy-rpc | src/main/java/top/yqingyu/rpc/consumer/ProxyClassMethodExecutor.java | [
{
"identifier": "Constants",
"path": "src/main/java/top/yqingyu/rpc/Constants.java",
"snippet": "public interface Constants {\n String method = \"@\";\n String param = \"#\";\n String parameterList = \"parameterList\";\n String invokeSuccess = \"0\";\n String invokeNoSuch = \"1\";\n String invokeThrowError = \"2\";\n String invokeResult = \"invokeResult\";\n String invokeErrorClass = \"invokeErrorClass\";\n String invokeErrorMessage = \"invokeErrorMessage\";\n String serviceIdentifierTag = \"serviceIdentifierTag\";\n //ms\n long authenticationWaitTime = 3000;\n String SpringCGLib = \"$$SpringCGLIB$$\";\n String JDK_PROXY = \"jdk.proxy\";\n String SpringCGLibRegx = \"[$]{2}SpringCGLIB[$]{2}\";\n\n List<String> specialMethod = Arrays.asList(\"toString\", \"hashcode\", \"equals\");\n\n String linkId = \"RPC_LINK_ID\";\n}"
},
{
"identifier": "RemoteServerException",
"path": "src/main/java/top/yqingyu/rpc/exception/RemoteServerException.java",
"snippet": "public class RemoteServerException extends QyRuntimeException {\n public RemoteServerException() {\n }\n\n public RemoteServerException(String message, Object... o) {\n super(message, o);\n }\n\n public RemoteServerException(Throwable cause, String message, Object... o) {\n super(cause, message, o);\n }\n\n public RemoteServerException(Throwable cause) {\n super(cause);\n }\n\n public RemoteServerException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace, Object... o) {\n super(message, cause, enableSuppression, writableStackTrace, o);\n }\n}"
},
{
"identifier": "RpcException",
"path": "src/main/java/top/yqingyu/rpc/exception/RpcException.java",
"snippet": "public class RpcException extends QyRuntimeException {\n public RpcException() {\n }\n\n public RpcException(String message, Object... o) {\n super(message, o);\n }\n\n public RpcException(Throwable cause, String message, Object... o) {\n super(cause, message, o);\n }\n\n public RpcException(Throwable cause) {\n super(cause);\n }\n\n public RpcException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace, Object... o) {\n super(message, cause, enableSuppression, writableStackTrace, o);\n }\n}"
},
{
"identifier": "RpcTimeOutException",
"path": "src/main/java/top/yqingyu/rpc/exception/RpcTimeOutException.java",
"snippet": "public class RpcTimeOutException extends QyRuntimeException {\n public RpcTimeOutException() {\n }\n\n public RpcTimeOutException(String message, Object... o) {\n super(message, o);\n }\n\n public RpcTimeOutException(Throwable cause, String message, Object... o) {\n super(cause, message, o);\n }\n\n public RpcTimeOutException(Throwable cause) {\n super(cause);\n }\n\n public RpcTimeOutException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace, Object... o) {\n super(message, cause, enableSuppression, writableStackTrace, o);\n }\n}"
},
{
"identifier": "RpcUtil",
"path": "src/main/java/top/yqingyu/rpc/util/RpcUtil.java",
"snippet": "public class RpcUtil {\n /**\n * 倘若该类实现的接口实现了某些接口,类名会选取与该对象全限定名最接近的接口的全限定名\n */\n public static String getClassName(Class<?> aClass) {\n String className = aClass.getName();\n if (aClass.isInterface()) {\n return className;\n }\n\n Class<?>[] interfaces = aClass.getInterfaces();\n Class<?> interface$ = null;\n String[] classNameS = className.split(\"[.]\");\n int sameMax = 0;\n\n for (Class<?> anInterface : interfaces) {\n String name = anInterface.getName();\n String[] split = name.split(\"[.]\");\n int min = Math.min(classNameS.length, split.length);\n for (int i = 0; i < min; i++) {\n if (!split[i].equals(classNameS[i])) {\n break;\n }\n if (i > sameMax) {\n sameMax = i;\n interface$ = anInterface;\n }\n }\n }\n if (interface$ != null) {\n className = interface$.getName();\n }\n return className;\n }\n\n public static ClassLoader getClassLoader(Class<?> c) {\n ClassLoader cl = c.getClassLoader();\n if (cl == null) {\n cl = DuplicatesPredicate.class.getClassLoader();\n }\n if (cl == null) {\n cl = Thread.currentThread().getContextClassLoader();\n }\n return cl;\n }\n}"
}
] | import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import top.yqingyu.common.cglib.proxy.MethodInterceptor;
import top.yqingyu.common.cglib.proxy.MethodProxy;
import top.yqingyu.common.qydata.DataMap;
import top.yqingyu.common.utils.StringUtil;
import top.yqingyu.qymsg.*;
import top.yqingyu.qymsg.netty.Connection;
import top.yqingyu.rpc.Constants;
import top.yqingyu.rpc.annontation.QyRpcProducerProperties;
import top.yqingyu.rpc.exception.RemoteServerException;
import top.yqingyu.rpc.exception.RpcException;
import top.yqingyu.rpc.exception.RpcTimeOutException;
import top.yqingyu.rpc.util.RpcUtil;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.concurrent.ConcurrentHashMap; | 1,658 | package top.yqingyu.rpc.consumer;
public class ProxyClassMethodExecutor implements MethodInterceptor {
public static final Logger logger = LoggerFactory.getLogger(ProxyClassMethodExecutor.class);
Class<?> proxyClass;
String holderName;
ConsumerHolder holder;
ConsumerHolderContext ctx;
MethodExecuteInterceptor interceptor;
ConcurrentHashMap<Method, QyRpcProducerProperties> methodPropertiesCache = new ConcurrentHashMap<>();
ConcurrentHashMap<Method, Boolean> emptyMethodPropertiesCache = new ConcurrentHashMap<>();
ConcurrentHashMap<Method, String> methodNameCache = new ConcurrentHashMap<>();
ConcurrentHashMap<Method, Object> specialMethodNameCache = new ConcurrentHashMap<>();
final static Boolean b = false;
public ProxyClassMethodExecutor(Class<?> proxyClass, String consumerName, ConsumerHolderContext ctx) {
this.proxyClass = proxyClass;
this.ctx = ctx;
holderName = consumerName;
interceptor = ctx.methodExecuteInterceptor;
}
@Override
public Object intercept(Object obj, Method method, Object[] param, MethodProxy proxy) throws Throwable {
if (holder == null) {
holder = ctx.getConsumerHolder(holderName);
if (holder == null) throw new RpcException("No consumer named {} was initialized please check", holderName);
}
interceptor.before(ctx, method, param);
Object result = specialMethodNameCache.get(method);
if (result != null) {
interceptor.completely(ctx, method, param, result);
return result;
}
String methodStrName = methodNameCache.get(method);
if (StringUtil.isEmpty(methodStrName)) {
String className = RpcUtil.getClassName(proxyClass);
String name = method.getName();
| package top.yqingyu.rpc.consumer;
public class ProxyClassMethodExecutor implements MethodInterceptor {
public static final Logger logger = LoggerFactory.getLogger(ProxyClassMethodExecutor.class);
Class<?> proxyClass;
String holderName;
ConsumerHolder holder;
ConsumerHolderContext ctx;
MethodExecuteInterceptor interceptor;
ConcurrentHashMap<Method, QyRpcProducerProperties> methodPropertiesCache = new ConcurrentHashMap<>();
ConcurrentHashMap<Method, Boolean> emptyMethodPropertiesCache = new ConcurrentHashMap<>();
ConcurrentHashMap<Method, String> methodNameCache = new ConcurrentHashMap<>();
ConcurrentHashMap<Method, Object> specialMethodNameCache = new ConcurrentHashMap<>();
final static Boolean b = false;
public ProxyClassMethodExecutor(Class<?> proxyClass, String consumerName, ConsumerHolderContext ctx) {
this.proxyClass = proxyClass;
this.ctx = ctx;
holderName = consumerName;
interceptor = ctx.methodExecuteInterceptor;
}
@Override
public Object intercept(Object obj, Method method, Object[] param, MethodProxy proxy) throws Throwable {
if (holder == null) {
holder = ctx.getConsumerHolder(holderName);
if (holder == null) throw new RpcException("No consumer named {} was initialized please check", holderName);
}
interceptor.before(ctx, method, param);
Object result = specialMethodNameCache.get(method);
if (result != null) {
interceptor.completely(ctx, method, param, result);
return result;
}
String methodStrName = methodNameCache.get(method);
if (StringUtil.isEmpty(methodStrName)) {
String className = RpcUtil.getClassName(proxyClass);
String name = method.getName();
| StringBuilder sb = new StringBuilder(className).append(Constants.method).append(name); | 0 | 2023-10-18 11:03:57+00:00 | 4k |
exagonsoft/drones-management-board-backend | src/main/java/exagonsoft/drones/service/impl/DroneServiceImpl.java | [
{
"identifier": "BatteryLevelDto",
"path": "src/main/java/exagonsoft/drones/dto/BatteryLevelDto.java",
"snippet": "@Getter\n@Setter\n@NoArgsConstructor\n@AllArgsConstructor\npublic class BatteryLevelDto {\n private int batteryLevel;\n}"
},
{
"identifier": "DroneDto",
"path": "src/main/java/exagonsoft/drones/dto/DroneDto.java",
"snippet": "@Getter\n@Setter\n@NoArgsConstructor\n@AllArgsConstructor\npublic class DroneDto {\n private Long id;\n private String serial_number;\n private ModelType model;\n private Integer max_weight;\n private Integer battery_capacity;\n private StateType state;\n}"
},
{
"identifier": "MedicationDto",
"path": "src/main/java/exagonsoft/drones/dto/MedicationDto.java",
"snippet": "@Getter\n@Setter\n@NoArgsConstructor\n@AllArgsConstructor\npublic class MedicationDto {\n private Long id;\n private String name;\n private Integer weight;\n private String code;\n private String imageUrl;\n}"
},
{
"identifier": "Drone",
"path": "src/main/java/exagonsoft/drones/entity/Drone.java",
"snippet": "@Getter\n@Setter\n@NoArgsConstructor\n@AllArgsConstructor\n@Entity\n@Table(name = \"drones\")\npublic class Drone {\n\n public enum ModelType {\n Lightweight,\n Middleweight,\n Cruiserweight,\n Heavyweight\n }\n\n public enum StateType {\n IDLE,\n LOADING,\n LOADED,\n DELIVERING,\n DELIVERED,\n RETURNING\n }\n\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private Long id;\n\n @Column(name = \"serial_number\", nullable = false, unique = true, length = 100)\n private String serial_number;\n\n @Column(name = \"model\", nullable = false)\n @Enumerated(EnumType.STRING)\n private ModelType model;\n\n @Column(name = \"max_weight\", nullable = false)\n @Max(value = 500, message = \"Maximum weight cannot exceed 500gr\")\n private Integer max_weight;\n\n @Column(name = \"battery_capacity\", nullable = false)\n @Max(value = 100, message = \"Battery capacity cannot exceed 100%\")\n private Integer battery_capacity;\n\n @Column(name = \"state\", nullable = false)\n @Enumerated(EnumType.STRING)\n private StateType state;\n}"
},
{
"identifier": "DroneMedications",
"path": "src/main/java/exagonsoft/drones/entity/DroneMedications.java",
"snippet": "@Getter\n@Setter\n@NoArgsConstructor\n@AllArgsConstructor\n@Entity\n@Table(name = \"drone_medications\")\npublic class DroneMedications {\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private Long id;\n\n @Column(name = \"drone_id\", nullable = false)\n private Long droneId;\n\n @Column(name = \"medication_id\", nullable = false)\n private Long medicationId;\n}"
},
{
"identifier": "Medication",
"path": "src/main/java/exagonsoft/drones/entity/Medication.java",
"snippet": "@Getter\n@Setter\n@NoArgsConstructor\n@AllArgsConstructor\n@Entity\n@Table(name = \"medications\")\npublic class Medication {\n\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private Long id;\n\n @Pattern(regexp = \"^[a-zA-Z0-9_-]*$\", message = \"Name can only contain letters, numbers, '-', and '_'\")\n @Size(max = 255, message = \"Name cannot exceed 255 characters\")\n @Column(name = \"name\", nullable = false, length = 255)\n private String name;\n\n @Column(name = \"weight\", nullable = false)\n private Integer weight;\n\n @Pattern(regexp = \"^[A-Z0-9_]*$\", message = \"Code can only contain uppercase letters, numbers, and '_'\")\n @Size(max = 255, message = \"Code cannot exceed 255 characters\")\n @Column(name = \"code\", nullable = false, length = 255)\n private String code;\n\n @Size(max = 1000, message = \"Image URL/path cannot exceed 1000 characters\")\n @Column(name = \"image_url\", nullable = false, length = 1000)\n private String imageUrl;\n}"
},
{
"identifier": "StateType",
"path": "src/main/java/exagonsoft/drones/entity/Drone.java",
"snippet": "public enum StateType {\n IDLE,\n LOADING,\n LOADED,\n DELIVERING,\n DELIVERED,\n RETURNING\n}"
},
{
"identifier": "DuplicateSerialNumberException",
"path": "src/main/java/exagonsoft/drones/exception/DuplicateSerialNumberException.java",
"snippet": "@ResponseStatus(value = HttpStatus.CONFLICT)\npublic class DuplicateSerialNumberException extends RuntimeException{\n public DuplicateSerialNumberException(String message){\n super(message);\n }\n\n @Override\n public String getMessage() {\n return super.getMessage();\n }\n}"
},
{
"identifier": "ResourceNotFoundException",
"path": "src/main/java/exagonsoft/drones/exception/ResourceNotFoundException.java",
"snippet": "@ResponseStatus(value = HttpStatus.NOT_FOUND)\npublic class ResourceNotFoundException extends RuntimeException {\n\n public ResourceNotFoundException(String message) {\n super(message);\n }\n}"
},
{
"identifier": "DroneMapper",
"path": "src/main/java/exagonsoft/drones/mapper/DroneMapper.java",
"snippet": "public class DroneMapper {\n public static DroneDto mapToDroneDto(Drone drone) {\n return new DroneDto(\n drone.getId(),\n drone.getSerial_number(),\n drone.getModel(),\n drone.getMax_weight(),\n drone.getBattery_capacity(),\n drone.getState());\n }\n\n public static Drone mapToDrone(DroneDto droneDto) {\n return new Drone(\n droneDto.getId(),\n droneDto.getSerial_number(),\n droneDto.getModel(),\n droneDto.getMax_weight(),\n droneDto.getBattery_capacity(),\n droneDto.getState());\n }\n}"
},
{
"identifier": "DroneRepository",
"path": "src/main/java/exagonsoft/drones/repository/DroneRepository.java",
"snippet": "public interface DroneRepository extends JpaRepository<Drone, Long> {\n @Query(value = \"SELECT * FROM drones WHERE battery_capacity >= 25 AND state = 'IDLE'\", nativeQuery = true)\n List<Drone> findAvailableDrones();\n\n @Query(value = \"SELECT serial_number, battery_capacity, id FROM drones\" , nativeQuery = true)\n List<Object[]> getAllDronesBatteryLevel();\n}"
},
{
"identifier": "DroneMedicationService",
"path": "src/main/java/exagonsoft/drones/service/DroneMedicationService.java",
"snippet": "public interface DroneMedicationService {\n List<DroneMedications> listAllDroneMedications(Long droneID);\n DroneMedications createDroneMedication(DroneMedications droneMedications);\n\n @Transactional\n void cleanupDroneMedication(Long droneId);\n \n List<Long> listAllMedicationsIdsByDroneId(Long droneId);\n}"
},
{
"identifier": "DroneService",
"path": "src/main/java/exagonsoft/drones/service/DroneService.java",
"snippet": "public interface DroneService {\n DroneDto createDrone(DroneDto droneDto);\n\n DroneDto getDroneByID(Long droneID);\n\n List<DroneDto> listAllDrones();\n\n DroneDto updateDrone(Long id, DroneDto updatedDrone);\n\n List<DroneDto> listAvailableDrones();\n\n BatteryLevelDto checkDroneBatteryLevel(Long droneID);\n\n List<MedicationDto> listDroneMedications(Long droneID);\n\n boolean loadDroneMedications(Long droneID, List<Long> medicationsIds);\n}"
},
{
"identifier": "MedicationService",
"path": "src/main/java/exagonsoft/drones/service/MedicationService.java",
"snippet": "public interface MedicationService {\n MedicationDto getMedication(Long medicationID);\n\n MedicationDto createMedication(MedicationDto medicationDto);\n\n MedicationDto updateMedication(Long id, MedicationDto medicationDto);\n\n void deleteMedication(Long medicationID);\n\n MedicationDto getMedicationById(Long medicationId);\n\n List<MedicationDto> listAllMedications();\n\n List<Medication> getMedicationsListByIds(List<Long> medicationIds);\n}"
},
{
"identifier": "UtilFunctions",
"path": "src/main/java/exagonsoft/drones/utils/UtilFunctions.java",
"snippet": "public class UtilFunctions {\n\n public static void validateDrone(DroneDto drone) {\n\n if (drone.getMax_weight() > 500) {\n throw new MaxWeightExceededException(\"Drone Max Weight Exceeded!. (max = 500gr)\");\n }\n\n if (drone.getSerial_number().length() > 100) {\n throw new MaxSerialNumberCharacters(\"Drone Serial Number Max Length Exceeded!. (max = 100)\");\n }\n }\n\n public static void validateDroneManagement(DroneDto updatedDrone) {\n\n if (updatedDrone.getState() == StateType.LOADING) {\n if (updatedDrone.getBattery_capacity() < 25) {\n throw new LowBatteryException(\n \"Drone battery level most be greater than 25% to start LOADING state!, (actual:\"\n + updatedDrone.getBattery_capacity() + \"%)\");\n }\n }\n }\n\n public static void validateDroneLoad(int droneMaxWeight, List<Medication> medicationList, StateType state) {\n\n int weightToLoad = medicationList.stream()\n .mapToInt(Medication::getWeight)\n .sum();\n\n if (weightToLoad > droneMaxWeight) {\n throw new MaxWeightExceededException(\"Drone Max Weight Exceeded!. (max = \" + droneMaxWeight + \"gr)\");\n }\n\n if (state != StateType.IDLE) {\n throw new DroneInvalidLoadStateException(\"The Drone can be loaded only in IDLE state!\");\n }\n }\n\n public static void validateMedication(MedicationDto medication) {\n String VALID_PATTERN = \"^[a-zA-Z0-9-_]+$\";\n String VALID_CODE_PATTERN = \"^[A-Z_0-9]+$\";\n Pattern pattern = Pattern.compile(VALID_PATTERN);\n Matcher matcher = pattern.matcher(medication.getName());\n Pattern patternCode = Pattern.compile(VALID_CODE_PATTERN);\n Matcher matcherCode = patternCode.matcher(medication.getCode());\n\n if (!matcher.matches()) {\n\n throw new MedicationInvalidNamePatternException(\n \"Medication Name Pattern Invalid!. (allowed only letters, numbers, ‘-‘, ‘_’)\");\n }\n\n if (!matcherCode.matches()) {\n throw new MedicationCodeInvalidPatternException(\n \"Medication Code Pattern Invalid!. (allowed only upper case letters, underscore and numbers)\");\n }\n }\n\n public static Drone updateDroneLifeCycle(Drone drone, List<Medication> medicationList) {\n try {\n if (drone.getState() == StateType.IDLE) {\n drone.setBattery_capacity(100);\n return drone;\n }\n\n int loadedWeight = medicationList.stream()\n .mapToInt(Medication::getWeight)\n .sum();\n int batterySpend = calculateBatterySpend(loadedWeight);\n int newBatteryLevel = drone.getBattery_capacity() - batterySpend;\n drone.setBattery_capacity(newBatteryLevel);\n switch (drone.getState()) {\n case LOADING:\n drone.setState(StateType.LOADED);\n break;\n case LOADED:\n drone.setState(StateType.DELIVERING);\n break;\n case DELIVERING:\n drone.setState(StateType.DELIVERED);\n break;\n case DELIVERED:\n drone.setState(StateType.RETURNING);\n break;\n case RETURNING:\n drone.setState(StateType.IDLE);\n break;\n default:\n break;\n }\n return drone;\n } catch (Exception e) {\n throw e;\n }\n }\n\n private static int calculateBatterySpend(int weightLoaded) {\n int batterySpend = 1;\n\n if (weightLoaded > 0 && weightLoaded <= 20) {\n batterySpend = 3;\n }\n\n if (weightLoaded > 20 && weightLoaded <= 50) {\n batterySpend = 5;\n }\n\n if (weightLoaded > 50 && weightLoaded <= 150) {\n batterySpend = 6;\n }\n\n if (weightLoaded > 150 && weightLoaded <= 400) {\n batterySpend = 7;\n }\n\n if (weightLoaded > 400) {\n batterySpend = 10;\n }\n\n return batterySpend;\n }\n\n public static void printInfo(String header, String message) {\n try {\n System.out.println(\"\\n\");\n System.out.println(\"****************************\" + header + \"****************************\" + \"\\n\");\n System.out.println(message);\n System.out.println(\"****************************\" + header + \" END ****************************\");\n System.out.println(\"\\n\");\n } catch (Exception e) {\n throw e;\n }\n }\n}"
}
] | import java.util.List;
import java.util.stream.Collectors;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Service;
import exagonsoft.drones.dto.BatteryLevelDto;
import exagonsoft.drones.dto.DroneDto;
import exagonsoft.drones.dto.MedicationDto;
import exagonsoft.drones.entity.Drone;
import exagonsoft.drones.entity.DroneMedications;
import exagonsoft.drones.entity.Medication;
import exagonsoft.drones.entity.Drone.StateType;
import exagonsoft.drones.exception.DuplicateSerialNumberException;
import exagonsoft.drones.exception.ResourceNotFoundException;
import exagonsoft.drones.mapper.DroneMapper;
import exagonsoft.drones.repository.DroneRepository;
import exagonsoft.drones.service.DroneMedicationService;
import exagonsoft.drones.service.DroneService;
import exagonsoft.drones.service.MedicationService;
import exagonsoft.drones.utils.UtilFunctions;
import lombok.AllArgsConstructor; | 3,230 | package exagonsoft.drones.service.impl;
@Service
@AllArgsConstructor | package exagonsoft.drones.service.impl;
@Service
@AllArgsConstructor | public class DroneServiceImpl implements DroneService { | 12 | 2023-10-16 08:32:39+00:00 | 4k |
LucassR0cha/demo-pattern-JDBC | src/model/dao/impl/SellerDaoJDBC.java | [
{
"identifier": "DB",
"path": "src/db/DB.java",
"snippet": "public class DB {\n\n\tprivate static Connection conn = null;\n\t\n\tpublic static Connection getConnection() {\n\t\tif (conn == null) {\n\t\t\ttry {\n\t\t\t\tProperties props = loadProperties();\n\t\t\t\tString url = props.getProperty(\"dburl\");\n\t\t\t\tconn = DriverManager.getConnection(url, props);\n\t\t\t}\n\t\t\tcatch (SQLException e) {\n\t\t\t\tthrow new DbException(e.getMessage());\n\t\t\t}\n\t\t}\n\t\treturn conn;\n\t}\n\t\n\tpublic static void closeConnection() {\n\t\tif (conn != null) {\n\t\t\ttry {\n\t\t\t\tconn.close();\n\t\t\t} catch (SQLException e) {\n\t\t\t\tthrow new DbException(e.getMessage());\n\t\t\t}\n\t\t}\n\t}\n\t\n\tprivate static Properties loadProperties() {\n\t\ttry (FileInputStream fs = new FileInputStream(\"db.properties\")) {\n\t\t\tProperties props = new Properties();\n\t\t\tprops.load(fs);\n\t\t\treturn props;\n\t\t}\n\t\tcatch (IOException e) {\n\t\t\tthrow new DbException(e.getMessage());\n\t\t}\n\t}\n\t\n\tpublic static void closeStatement(Statement st) {\n\t\tif (st != null) {\n\t\t\ttry {\n\t\t\t\tst.close();\n\t\t\t} catch (SQLException e) {\n\t\t\t\tthrow new DbException(e.getMessage());\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic static void closeResultSet(ResultSet rs) {\n\t\tif (rs != null) {\n\t\t\ttry {\n\t\t\t\trs.close();\n\t\t\t} catch (SQLException e) {\n\t\t\t\tthrow new DbException(e.getMessage());\n\t\t\t}\n\t\t}\n\t}\n}"
},
{
"identifier": "DbException",
"path": "src/db/DbException.java",
"snippet": "public class DbException extends RuntimeException {\n\tprivate static final long serialVersionUID = 1L;\n\n\tpublic DbException(String msg) {\n\t\tsuper(msg);\n\t}\n}"
},
{
"identifier": "SellerDao",
"path": "src/model/dao/SellerDao.java",
"snippet": "public interface SellerDao {\n\n\tvoid insert(Seller obj);\n\n\tvoid update(Seller obj);\n\n\tvoid deleteById(Integer id);\n\n\tSeller findById(Integer id);\n\n\tList<Seller> findAll();\n\n\tList<Seller> findByDepartment(Department department);\n}"
},
{
"identifier": "Department",
"path": "src/model/entities/Department.java",
"snippet": "public class Department implements Serializable {\n\n\tprivate static final long serialVersionUID = 1L;\n\n\tprivate Integer id;\n\tprivate String name;\n\n\tpublic Department() {\n\t}\n\n\tpublic Department(Integer id, String name) {\n\t\tthis.id = id;\n\t\tthis.name = name;\n\t}\n\n\tpublic Integer getId() {\n\t\treturn id;\n\t}\n\n\tpublic void setId(Integer id) {\n\t\tthis.id = id;\n\t}\n\n\tpublic String getName() {\n\t\treturn name;\n\t}\n\n\tpublic void setName(String name) {\n\t\tthis.name = name;\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\tfinal int prime = 31;\n\t\tint result = 1;\n\t\tresult = prime * result + ((id == null) ? 0 : id.hashCode());\n\t\treturn result;\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj)\n\t\t\treturn true;\n\t\tif (obj == null)\n\t\t\treturn false;\n\t\tif (getClass() != obj.getClass())\n\t\t\treturn false;\n\t\tDepartment other = (Department) obj;\n\t\tif (id == null) {\n\t\t\tif (other.id != null)\n\t\t\t\treturn false;\n\t\t} else if (!id.equals(other.id))\n\t\t\treturn false;\n\t\treturn true;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"Department id: \" + id + \", name: \" + name;\n\t}\n}"
},
{
"identifier": "Seller",
"path": "src/model/entities/Seller.java",
"snippet": "public class Seller implements Serializable {\n\n\tprivate static final long serialVersionUID = 1L;\n\t\n\tprivate Integer id;\n\tprivate String name;\n\tprivate String email;\n\tprivate Date birthDate;\n\tprivate Double baseSalary;\n\n\tprivate Department department;\n\n\tpublic Seller() {\n\t}\n\n\tpublic Seller(\n\t\t\tInteger id, String name, String email, \n\t\t\tDate birthDate, Double baseSalary, \n\t\t\tDepartment department) {\n\n\t\tthis.id = id;\n\t\tthis.name = name;\n\t\tthis.email = email;\n\t\tthis.birthDate = birthDate;\n\t\tthis.baseSalary = baseSalary;\n\t\tthis.department = department;\n\t}\n\n\tpublic Integer getId() {\n\t\treturn id;\n\t}\n\n\tpublic void setId(Integer id) {\n\t\tthis.id = id;\n\t}\n\n\tpublic String getName() {\n\t\treturn name;\n\t}\n\n\tpublic void setName(String name) {\n\t\tthis.name = name;\n\t}\n\n\tpublic String getEmail() {\n\t\treturn email;\n\t}\n\n\tpublic void setEmail(String email) {\n\t\tthis.email = email;\n\t}\n\n\tpublic Date getBirthDate() {\n\t\treturn birthDate;\n\t}\n\n\tpublic void setBirthDate(Date birthDate) {\n\t\tthis.birthDate = birthDate;\n\t}\n\n\tpublic Double getBaseSalary() {\n\t\treturn baseSalary;\n\t}\n\n\tpublic void setBaseSalary(Double baseSalary) {\n\t\tthis.baseSalary = baseSalary;\n\t}\n\n\tpublic Department getDepartment() {\n\t\treturn department;\n\t}\n\n\tpublic void setDepartment(Department department) {\n\t\tthis.department = department;\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\tfinal int prime = 31;\n\t\tint result = 1;\n\t\tresult = prime * result + ((id == null) ? 0 : id.hashCode());\n\t\treturn result;\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj)\n\t\t\treturn true;\n\t\tif (obj == null)\n\t\t\treturn false;\n\t\tif (getClass() != obj.getClass())\n\t\t\treturn false;\n\t\tSeller other = (Seller) obj;\n\t\tif (id == null) {\n\t\t\tif (other.id != null)\n\t\t\t\treturn false;\n\t\t} else if (!id.equals(other.id))\n\t\t\treturn false;\n\t\treturn true;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"Seller id: \" + id + \", name: \" + name \n\t\t\t\t+ \", email: \" + email + \", birthDate: \" + birthDate\n\t\t\t\t+ \", baseSalary: \" + baseSalary \n\t\t\t\t+ \", department: \" + department;\n\t}\n}"
}
] | import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import db.DB;
import db.DbException;
import model.dao.SellerDao;
import model.entities.Department;
import model.entities.Seller; | 1,718 | package model.dao.impl;
public class SellerDaoJDBC implements SellerDao {
private Connection conn;
public SellerDaoJDBC(Connection conn) {
this.conn = conn;
}
@Override | package model.dao.impl;
public class SellerDaoJDBC implements SellerDao {
private Connection conn;
public SellerDaoJDBC(Connection conn) {
this.conn = conn;
}
@Override | public void insert(Seller obj) { | 4 | 2023-10-16 23:09:51+00:00 | 4k |
toel--/ocpp-backend-emulator | src/se/toel/ocpp/backendEmulator/Emulator.java | [
{
"identifier": "WebSocket",
"path": "src/org/java_websocket/WebSocket.java",
"snippet": "public interface WebSocket {\n\n /**\n * sends the closing handshake. may be send in response to an other handshake.\n *\n * @param code the closing code\n * @param message the closing message\n */\n void close(int code, String message);\n\n /**\n * sends the closing handshake. may be send in response to an other handshake.\n *\n * @param code the closing code\n */\n void close(int code);\n\n /**\n * Convenience function which behaves like close(CloseFrame.NORMAL)\n */\n void close();\n\n /**\n * This will close the connection immediately without a proper close handshake. The code and the\n * message therefore won't be transferred over the wire also they will be forwarded to\n * onClose/onWebsocketClose.\n *\n * @param code the closing code\n * @param message the closing message\n **/\n void closeConnection(int code, String message);\n\n /**\n * Send Text data to the other end.\n *\n * @param text the text data to send\n * @throws WebsocketNotConnectedException websocket is not yet connected\n */\n void send(String text);\n\n /**\n * Send Binary data (plain bytes) to the other end.\n *\n * @param bytes the binary data to send\n * @throws IllegalArgumentException the data is null\n * @throws WebsocketNotConnectedException websocket is not yet connected\n */\n void send(ByteBuffer bytes);\n\n /**\n * Send Binary data (plain bytes) to the other end.\n *\n * @param bytes the byte array to send\n * @throws IllegalArgumentException the data is null\n * @throws WebsocketNotConnectedException websocket is not yet connected\n */\n void send(byte[] bytes);\n\n /**\n * Send a frame to the other end\n *\n * @param framedata the frame to send to the other end\n */\n void sendFrame(Framedata framedata);\n\n /**\n * Send a collection of frames to the other end\n *\n * @param frames the frames to send to the other end\n */\n void sendFrame(Collection<Framedata> frames);\n\n /**\n * Send a ping to the other end\n *\n * @throws WebsocketNotConnectedException websocket is not yet connected\n */\n void sendPing();\n\n /**\n * Allows to send continuous/fragmented frames conveniently. <br> For more into on this frame type\n * see http://tools.ietf.org/html/rfc6455#section-5.4<br>\n * <p>\n * If the first frame you send is also the last then it is not a fragmented frame and will\n * received via onMessage instead of onFragmented even though it was send by this method.\n *\n * @param op This is only important for the first frame in the sequence. Opcode.TEXT,\n * Opcode.BINARY are allowed.\n * @param buffer The buffer which contains the payload. It may have no bytes remaining.\n * @param fin true means the current frame is the last in the sequence.\n **/\n void sendFragmentedFrame(Opcode op, ByteBuffer buffer, boolean fin);\n\n /**\n * Checks if the websocket has buffered data\n *\n * @return has the websocket buffered data\n */\n boolean hasBufferedData();\n\n /**\n * Returns the address of the endpoint this socket is connected to, or {@code null} if it is\n * unconnected.\n *\n * @return the remote socket address or null, if this socket is unconnected\n */\n InetSocketAddress getRemoteSocketAddress();\n\n /**\n * Returns the address of the endpoint this socket is bound to, or {@code null} if it is not\n * bound.\n *\n * @return the local socket address or null, if this socket is not bound\n */\n InetSocketAddress getLocalSocketAddress();\n\n /**\n * Is the websocket in the state OPEN\n *\n * @return state equals ReadyState.OPEN\n */\n boolean isOpen();\n\n /**\n * Is the websocket in the state CLOSING\n *\n * @return state equals ReadyState.CLOSING\n */\n boolean isClosing();\n\n /**\n * Returns true when no further frames may be submitted<br> This happens before the socket\n * connection is closed.\n *\n * @return true when no further frames may be submitted\n */\n boolean isFlushAndClose();\n\n /**\n * Is the websocket in the state CLOSED\n *\n * @return state equals ReadyState.CLOSED\n */\n boolean isClosed();\n\n /**\n * Getter for the draft\n *\n * @return the used draft\n */\n Draft getDraft();\n\n /**\n * Retrieve the WebSocket 'ReadyState'. This represents the state of the connection. It returns a\n * numerical value, as per W3C WebSockets specs.\n *\n * @return Returns '0 = CONNECTING', '1 = OPEN', '2 = CLOSING' or '3 = CLOSED'\n */\n ReadyState getReadyState();\n\n /**\n * Returns the HTTP Request-URI as defined by http://tools.ietf.org/html/rfc2616#section-5.1.2<br>\n * If the opening handshake has not yet happened it will return null.\n *\n * @return Returns the decoded path component of this URI.\n **/\n String getResourceDescriptor();\n\n /**\n * Setter for an attachment on the socket connection. The attachment may be of any type.\n *\n * @param attachment The object to be attached to the user\n * @param <T> The type of the attachment\n * @since 1.3.7\n **/\n <T> void setAttachment(T attachment);\n\n /**\n * Getter for the connection attachment.\n *\n * @param <T> The type of the attachment\n * @return Returns the user attachment\n * @since 1.3.7\n **/\n <T> T getAttachment();\n\n /**\n * Does this websocket use an encrypted (wss/ssl) or unencrypted (ws) connection\n *\n * @return true, if the websocket does use wss and therefore has a SSLSession\n * @since 1.4.1\n */\n boolean hasSSLSupport();\n\n /**\n * Returns the ssl session of websocket, if ssl/wss is used for this instance.\n *\n * @return the ssl session of this websocket instance\n * @throws IllegalArgumentException the underlying channel does not use ssl (use hasSSLSupport()\n * to check)\n * @since 1.4.1\n */\n SSLSession getSSLSession() throws IllegalArgumentException;\n\n /**\n * Returns the used Sec-WebSocket-Protocol for this websocket connection\n *\n * @return the Sec-WebSocket-Protocol or null, if no draft available\n * @throws IllegalArgumentException the underlying draft does not support a Sec-WebSocket-Protocol\n * @since 1.5.2\n */\n IProtocol getProtocol();\n}"
},
{
"identifier": "ClientHandshake",
"path": "src/org/java_websocket/handshake/ClientHandshake.java",
"snippet": "public interface ClientHandshake extends Handshakedata {\n\n /**\n * returns the HTTP Request-URI as defined by http://tools.ietf.org/html/rfc2616#section-5.1.2\n *\n * @return the HTTP Request-URI\n */\n String getResourceDescriptor();\n}"
}
] | import java.net.InetSocketAddress;
import java.util.Iterator;
import org.java_websocket.WebSocket;
import org.java_websocket.handshake.ClientHandshake;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import se.toel.util.Dev;
import se.toel.util.FileUtils; | 1,992 | /*
* WS Emulator for the OCPP bridge
*/
package se.toel.ocpp.backendEmulator;
/**
*
* @author toel
*/
public class Emulator {
/***************************************************************************
* Constants and variables
**************************************************************************/
private final Logger log = LoggerFactory.getLogger(Emulator.class);
private final String deviceId; | /*
* WS Emulator for the OCPP bridge
*/
package se.toel.ocpp.backendEmulator;
/**
*
* @author toel
*/
public class Emulator {
/***************************************************************************
* Constants and variables
**************************************************************************/
private final Logger log = LoggerFactory.getLogger(Emulator.class);
private final String deviceId; | private final WebSocket ws; | 0 | 2023-10-16 23:10:55+00:00 | 4k |
weibocom/rill-flow | rill-flow-service/src/main/java/com/weibo/rill/flow/service/component/DAGToolConverter.java | [
{
"identifier": "TaskCategory",
"path": "rill-flow-dag/olympicene-core/src/main/java/com/weibo/rill/flow/olympicene/core/model/task/TaskCategory.java",
"snippet": "@AllArgsConstructor\n@Getter\npublic enum TaskCategory {\n // 调用函数服务的Task\n FUNCTION(\"function\", 0),\n\n // 流程控制Task,执行分支语句\n CHOICE(\"choice\", 1),\n\n // 流程控制Task,执行循环语句\n FOREACH(\"foreach\", 1),\n\n // 本身无处理逻辑,等待外部通知,然后执行 output 更新数据, 兼容olympiadane1.0\n SUSPENSE(\"suspense\", 2),\n\n // 空 task\n PASS(\"pass\", 2),\n\n // return task\n RETURN(\"return\", 2),\n ;\n\n private final String value;\n\n /**\n * TaskCategory类型\n * 0: 计算类任务 需调用外部系统资源执行 如 程序语言中 运算符 方法\n * 1: 流程控制类任务 生成子任务 如 程序语言中 选择结构与循环结构\n * 2: 流程控制类任务 控制任务执行顺序 如 程序语言中 wait return\n */\n private final int type;\n\n @JsonValue\n public String getValue() {\n return value;\n }\n\n @JsonCreator\n public static TaskCategory forValues(String value) {\n for (TaskCategory item : TaskCategory.values()) {\n if (item.value.equals(value)) {\n return item;\n }\n }\n\n return null;\n }\n}"
},
{
"identifier": "TaskInfo",
"path": "rill-flow-interfaces/src/main/java/com/weibo/rill/flow/interfaces/model/task/TaskInfo.java",
"snippet": "@Setter\n@Getter\n@JsonIdentityInfo(\n generator = ObjectIdGenerators.UUIDGenerator.class,\n property = \"@json_id\"\n)\npublic class TaskInfo {\n private BaseTask task;\n\n /**\n * 区别于baseTask中的name,这里的name是TaskInfo,可能出现一个baseTask对应多个TaskInfo的情况,\n * 比如foreach场景中,每次遍历的TaskInfo都是不一样的\n */\n private String name;\n\n /**\n * 一条路径(route)的名字\n */\n private String routeName;\n\n private TaskStatus taskStatus;\n\n private Map<String, TaskStatus> subGroupIndexToStatus;\n\n private Map<String, Boolean> subGroupKeyJudgementMapping;\n\n private Map<String, String> subGroupIndexToIdentity;\n\n private TaskInvokeMsg taskInvokeMsg;\n\n /**\n * 以下为引用数据\n */\n private List<TaskInfo> next = new LinkedList<>();\n private TaskInfo parent;\n private Map<String, TaskInfo> children = new LinkedHashMap<>();\n private List<TaskInfo> dependencies = new LinkedList<>();\n\n @Override\n public String toString() {\n return \"TaskInfo{\" +\n \"task=\" + task +\n \", name='\" + name + '\\'' +\n \", routeName='\" + routeName + '\\'' +\n \", taskStatus=\" + taskStatus +\n '}';\n }\n\n public void updateInvokeMsg(TaskInvokeMsg taskInvokeMsg) {\n if (taskInvokeMsg == null || this.taskInvokeMsg == taskInvokeMsg) {\n return;\n }\n\n if (this.taskInvokeMsg == null) {\n this.taskInvokeMsg = taskInvokeMsg;\n } else {\n this.taskInvokeMsg.updateInvokeMsg(taskInvokeMsg);\n }\n }\n\n public void update(TaskInfo taskInfo) {\n doUpdate(1, taskInfo);\n }\n\n public void doUpdate(int depth, TaskInfo taskInfo) {\n if (taskInfo == null) {\n return;\n }\n\n Optional.ofNullable(taskInfo.getTaskStatus()).ifPresent(this::setTaskStatus);\n Optional.ofNullable(taskInfo.getSubGroupIndexToStatus()).filter(it -> !it.isEmpty()).ifPresent(this::setSubGroupIndexToStatus);\n Optional.ofNullable(taskInfo.getSubGroupKeyJudgementMapping()).filter(it -> !it.isEmpty()).ifPresent(this::setSubGroupKeyJudgementMapping);\n Optional.ofNullable(taskInfo.getSubGroupIndexToIdentity()).filter(it -> !it.isEmpty()).ifPresent(this::setSubGroupIndexToIdentity);\n Optional.ofNullable(taskInfo.getTaskInvokeMsg()).ifPresent(this::setTaskInvokeMsg);\n if (children == null) {\n children = new LinkedHashMap<>();\n }\n Optional.ofNullable(taskInfo.getChildren()).filter(it -> !it.isEmpty())\n .ifPresent(taskInfos -> taskInfos.forEach((taskName, tInfo) -> {\n if (this.children.containsKey(taskName) && depth <= 3) {\n this.children.get(taskName).doUpdate(depth + 1, tInfo);\n } else {\n this.children.put(taskName, tInfo);\n tInfo.setParent(this);\n }\n }));\n }\n\n public static TaskInfo cloneToSave(TaskInfo taskInfo) {\n // 设计上要求taskName不重复\n // 添加该set 避免循环引用导致递归无法退出\n Set<String> allTaskNames = new HashSet<>();\n return doCloneToSave(taskInfo, allTaskNames);\n }\n\n private static TaskInfo doCloneToSave(TaskInfo taskInfo, Set<String> allTaskNames) {\n if (taskInfo == null) {\n return null;\n }\n\n String taskName = taskInfo.getName();\n if (allTaskNames.contains(taskName)) {\n throw new DAGException(-1, \"name duplicated: \" + taskName);\n }\n allTaskNames.add(taskName);\n\n TaskInfo taskInfoClone = new TaskInfo();\n taskInfoClone.setName(taskInfo.getName());\n taskInfoClone.setRouteName(taskInfo.getRouteName());\n taskInfoClone.setTaskStatus(taskInfo.getTaskStatus());\n taskInfoClone.setSubGroupIndexToStatus(taskInfo.getSubGroupIndexToStatus());\n taskInfoClone.setSubGroupKeyJudgementMapping(taskInfo.getSubGroupKeyJudgementMapping());\n taskInfoClone.setSubGroupIndexToIdentity(taskInfo.getSubGroupIndexToIdentity());\n taskInfoClone.setTaskInvokeMsg(taskInfo.getTaskInvokeMsg());\n Map<String, TaskInfo> children = new LinkedHashMap<>();\n if (taskInfo.getChildren() != null && !taskInfo.getChildren().isEmpty()) {\n taskInfo.getChildren().forEach((name, task) -> children.put(name, doCloneToSave(task, allTaskNames)));\n }\n taskInfoClone.setChildren(children);\n return taskInfoClone;\n }\n}"
}
] | import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import com.weibo.rill.flow.olympicene.core.model.task.TaskCategory;
import com.weibo.rill.flow.interfaces.model.task.TaskInfo;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors; | 1,920 | /*
* Copyright 2021-2023 Weibo, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.weibo.rill.flow.service.component;
public class DAGToolConverter {
private static final Map<String, String> statusMapper = ImmutableMap.of("SUCCEED", "SUCCEEDED"); | /*
* Copyright 2021-2023 Weibo, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.weibo.rill.flow.service.component;
public class DAGToolConverter {
private static final Map<String, String> statusMapper = ImmutableMap.of("SUCCEED", "SUCCEEDED"); | public static Map<String, Object> convertTaskInfo(TaskInfo taskInfo) { | 1 | 2023-11-03 03:46:01+00:00 | 4k |
Yanyutin753/fakeApiTool-One-API | rearServer/src/main/java/com/yyandywt99/fakeapitool/service/impl/apiServiceImpl.java | [
{
"identifier": "apiMapper",
"path": "rearServer/src/main/java/com/yyandywt99/fakeapitool/mapper/apiMapper.java",
"snippet": "@Mapper\npublic interface apiMapper {\n /**\n * @更新updateUrl\n * @更新oneAPi里的fakeApi调用地址\n */\n @Update(\"update channels set base_url = #{newDateUrl} where base_url like '%fakeopen.com%'\")\n public void toUpdateUrl(String newDateUrl);\n\n /**\n * @更新updateApi\n * @更新oneAPi里的fakeApi的api\n */\n void updateApi(String api,Integer count);\n\n @Insert(\"INSERT INTO oneapi.channels (type, `key`, status, name,\" +\n \" weight, created_time, test_time, response_time, base_url,\" +\n \" other, balance, balance_updated_time, models, `group`, used_quota,\" +\n \" model_mapping, priority) VALUES (8, #{key}, 1, #{name}, 0, UNIX_TIMESTAMP(NOW()),\" +\n \"UNIX_TIMESTAMP(NOW()), 6, 'https://ai.fakeopen.com/', '',\" +\n \" 0, 0, 'gpt-3.5-turbo,gpt-3.5-turbo-0301,gpt-3.5-turbo-0613,gpt-3.5-turbo-16k,gpt-3.5-turbo-16k-0613',\" +\n \" 'default', 0, '', 1);\")\n void addKeys(addKeyPojo addKeyPojo);\n\n @Select(\"select id from channels where name = #{name}\")\n List<Integer> deleteKeys(String name);\n\n @Insert(\"insert into fakeapitool (name, value, userName, password, updateTime)\" +\n \" values (#{name},#{value},#{userName},#{password},now())\")\n void addToken(token token);\n\n @Delete(\"delete from fakeapitool where name = #{name};\")\n void deleteToken(String name);\n\n void requiredToken(token tem);\n\n /**\n * 通过构造CONCAT()来连接%值%\n */\n @Select(\"select name, value, userName, password, updateTime from fakeapitool where name like CONCAT('%', #{name}, '%')\")\n List<token> selectToken(String name);\n\n void requiredUser(String userName,String password);\n\n @Select(\"select count(*) from fakeapitooluser\" +\n \" where name = #{userName} and password = #{password};\")\n Integer login(String userName, String password);\n\n /**\n * 精确查找\n */\n @Select(\"select name, value, userName, password, updateTime from fakeapitool where name = #{name}\")\n token selectAccuracyToken(String name);\n}"
},
{
"identifier": "addKeyPojo",
"path": "rearServer/src/main/java/com/yyandywt99/fakeapitool/pojo/addKeyPojo.java",
"snippet": "@Data\n@NoArgsConstructor\n@AllArgsConstructor\npublic class addKeyPojo {\n Integer id;\n String name;\n String key;\n\n}"
},
{
"identifier": "token",
"path": "rearServer/src/main/java/com/yyandywt99/fakeapitool/pojo/token.java",
"snippet": "@Data\n@NoArgsConstructor\n@AllArgsConstructor\npublic class token {\n private String name;\n private String value;\n private String userName;\n private String password;\n private String updateTime;\n\n}"
},
{
"identifier": "apiService",
"path": "rearServer/src/main/java/com/yyandywt99/fakeapitool/service/apiService.java",
"snippet": "public interface apiService {\n String getUpdateUrl() throws Exception;\n\n String requiredToken(token token);\n\n String addToken(token token) ;\n\n String deleteToken(String name);\n\n boolean addKeys(token token);\n\n List<token> seleteToken(String name);\n\n token selectAccuracyToken(String name);\n\n String requiredUser(String userName,String password);\n\n String login(String userName, String password);\n\n String autoUpdateToken(String name) throws Exception;\n\n boolean autoUpdateSimpleToken(String name) throws Exception;\n}"
}
] | import com.yyandywt99.fakeapitool.mapper.apiMapper;
import com.yyandywt99.fakeapitool.pojo.addKeyPojo;
import com.yyandywt99.fakeapitool.pojo.token;
import com.yyandywt99.fakeapitool.service.apiService;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List; | 2,100 | package com.yyandywt99.fakeapitool.service.impl;
/**
* @author Yangyang
* @create 2023-11-07 14:54
*/
@Slf4j
@Service
public class apiServiceImpl implements apiService {
/**
* 拿到apiMapper,为调用做准备
*/
@Autowired
private apiMapper apiMapper;
@Value("${baseUrlWithoutPath}")
private String baseUrlWithoutPath;
// @Value("${baseUrlAutoToken}")
// private String baseUrlAutoToken;
private String session;
private String getSession(){
return this.session;
};
private void setSession(String session){
this.session = session;
}
public boolean existSession(){
if(getSession() == null || getSession().isEmpty()){
return false;
}
return true;
}
/**
*
* @param temTaken
* @return 以fk-开头的fakeApiKey
* @throws Exception
* 通过https://ai.fakeopen.com/token/register
* unique_name(apiKey名字)、access_token(token)、
* expires_i(有效期默认为0)、show_conversations(是否不隔绝对话,默认是)、
*
*/
public List<String> getKeys(token temTaken) throws Exception {
List<String> res = new ArrayList<>();
int temToken = 1;
while (temToken <= 3) {
// 替换为你的unique_name
String unique_name = temTaken.getName() + temToken;
// 请确保在Java中有token_info这个Map
String access_token = temTaken.getValue();
// 假设expires_in为0
int expires_in = 0;
boolean show_conversations = true;
String url = "https://ai.fakeopen.com/token/register";
String data = "unique_name=" + unique_name + "&access_token=" + access_token + "&expires_in=" + expires_in + "&show_conversations=" + show_conversations;
String tokenKey = "";
try {
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// 设置请求方法为POST
con.setRequestMethod("POST");
con.setDoOutput(true);
// 发送POST数据
OutputStream os = con.getOutputStream();
os.write(data.getBytes());
os.flush();
os.close();
// 获取响应
int responseCode = con.getResponseCode();
if (responseCode == 200) {
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
String responseJson = response.toString();
tokenKey = new JSONObject(responseJson).getString("token_key");
} else {
BufferedReader in = new BufferedReader(new InputStreamReader(con.getErrorStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
String errStr = response.toString().replace("\n", "").replace("\r", "").trim();
System.out.println("share token failed: " + errStr);
return null;
}
// 使用正则表达式匹配字符串
String shareToken = tokenKey;
if (shareToken.matches("^(fk-|pk-).*")) {
log.info("open_ai_api_key has been updated to: " + shareToken);
res.add(shareToken);
}
} catch (IOException e) {
e.printStackTrace();
}
temToken ++;
}
return res;
}
/**
* 添加Key值
* 会通过Post方法访问One-Api接口/api/channel/,添加新keys
* @return "true"or"false"
*/ | package com.yyandywt99.fakeapitool.service.impl;
/**
* @author Yangyang
* @create 2023-11-07 14:54
*/
@Slf4j
@Service
public class apiServiceImpl implements apiService {
/**
* 拿到apiMapper,为调用做准备
*/
@Autowired
private apiMapper apiMapper;
@Value("${baseUrlWithoutPath}")
private String baseUrlWithoutPath;
// @Value("${baseUrlAutoToken}")
// private String baseUrlAutoToken;
private String session;
private String getSession(){
return this.session;
};
private void setSession(String session){
this.session = session;
}
public boolean existSession(){
if(getSession() == null || getSession().isEmpty()){
return false;
}
return true;
}
/**
*
* @param temTaken
* @return 以fk-开头的fakeApiKey
* @throws Exception
* 通过https://ai.fakeopen.com/token/register
* unique_name(apiKey名字)、access_token(token)、
* expires_i(有效期默认为0)、show_conversations(是否不隔绝对话,默认是)、
*
*/
public List<String> getKeys(token temTaken) throws Exception {
List<String> res = new ArrayList<>();
int temToken = 1;
while (temToken <= 3) {
// 替换为你的unique_name
String unique_name = temTaken.getName() + temToken;
// 请确保在Java中有token_info这个Map
String access_token = temTaken.getValue();
// 假设expires_in为0
int expires_in = 0;
boolean show_conversations = true;
String url = "https://ai.fakeopen.com/token/register";
String data = "unique_name=" + unique_name + "&access_token=" + access_token + "&expires_in=" + expires_in + "&show_conversations=" + show_conversations;
String tokenKey = "";
try {
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// 设置请求方法为POST
con.setRequestMethod("POST");
con.setDoOutput(true);
// 发送POST数据
OutputStream os = con.getOutputStream();
os.write(data.getBytes());
os.flush();
os.close();
// 获取响应
int responseCode = con.getResponseCode();
if (responseCode == 200) {
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
String responseJson = response.toString();
tokenKey = new JSONObject(responseJson).getString("token_key");
} else {
BufferedReader in = new BufferedReader(new InputStreamReader(con.getErrorStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
String errStr = response.toString().replace("\n", "").replace("\r", "").trim();
System.out.println("share token failed: " + errStr);
return null;
}
// 使用正则表达式匹配字符串
String shareToken = tokenKey;
if (shareToken.matches("^(fk-|pk-).*")) {
log.info("open_ai_api_key has been updated to: " + shareToken);
res.add(shareToken);
}
} catch (IOException e) {
e.printStackTrace();
}
temToken ++;
}
return res;
}
/**
* 添加Key值
* 会通过Post方法访问One-Api接口/api/channel/,添加新keys
* @return "true"or"false"
*/ | public boolean addKey(addKeyPojo addKeyPojo) throws Exception { | 1 | 2023-11-09 08:04:54+00:00 | 4k |
aliyun/alibabacloud-compute-nest-saas-boost | boost.server/src/test/java/org/example/controller/OrderControllerTest.java | [
{
"identifier": "BaseResult",
"path": "boost.common/src/main/java/org/example/common/BaseResult.java",
"snippet": "@Data\npublic class BaseResult<T> implements Serializable {\n private static final long serialVersionUID = 5680133981298179266L;\n\n /**\n * Status code.\n */\n protected String code;\n\n /**\n * Response message.\n */\n protected String message;\n\n /**\n * Return data.\n */\n private T data;\n\n protected String requestId;\n\n public static <T> BaseResult<T> success() {\n return new BaseResult<>();\n }\n\n public static <T> BaseResult<T> success(T data) {\n return new BaseResult<>(data);\n }\n\n public static <T> BaseResult<T> fail(String message) {\n return new BaseResult<>(String.valueOf(HttpStatus.INTERNAL_SERVER_ERROR.value()), message);\n }\n\n public static <T> BaseResult<T> fail(CommonErrorInfo commonErrorInfo) {\n return new BaseResult<>(commonErrorInfo);\n }\n\n public BaseResult() {\n this.code = String.valueOf(HttpStatus.OK.value());\n this.message = HttpStatus.OK.getReasonPhrase();\n this.requestId = MDC.get(REQUEST_ID);\n }\n\n public BaseResult(String code, String message, T data, String requestId) {\n this.code = code;\n this.message = message;\n this.data = data;\n this.requestId = requestId;\n }\n\n public BaseResult(HttpStatus httpStatus) {\n this(String.valueOf(httpStatus.value()), httpStatus.getReasonPhrase());\n }\n\n public BaseResult(CommonErrorInfo commonErrorInfo) {\n this(commonErrorInfo.getCode(), commonErrorInfo.getMessage());\n }\n\n /**\n * If there is no data returned, you can manually specify the status code and message.\n */\n public BaseResult(String code, String msg) {\n this(code,msg,null,MDC.get(REQUEST_ID));\n }\n\n /**\n * When data is returned, the status code is 200, and the default message is \"Operation successful!\"\n */\n public BaseResult(T data) {\n this(HttpStatus.OK.getReasonPhrase(), data);\n }\n\n /**\n * When data is returned, the status code is 200, and the message can be manually specified.\n */\n public BaseResult(String msg, T data) {\n this(String.valueOf(HttpStatus.OK.value()), msg, data, MDC.get(REQUEST_ID));\n }\n\n /**\n * When data is returned, you can customize the status code and manually specify the message.\n */\n public BaseResult(String code, String msg,T data) {\n this(code, msg, data, MDC.get(REQUEST_ID));\n }\n}"
},
{
"identifier": "ListResult",
"path": "boost.common/src/main/java/org/example/common/ListResult.java",
"snippet": "public class ListResult<T> extends BaseResult implements Serializable {\n\n private static final long serialVersionUID = 729779190711627058L;\n\n private List<T> data;\n\n private Long count;\n\n private String nextToken;\n\n public ListResult() {\n }\n\n @Override\n public List<T> getData() {\n return this.data;\n }\n\n public void setData(List<T> data) {\n this.data = data;\n }\n\n public Long getCount() {\n return this.count;\n }\n\n public void setCount(long count) {\n this.count = count;\n }\n\n public String getNextToken() {\n return nextToken;\n }\n\n public void setNextToken(String nextToken) {\n this.nextToken = nextToken;\n }\n\n public static <T> ListResult<T> genSuccessListResult(List<T> data, long count) {\n ListResult<T> listResult = new ListResult<T>();\n listResult.setData(data);\n listResult.setCount(count);\n return listResult;\n }\n\n public static <T> ListResult<T> genSuccessListResult(List<T> data, long count, String nextToken) {\n ListResult<T> listResult = new ListResult<T>();\n listResult.setData(data);\n listResult.setCount(count);\n listResult.setNextToken(nextToken);\n return listResult;\n }\n}"
},
{
"identifier": "OrderDTO",
"path": "boost.common/src/main/java/org/example/common/dto/OrderDTO.java",
"snippet": "@Data\npublic class OrderDTO {\n\n /**\n * The Order ID, which corresponds to the Alipay Out Transaction Number.\n */\n private String orderId;\n\n /**\n * Transaction status.\n */\n private TradeStatus tradeStatus;\n\n /**\n * Transaction creation time.\n */\n private String gmtCreate;\n\n /**\n * Desc:subject\n */\n private ProductName productName;\n\n /**\n * Desc:nest service configs\n */\n private String productComponents;\n\n /**\n * Total Amount.\n */\n private Double totalAmount;\n\n /**\n * Payment type.\n */\n private PaymentType type;\n\n /**\n * Refund ID, can only be created once.\n */\n private String refundId;\n\n /**\n * Refund Date.\n */\n private String refundDate;\n\n /**\n * Refund Amount.\n */\n private Double refundAmount;\n\n /**\n * Compute nest service instance id.\n */\n private String serviceInstanceId;\n\n /**\n * Transaction payment time.\n */\n private String gmtPayment;\n\n /**\n * Pay Period.\n */\n private Long payPeriod;\n\n /**\n * Pay Period Unit.\n */\n private PayPeriodUnit payPeriodUnit;\n\n /**\n * Specification Name.\n */\n private String specificationName;\n\n /**\n * Seller received amount.\n */\n private Double receiptAmount;\n\n /**\n * Account Id. corresponds to the aliyun aid.\n */\n private Long accountId;\n\n private Long billingStartDateMillis;\n\n private Long billingEndDateMillis;\n}"
},
{
"identifier": "UserInfoModel",
"path": "boost.common/src/main/java/org/example/common/model/UserInfoModel.java",
"snippet": "@Data\n@NoArgsConstructor\n@AllArgsConstructor\npublic class UserInfoModel {\n\n @JsonProperty(\"sub\")\n private String sub;\n\n @JsonProperty(\"name\")\n private String name;\n\n @JsonProperty(\"login_name\")\n @ApiModelProperty(\"login_name\")\n private String loginName;\n\n @JsonProperty(\"aid\")\n private String aid;\n\n @JsonProperty(\"uid\")\n private String uid;\n}"
},
{
"identifier": "CreateOrderParam",
"path": "boost.common/src/main/java/org/example/common/param/CreateOrderParam.java",
"snippet": "@Data\npublic class CreateOrderParam {\n\n @NotNull\n private ProductName productName;\n\n @NotNull\n private String productComponents;\n\n @NotNull\n private PaymentType type;\n}"
},
{
"identifier": "GetOrderParam",
"path": "boost.common/src/main/java/org/example/common/param/GetOrderParam.java",
"snippet": "@AllArgsConstructor\n@Data\npublic class GetOrderParam {\n\n private String orderId;\n}"
},
{
"identifier": "ListOrdersParam",
"path": "boost.common/src/main/java/org/example/common/param/ListOrdersParam.java",
"snippet": "@Data\npublic class ListOrdersParam {\n\n private String serviceInstanceId;\n\n private String startTime;\n\n private String endTime;\n\n private TradeStatus tradeStatus;\n\n private Integer maxResults;\n\n private String nextToken;\n}"
},
{
"identifier": "RefundOrderParam",
"path": "boost.common/src/main/java/org/example/common/param/RefundOrderParam.java",
"snippet": "@Data\npublic class RefundOrderParam {\n\n private String orderId;\n\n @NotNull\n private Boolean dryRun;\n\n private String serviceInstanceId;\n\n private PaymentType paymentType;\n}"
},
{
"identifier": "OrderService",
"path": "boost.server/src/main/java/org/example/service/OrderService.java",
"snippet": "public interface OrderService {\n\n /**\n * Create Alipay order.\n * @param param CreateOrder\n * @param userInfoModel user information\n * @return {@link BaseResult <String>}\n * @throws AlipayApiException external exception\n */\n BaseResult<String> createOrder(UserInfoModel userInfoModel, CreateOrderParam param) throws AlipayApiException;\n\n /**\n * Get a row of order from table store:order.\n * @param param GetOrderParam\n * @param userInfoModel UserInfo\n * @return {@link BaseResult<String>}\n */\n BaseResult<OrderDTO> getOrder(UserInfoModel userInfoModel, GetOrderParam param);\n\n /**\n * List orders from table store:order.\n * @param param ListOrdersParam\n * @param userInfoModel UserInfo\n * @return {@link ListResult <OrderDTO>}\n */\n ListResult<OrderDTO> listOrders(UserInfoModel userInfoModel, ListOrdersParam param);\n\n /**\n * Update table store:order.\n * @param userInfoModel user info\n * @param param Order data object\n */\n void updateOrder(UserInfoModel userInfoModel, OrderDO param);\n\n /**\n * Order refund.\n * @param param param\n * @param userInfoModel user info\n * @return true or false\n */\n BaseResult<Double> refundOrder(UserInfoModel userInfoModel, RefundOrderParam param);\n}"
}
] | import com.alipay.api.AlipayApiException;
import org.example.common.BaseResult;
import org.example.common.ListResult;
import org.example.common.dto.OrderDTO;
import org.example.common.model.UserInfoModel;
import org.example.common.param.CreateOrderParam;
import org.example.common.param.GetOrderParam;
import org.example.common.param.ListOrdersParam;
import org.example.common.param.RefundOrderParam;
import org.example.service.OrderService;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.slf4j.Logger;
import java.util.Arrays;
import static org.mockito.Mockito.*; | 2,605 | /*
*Copyright (c) Alibaba Group;
*Licensed under the Apache License, Version 2.0 (the "License");
*you may not use this file except in compliance with the License.
*You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*Unless required by applicable law or agreed to in writing, software
*distributed under the License is distributed on an "AS IS" BASIS,
*WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*See the License for the specific language governing permissions and
*limitations under the License.
*/
package org.example.controller;
class OrderControllerTest {
@Mock
OrderService orderService;
@Mock
Logger log;
@InjectMocks
OrderController orderController;
@BeforeEach
void setUp() {
MockitoAnnotations.initMocks(this);
}
@Test
void testCreateOrder() throws AlipayApiException {
when(orderService.createOrder(any(), any())).thenReturn(new BaseResult<String>("code", "message", "data", "requestId"));
| /*
*Copyright (c) Alibaba Group;
*Licensed under the Apache License, Version 2.0 (the "License");
*you may not use this file except in compliance with the License.
*You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*Unless required by applicable law or agreed to in writing, software
*distributed under the License is distributed on an "AS IS" BASIS,
*WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*See the License for the specific language governing permissions and
*limitations under the License.
*/
package org.example.controller;
class OrderControllerTest {
@Mock
OrderService orderService;
@Mock
Logger log;
@InjectMocks
OrderController orderController;
@BeforeEach
void setUp() {
MockitoAnnotations.initMocks(this);
}
@Test
void testCreateOrder() throws AlipayApiException {
when(orderService.createOrder(any(), any())).thenReturn(new BaseResult<String>("code", "message", "data", "requestId"));
| BaseResult<String> result = orderController.createOrder(new UserInfoModel("sub", "name", "loginName", "aid", "uid"), new CreateOrderParam()); | 4 | 2023-11-01 08:19:34+00:00 | 4k |
softwaremill/jox | core/src/main/java/com/softwaremill/jox/Channel.java | [
{
"identifier": "CellState",
"path": "core/src/main/java/com/softwaremill/jox/Channel.java",
"snippet": "enum CellState {\n DONE,\n INTERRUPTED_SEND, // the send/receive differentiation is important for expandBuffer\n INTERRUPTED_RECEIVE,\n BROKEN,\n IN_BUFFER, // used to inform a potentially concurrent sender that the cell is now in the buffer\n RESUMING, // expandBuffer is resuming a sender\n CLOSED\n}"
},
{
"identifier": "findAndMoveForward",
"path": "core/src/main/java/com/softwaremill/jox/Segment.java",
"snippet": "static Segment findAndMoveForward(AtomicReference<Segment> ref, Segment start, long id) {\n while (true) {\n var segment = findSegment(start, id);\n if (segment == null) {\n return null;\n }\n if (moveForward(ref, segment)) {\n return segment;\n }\n }\n}"
}
] | import java.lang.invoke.MethodHandles;
import java.lang.invoke.VarHandle;
import java.util.Comparator;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.LockSupport;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Stream;
import static com.softwaremill.jox.CellState.*;
import static com.softwaremill.jox.Segment.findAndMoveForward; | 2,516 | package com.softwaremill.jox;
/**
* Channel is a thread-safe data structure which exposes three basic operations:
* <p>
* - {@link Channel#send(Object)}-ing a value to the channel
* - {@link Channel#receive()}-ing a value from the channel
* - closing the channel using {@link Channel#done()} or {@link Channel#error(Throwable)}
* <p>
* There are three channel flavors:
* <p>
* - rendezvous channels, where senders and receivers must meet to exchange values
* - buffered channels, where a given number of sent elements might be buffered, before subsequent `send`s block
* - unlimited channels, where an unlimited number of elements might be buffered, hence `send` never blocks
* <p>
* The no-argument {@link Channel} constructor creates a rendezvous channel, while a buffered channel can be created
* by providing a positive integer to the constructor. A rendezvous channel behaves like a buffered channel with
* buffer size 0. An unlimited channel can be created using {@link Channel#newUnlimitedChannel()}.
* <p>
* In a rendezvous channel, senders and receivers block, until a matching party arrives (unless one is already waiting).
* Similarly, buffered channels block if the buffer is full (in case of senders), or in case of receivers, if the
* buffer is empty and there are no waiting senders.
* <p>
* All blocking operations behave properly upon interruption.
* <p>
* Channels might be closed, either because no more elements will be produced by the source (using
* {@link Channel#done()}), or because there was an error while producing or processing the received elements (using
* {@link Channel#error(Throwable)}).
* <p>
* After closing, no more elements can be sent to the channel. If the channel is "done", any pending sends will be
* completed normally. If the channel is in an "error" state, pending sends will be interrupted and will return with
* the reason for the closure.
* <p>
* In case the channel is closed, one of the {@link ChannelClosedException}s is thrown. Alternatively, you can call
* the less type-safe, but more exception-safe {@link Channel#sendSafe(Object)} and {@link Channel#receiveSafe()}
* methods, which do not throw in case the channel is closed, but return one of the {@link ChannelClosed} values.
*
* @param <T> The type of the elements processed by the channel.
*/
public final class Channel<T> {
/*
Inspired by the "Fast and Scalable Channels in Kotlin Coroutines" paper (https://arxiv.org/abs/2211.04986), and
the Kotlin implementation (https://github.com/Kotlin/kotlinx.coroutines/blob/master/kotlinx-coroutines-core/common/src/channels/BufferedChannel.kt).
Notable differences from the Kotlin implementation:
* we block (virtual) threads, instead of suspend functions
* in Kotlin's channels, the buffer stores both the elements (in even indexes), and the state for each cell (in odd
indexes). This would be also possible here, but in two-thread rendezvous tests, this is slightly slower than the
approach below: we transmit the elements inside objects representing state. This does incur an additional
allocation in case of the `Buffered` state (when there's a waiting receiver - we can't simply use a constant).
However, we add a field to `Continuation` (which is a channel-specific class, unlike in Kotlin), to avoid the
allocation when the sender suspends.
* as we don't directly store elements in the buffer, we don't need to clear them on interrupt etc. This is done
automatically when the cell's state is set to something else than a Continuation/Buffered.
* instead of the `completedExpandBuffersAndPauseFlag` counter, we maintain a counter of cells which haven't been
interrupted & processed by `expandBuffer` in each segment. The segment becomes logically removed, only once all
cells have been interrupted, processed & there are no pointers. The segment is notified that a cell is interrupted
directly from `Continuation`, and that a cell is processed after `expandBuffer` completes.
* the close procedure is a bit different - the Kotlin version does this "cooperatively", that is multiple threads
that observe that the channel is closing participate in appropriate state mutations. This doesn't seem to be
necessary in this implementation. Instead, `close()` sets the closed flag and closes the segment chain - which
constraints the number of cells to close. `send()` observes the closed status right away, `receive()` observes
it via the closed segment chain, or via closed cells. Same as in Kotlin, the cells are closed in reverse order.
All eligible cells are attempted to be closed, so it's guaranteed that each operation will observe the closing
appropriately.
Other notes:
* we need the previous pointers in segments to physically remove segments full of cells in the interrupted state.
Segments before such an interrupted segments might still hold awaiting continuations. When physically removing a
segment, we need to update the `next` pointer of the `previous` ("alive") segment. That way the memory usage is
bounded by the number of awaiting threads.
* after a `send`, if we know that R > s, or after a `receive`, when we know that S > r, we can set the `previous`
pointer in the segment to `null`, so that the previous segments can be GCd. Even if there are still ongoing
operations on these (previous) segments, and we'll end up wanting to remove such a segment, subsequent channel
operations won't use them, so the relinking won't be useful.
*/
private final int capacity;
/**
* The total number of `send` operations ever invoked, and a flag indicating if the channel is closed.
* The flag is shifted by {@link Channel#SENDERS_AND_CLOSED_FLAG_SHIFT} bits.
* <p>
* Each {@link Channel#send} invocation gets a unique cell to process.
*/
private final AtomicLong sendersAndClosedFlag = new AtomicLong(0L);
private final AtomicLong receivers = new AtomicLong(0L);
private final AtomicLong bufferEnd;
/**
* Segments holding cell states. State can be {@link CellState}, {@link Buffered}, or {@link Continuation}.
*/
private final AtomicReference<Segment> sendSegment;
private final AtomicReference<Segment> receiveSegment;
private final AtomicReference<Segment> bufferEndSegment;
private final AtomicReference<ChannelClosed> closedReason;
private final boolean isRendezvous;
private final boolean isUnlimited;
/**
* Creates a rendezvous channel.
*/
public Channel() {
this(0);
}
/**
* Creates a buffered channel (when capacity is positive), or a rendezvous channel if the capacity is 0.
*/
public Channel(int capacity) {
if (capacity < UNLIMITED_CAPACITY) {
throw new IllegalArgumentException("Capacity must be 0 (rendezvous), positive (buffered) or -1 (unlimited channels).");
}
this.capacity = capacity;
isRendezvous = capacity == 0L;
isUnlimited = capacity == UNLIMITED_CAPACITY;
var isRendezvousOrUnlimited = isRendezvous || isUnlimited;
var firstSegment = new Segment(0, null, isRendezvousOrUnlimited ? 2 : 3, isRendezvousOrUnlimited);
sendSegment = new AtomicReference<>(firstSegment);
receiveSegment = new AtomicReference<>(firstSegment);
// If the capacity is 0 or -1, buffer expansion never happens, so the buffer end segment points to a null segment,
// not the first one. This is also reflected in the pointer counter of firstSegment.
bufferEndSegment = new AtomicReference<>(isRendezvousOrUnlimited ? Segment.NULL_SEGMENT : firstSegment);
bufferEnd = new AtomicLong(capacity);
closedReason = new AtomicReference<>(null);
}
public static <T> Channel<T> newUnlimitedChannel() {
return new Channel<>(UNLIMITED_CAPACITY);
}
private static final int UNLIMITED_CAPACITY = -1;
// *******
// Sending
// *******
/**
* Send a value to the channel.
*
* @param value The value to send. Not {@code null}.
* @throws ChannelClosedException When the channel is closed.
*/
public void send(T value) throws InterruptedException {
var r = sendSafe(value);
if (r instanceof ChannelClosed c) {
throw c.toException();
}
}
/**
* Send a value to the channel. Doesn't throw exceptions when the channel is closed, but returns a value.
*
* @param value The value to send. Not {@code null}.
* @return Either {@code null}, or {@link ChannelClosed}, when the channel is closed.
*/
public Object sendSafe(T value) throws InterruptedException {
return doSend(value, null, null);
}
/**
* @return If {@code select} & {@code selectClause} is {@code null}: {@code null} when the value was sent, or
* {@link ChannelClosed}, when the channel is closed. Otherwise, might also return {@link StoredSelectClause}.
*/
private Object doSend(T value, SelectInstance select, SelectClause<?> selectClause) throws InterruptedException {
if (value == null) {
throw new NullPointerException();
}
while (true) {
// reading the segment before the counter increment - this is needed to find the required segment later
var segment = sendSegment.get();
// reserving the next cell
var scf = sendersAndClosedFlag.getAndIncrement();
if (isClosed(scf)) {
return closedReason.get();
}
var s = getSendersCounter(scf);
// calculating the segment id and the index within the segment
var id = s / Segment.SEGMENT_SIZE;
var i = (int) (s % Segment.SEGMENT_SIZE);
// check if `sendSegment` stores a previous segment, if so move the reference forward
if (segment.getId() != id) { | package com.softwaremill.jox;
/**
* Channel is a thread-safe data structure which exposes three basic operations:
* <p>
* - {@link Channel#send(Object)}-ing a value to the channel
* - {@link Channel#receive()}-ing a value from the channel
* - closing the channel using {@link Channel#done()} or {@link Channel#error(Throwable)}
* <p>
* There are three channel flavors:
* <p>
* - rendezvous channels, where senders and receivers must meet to exchange values
* - buffered channels, where a given number of sent elements might be buffered, before subsequent `send`s block
* - unlimited channels, where an unlimited number of elements might be buffered, hence `send` never blocks
* <p>
* The no-argument {@link Channel} constructor creates a rendezvous channel, while a buffered channel can be created
* by providing a positive integer to the constructor. A rendezvous channel behaves like a buffered channel with
* buffer size 0. An unlimited channel can be created using {@link Channel#newUnlimitedChannel()}.
* <p>
* In a rendezvous channel, senders and receivers block, until a matching party arrives (unless one is already waiting).
* Similarly, buffered channels block if the buffer is full (in case of senders), or in case of receivers, if the
* buffer is empty and there are no waiting senders.
* <p>
* All blocking operations behave properly upon interruption.
* <p>
* Channels might be closed, either because no more elements will be produced by the source (using
* {@link Channel#done()}), or because there was an error while producing or processing the received elements (using
* {@link Channel#error(Throwable)}).
* <p>
* After closing, no more elements can be sent to the channel. If the channel is "done", any pending sends will be
* completed normally. If the channel is in an "error" state, pending sends will be interrupted and will return with
* the reason for the closure.
* <p>
* In case the channel is closed, one of the {@link ChannelClosedException}s is thrown. Alternatively, you can call
* the less type-safe, but more exception-safe {@link Channel#sendSafe(Object)} and {@link Channel#receiveSafe()}
* methods, which do not throw in case the channel is closed, but return one of the {@link ChannelClosed} values.
*
* @param <T> The type of the elements processed by the channel.
*/
public final class Channel<T> {
/*
Inspired by the "Fast and Scalable Channels in Kotlin Coroutines" paper (https://arxiv.org/abs/2211.04986), and
the Kotlin implementation (https://github.com/Kotlin/kotlinx.coroutines/blob/master/kotlinx-coroutines-core/common/src/channels/BufferedChannel.kt).
Notable differences from the Kotlin implementation:
* we block (virtual) threads, instead of suspend functions
* in Kotlin's channels, the buffer stores both the elements (in even indexes), and the state for each cell (in odd
indexes). This would be also possible here, but in two-thread rendezvous tests, this is slightly slower than the
approach below: we transmit the elements inside objects representing state. This does incur an additional
allocation in case of the `Buffered` state (when there's a waiting receiver - we can't simply use a constant).
However, we add a field to `Continuation` (which is a channel-specific class, unlike in Kotlin), to avoid the
allocation when the sender suspends.
* as we don't directly store elements in the buffer, we don't need to clear them on interrupt etc. This is done
automatically when the cell's state is set to something else than a Continuation/Buffered.
* instead of the `completedExpandBuffersAndPauseFlag` counter, we maintain a counter of cells which haven't been
interrupted & processed by `expandBuffer` in each segment. The segment becomes logically removed, only once all
cells have been interrupted, processed & there are no pointers. The segment is notified that a cell is interrupted
directly from `Continuation`, and that a cell is processed after `expandBuffer` completes.
* the close procedure is a bit different - the Kotlin version does this "cooperatively", that is multiple threads
that observe that the channel is closing participate in appropriate state mutations. This doesn't seem to be
necessary in this implementation. Instead, `close()` sets the closed flag and closes the segment chain - which
constraints the number of cells to close. `send()` observes the closed status right away, `receive()` observes
it via the closed segment chain, or via closed cells. Same as in Kotlin, the cells are closed in reverse order.
All eligible cells are attempted to be closed, so it's guaranteed that each operation will observe the closing
appropriately.
Other notes:
* we need the previous pointers in segments to physically remove segments full of cells in the interrupted state.
Segments before such an interrupted segments might still hold awaiting continuations. When physically removing a
segment, we need to update the `next` pointer of the `previous` ("alive") segment. That way the memory usage is
bounded by the number of awaiting threads.
* after a `send`, if we know that R > s, or after a `receive`, when we know that S > r, we can set the `previous`
pointer in the segment to `null`, so that the previous segments can be GCd. Even if there are still ongoing
operations on these (previous) segments, and we'll end up wanting to remove such a segment, subsequent channel
operations won't use them, so the relinking won't be useful.
*/
private final int capacity;
/**
* The total number of `send` operations ever invoked, and a flag indicating if the channel is closed.
* The flag is shifted by {@link Channel#SENDERS_AND_CLOSED_FLAG_SHIFT} bits.
* <p>
* Each {@link Channel#send} invocation gets a unique cell to process.
*/
private final AtomicLong sendersAndClosedFlag = new AtomicLong(0L);
private final AtomicLong receivers = new AtomicLong(0L);
private final AtomicLong bufferEnd;
/**
* Segments holding cell states. State can be {@link CellState}, {@link Buffered}, or {@link Continuation}.
*/
private final AtomicReference<Segment> sendSegment;
private final AtomicReference<Segment> receiveSegment;
private final AtomicReference<Segment> bufferEndSegment;
private final AtomicReference<ChannelClosed> closedReason;
private final boolean isRendezvous;
private final boolean isUnlimited;
/**
* Creates a rendezvous channel.
*/
public Channel() {
this(0);
}
/**
* Creates a buffered channel (when capacity is positive), or a rendezvous channel if the capacity is 0.
*/
public Channel(int capacity) {
if (capacity < UNLIMITED_CAPACITY) {
throw new IllegalArgumentException("Capacity must be 0 (rendezvous), positive (buffered) or -1 (unlimited channels).");
}
this.capacity = capacity;
isRendezvous = capacity == 0L;
isUnlimited = capacity == UNLIMITED_CAPACITY;
var isRendezvousOrUnlimited = isRendezvous || isUnlimited;
var firstSegment = new Segment(0, null, isRendezvousOrUnlimited ? 2 : 3, isRendezvousOrUnlimited);
sendSegment = new AtomicReference<>(firstSegment);
receiveSegment = new AtomicReference<>(firstSegment);
// If the capacity is 0 or -1, buffer expansion never happens, so the buffer end segment points to a null segment,
// not the first one. This is also reflected in the pointer counter of firstSegment.
bufferEndSegment = new AtomicReference<>(isRendezvousOrUnlimited ? Segment.NULL_SEGMENT : firstSegment);
bufferEnd = new AtomicLong(capacity);
closedReason = new AtomicReference<>(null);
}
public static <T> Channel<T> newUnlimitedChannel() {
return new Channel<>(UNLIMITED_CAPACITY);
}
private static final int UNLIMITED_CAPACITY = -1;
// *******
// Sending
// *******
/**
* Send a value to the channel.
*
* @param value The value to send. Not {@code null}.
* @throws ChannelClosedException When the channel is closed.
*/
public void send(T value) throws InterruptedException {
var r = sendSafe(value);
if (r instanceof ChannelClosed c) {
throw c.toException();
}
}
/**
* Send a value to the channel. Doesn't throw exceptions when the channel is closed, but returns a value.
*
* @param value The value to send. Not {@code null}.
* @return Either {@code null}, or {@link ChannelClosed}, when the channel is closed.
*/
public Object sendSafe(T value) throws InterruptedException {
return doSend(value, null, null);
}
/**
* @return If {@code select} & {@code selectClause} is {@code null}: {@code null} when the value was sent, or
* {@link ChannelClosed}, when the channel is closed. Otherwise, might also return {@link StoredSelectClause}.
*/
private Object doSend(T value, SelectInstance select, SelectClause<?> selectClause) throws InterruptedException {
if (value == null) {
throw new NullPointerException();
}
while (true) {
// reading the segment before the counter increment - this is needed to find the required segment later
var segment = sendSegment.get();
// reserving the next cell
var scf = sendersAndClosedFlag.getAndIncrement();
if (isClosed(scf)) {
return closedReason.get();
}
var s = getSendersCounter(scf);
// calculating the segment id and the index within the segment
var id = s / Segment.SEGMENT_SIZE;
var i = (int) (s % Segment.SEGMENT_SIZE);
// check if `sendSegment` stores a previous segment, if so move the reference forward
if (segment.getId() != id) { | segment = findAndMoveForward(sendSegment, segment, id); | 1 | 2023-11-08 12:58:16+00:00 | 4k |
mioclient/oyvey-ported | src/main/java/me/alpha432/oyvey/manager/ColorManager.java | [
{
"identifier": "Component",
"path": "src/main/java/me/alpha432/oyvey/features/gui/Component.java",
"snippet": "public class Component\n extends Feature {\n public static int[] counter1 = new int[]{1};\n protected DrawContext context;\n private final List<Item> items = new ArrayList<>();\n public boolean drag;\n private int x;\n private int y;\n private int x2;\n private int y2;\n private int width;\n private int height;\n private boolean open;\n private boolean hidden = false;\n\n public Component(String name, int x, int y, boolean open) {\n super(name);\n this.x = x;\n this.y = y;\n this.width = 88;\n this.height = 18;\n this.open = open;\n this.setupItems();\n }\n\n public void setupItems() {\n }\n\n private void drag(int mouseX, int mouseY) {\n if (!this.drag) {\n return;\n }\n this.x = this.x2 + mouseX;\n this.y = this.y2 + mouseY;\n }\n\n public void drawScreen(DrawContext context, int mouseX, int mouseY, float partialTicks) {\n this.context = context;\n this.drag(mouseX, mouseY);\n counter1 = new int[]{1};\n float totalItemHeight = this.open ? this.getTotalItemHeight() - 2.0f : 0.0f;\n int color = ColorUtil.toARGB(ClickGui.getInstance().topRed.getValue(), ClickGui.getInstance().topGreen.getValue(), ClickGui.getInstance().topBlue.getValue(), 255);\n context.fill(this.x, this.y - 1, this.x + this.width, this.y + this.height - 6, ClickGui.getInstance().rainbow.getValue() ? ColorUtil.rainbow(ClickGui.getInstance().rainbowHue.getValue()).getRGB() : color);\n if (this.open) {\n RenderUtil.rect(context.getMatrices(), this.x, (float) this.y + 12.5f, this.x + this.width, (float) (this.y + this.height) + totalItemHeight, 0x77000000);\n }\n drawString(this.getName(), (float) this.x + 3.0f, (float) this.y - 4.0f - (float) OyVeyGui.getClickGui().getTextOffset(), -1);\n if (this.open) {\n float y = (float) (this.getY() + this.getHeight()) - 3.0f;\n for (Item item : this.getItems()) {\n Component.counter1[0] = counter1[0] + 1;\n if (item.isHidden()) continue;\n item.setLocation((float) this.x + 2.0f, y);\n item.setWidth(this.getWidth() - 4);\n item.drawScreen(context, mouseX, mouseY, partialTicks);\n y += (float) item.getHeight() + 1.5f;\n }\n }\n }\n\n public void mouseClicked(int mouseX, int mouseY, int mouseButton) {\n if (mouseButton == 0 && this.isHovering(mouseX, mouseY)) {\n this.x2 = this.x - mouseX;\n this.y2 = this.y - mouseY;\n OyVeyGui.getClickGui().getComponents().forEach(component -> {\n if (component.drag) {\n component.drag = false;\n }\n });\n this.drag = true;\n return;\n }\n if (mouseButton == 1 && this.isHovering(mouseX, mouseY)) {\n this.open = !this.open;\n mc.getSoundManager().play(PositionedSoundInstance.master(SoundEvents.UI_BUTTON_CLICK, 1f));\n return;\n }\n if (!this.open) {\n return;\n }\n this.getItems().forEach(item -> item.mouseClicked(mouseX, mouseY, mouseButton));\n }\n\n public void mouseReleased(int mouseX, int mouseY, int releaseButton) {\n if (releaseButton == 0) {\n this.drag = false;\n }\n if (!this.open) {\n return;\n }\n this.getItems().forEach(item -> item.mouseReleased(mouseX, mouseY, releaseButton));\n }\n\n public void onKeyTyped(char typedChar, int keyCode) {\n if (!this.open) {\n return;\n }\n this.getItems().forEach(item -> item.onKeyTyped(typedChar, keyCode));\n }\n\n public void onKeyPressed(int key) {\n if (!open) return;\n this.getItems().forEach(item -> item.onKeyPressed(key));\n }\n\n public void addButton(Button button) {\n this.items.add(button);\n }\n\n public int getX() {\n return this.x;\n }\n\n public void setX(int x) {\n this.x = x;\n }\n\n public int getY() {\n return this.y;\n }\n\n public void setY(int y) {\n this.y = y;\n }\n\n public int getWidth() {\n return this.width;\n }\n\n public void setWidth(int width) {\n this.width = width;\n }\n\n public int getHeight() {\n return this.height;\n }\n\n public void setHeight(int height) {\n this.height = height;\n }\n\n public boolean isHidden() {\n return this.hidden;\n }\n\n public void setHidden(boolean hidden) {\n this.hidden = hidden;\n }\n\n public boolean isOpen() {\n return this.open;\n }\n\n public final List<Item> getItems() {\n return this.items;\n }\n\n private boolean isHovering(int mouseX, int mouseY) {\n return mouseX >= this.getX() && mouseX <= this.getX() + this.getWidth() && mouseY >= this.getY() && mouseY <= this.getY() + this.getHeight() - (this.open ? 2 : 0);\n }\n\n private float getTotalItemHeight() {\n float height = 0.0f;\n for (Item item : this.getItems()) {\n height += (float) item.getHeight() + 1.5f;\n }\n return height;\n }\n\n protected void drawString(String text, double x, double y, Color color) {\n drawString(text, x, y, color.hashCode());\n }\n\n protected void drawString(String text, double x, double y, int color) {\n context.drawTextWithShadow(mc.textRenderer, text, (int) x, (int) y, color);\n }\n}"
},
{
"identifier": "ClickGui",
"path": "src/main/java/me/alpha432/oyvey/features/modules/client/ClickGui.java",
"snippet": "public class ClickGui\n extends Module {\n private static ClickGui INSTANCE = new ClickGui();\n public Setting<String> prefix = this.register(new Setting<>(\"Prefix\", \".\"));\n public Setting<Boolean> customFov = this.register(new Setting<>(\"CustomFov\", false));\n public Setting<Float> fov = this.register(new Setting<>(\"Fov\", 150f, -180f, 180f));\n public Setting<Integer> red = this.register(new Setting<>(\"Red\", 0, 0, 255));\n public Setting<Integer> green = this.register(new Setting<>(\"Green\", 0, 0, 255));\n public Setting<Integer> blue = this.register(new Setting<>(\"Blue\", 255, 0, 255));\n public Setting<Integer> hoverAlpha = this.register(new Setting<>(\"Alpha\", 180, 0, 255));\n public Setting<Integer> topRed = this.register(new Setting<>(\"SecondRed\", 0, 0, 255));\n public Setting<Integer> topGreen = this.register(new Setting<>(\"SecondGreen\", 0, 0, 255));\n public Setting<Integer> topBlue = this.register(new Setting<>(\"SecondBlue\", 150, 0, 255));\n public Setting<Integer> alpha = this.register(new Setting<>(\"HoverAlpha\", 240, 0, 255));\n public Setting<Boolean> rainbow = this.register(new Setting<>(\"Rainbow\", false));\n public Setting<rainbowMode> rainbowModeHud = this.register(new Setting<>(\"HRainbowMode\", rainbowMode.Static, v -> this.rainbow.getValue()));\n public Setting<rainbowModeArray> rainbowModeA = this.register(new Setting<>(\"ARainbowMode\", rainbowModeArray.Static, v -> this.rainbow.getValue()));\n public Setting<Integer> rainbowHue = this.register(new Setting<>(\"Delay\", 240, 0, 600, v -> this.rainbow.getValue()));\n public Setting<Float> rainbowBrightness = this.register(new Setting<>(\"Brightness \", 150.0f, 1.0f, 255.0f, v -> this.rainbow.getValue()));\n public Setting<Float> rainbowSaturation = this.register(new Setting<>(\"Saturation\", 150.0f, 1.0f, 255.0f, v -> this.rainbow.getValue()));\n private OyVeyGui click;\n\n public ClickGui() {\n super(\"ClickGui\", \"Opens the ClickGui\", Module.Category.CLIENT, true, false, false);\n setBind(GLFW.GLFW_KEY_RIGHT_SHIFT);\n this.setInstance();\n }\n\n public static ClickGui getInstance() {\n if (INSTANCE == null) {\n INSTANCE = new ClickGui();\n }\n return INSTANCE;\n }\n\n private void setInstance() {\n INSTANCE = this;\n }\n\n @Override\n public void onUpdate() {\n if (this.customFov.getValue().booleanValue()) {\n mc.options.getFov().setValue(this.fov.getValue().intValue());\n }\n }\n\n @Subscribe\n public void onSettingChange(ClientEvent event) {\n if (event.getStage() == 2 && event.getSetting().getFeature().equals(this)) {\n if (event.getSetting().equals(this.prefix)) {\n OyVey.commandManager.setPrefix(this.prefix.getPlannedValue());\n Command.sendMessage(\"Prefix set to \" + Formatting.DARK_GRAY + OyVey.commandManager.getPrefix());\n }\n OyVey.colorManager.setColor(this.red.getPlannedValue(), this.green.getPlannedValue(), this.blue.getPlannedValue(), this.hoverAlpha.getPlannedValue());\n }\n }\n\n @Override\n public void onEnable() {\n mc.setScreen(OyVeyGui.getClickGui());\n }\n\n @Override\n public void onLoad() {\n OyVey.colorManager.setColor(this.red.getValue(), this.green.getValue(), this.blue.getValue(), this.hoverAlpha.getValue());\n OyVey.commandManager.setPrefix(this.prefix.getValue());\n }\n\n @Override\n public void onTick() {\n if (!(ClickGui.mc.currentScreen instanceof OyVeyGui)) {\n this.disable();\n }\n }\n\n public enum rainbowModeArray {\n Static,\n Up\n\n }\n\n public enum rainbowMode {\n Static,\n Sideway\n\n }\n}"
},
{
"identifier": "ColorUtil",
"path": "src/main/java/me/alpha432/oyvey/util/ColorUtil.java",
"snippet": "public class ColorUtil {\n public static int toARGB(int r, int g, int b, int a) {\n return new Color(r, g, b, a).getRGB();\n }\n\n public static int toRGBA(int r, int g, int b) {\n return ColorUtil.toRGBA(r, g, b, 255);\n }\n\n public static int toRGBA(int r, int g, int b, int a) {\n return (r << 16) + (g << 8) + b + (a << 24);\n }\n\n public static int toRGBA(float r, float g, float b, float a) {\n return ColorUtil.toRGBA((int) (r * 255.0f), (int) (g * 255.0f), (int) (b * 255.0f), (int) (a * 255.0f));\n }\n\n public static Color rainbow(int delay) {\n double rainbowState = Math.ceil((double) (System.currentTimeMillis() + (long) delay) / 20.0);\n return Color.getHSBColor((float) ((rainbowState %= 360.0) / 360.0), ClickGui.getInstance().rainbowSaturation.getValue().floatValue() / 255.0f, ClickGui.getInstance().rainbowBrightness.getValue().floatValue() / 255.0f);\n }\n\n public static int toRGBA(float[] colors) {\n if (colors.length != 4) {\n throw new IllegalArgumentException(\"colors[] must have a length of 4!\");\n }\n return ColorUtil.toRGBA(colors[0], colors[1], colors[2], colors[3]);\n }\n\n public static int toRGBA(double[] colors) {\n if (colors.length != 4) {\n throw new IllegalArgumentException(\"colors[] must have a length of 4!\");\n }\n return ColorUtil.toRGBA((float) colors[0], (float) colors[1], (float) colors[2], (float) colors[3]);\n }\n\n public static int toRGBA(Color color) {\n return ColorUtil.toRGBA(color.getRed(), color.getGreen(), color.getBlue(), color.getAlpha());\n }\n}"
}
] | import me.alpha432.oyvey.features.gui.Component;
import me.alpha432.oyvey.features.modules.client.ClickGui;
import me.alpha432.oyvey.util.ColorUtil;
import java.awt.*; | 3,289 | package me.alpha432.oyvey.manager;
public class ColorManager {
private float red = 1.0f;
private float green = 1.0f;
private float blue = 1.0f;
private float alpha = 1.0f;
private Color color = new Color(this.red, this.green, this.blue, this.alpha);
public void init() {
ClickGui ui = ClickGui.getInstance();
setColor(ui.red.getValue(), ui.green.getValue(), ui.blue.getValue(), ui.hoverAlpha.getValue());
}
public Color getColor() {
return this.color;
}
public void setColor(Color color) {
this.color = color;
}
public int getColorAsInt() { | package me.alpha432.oyvey.manager;
public class ColorManager {
private float red = 1.0f;
private float green = 1.0f;
private float blue = 1.0f;
private float alpha = 1.0f;
private Color color = new Color(this.red, this.green, this.blue, this.alpha);
public void init() {
ClickGui ui = ClickGui.getInstance();
setColor(ui.red.getValue(), ui.green.getValue(), ui.blue.getValue(), ui.hoverAlpha.getValue());
}
public Color getColor() {
return this.color;
}
public void setColor(Color color) {
this.color = color;
}
public int getColorAsInt() { | return ColorUtil.toRGBA(this.color); | 2 | 2023-11-05 18:10:28+00:00 | 4k |
Jlan45/MCCTF | src/main/java/darkflow/mcctf/MCCTF.java | [
{
"identifier": "BlockFlagCollecter",
"path": "src/main/java/darkflow/mcctf/blocks/BlockFlagCollecter.java",
"snippet": "public class BlockFlagCollecter extends Block {\n public BlockFlagCollecter() {\n super(Settings.of(Material.ICE).hardness(-1f).dropsNothing());\n }\n @Override\n public ActionResult onUse(BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, BlockHitResult hit) {\n\n if(!world.isClient) {\n ItemStack itemStack = player.getHandItems().iterator().next();\n if (itemStack.getItem().getTranslationKey().equals(\"item.mcctf.flag\")) {\n //TODO flag验证\n String userFlag=itemStack.getNbt().getString(\"flag\");\n String questionUUID=itemStack.getNbt().getString(\"question\");\n Question tmpQuestion=new Question(\"test\", UUID.randomUUID().toString(),1000,\"\",\"\");\n try {\n if (verifyFlag(player,tmpQuestion, userFlag)) {\n player.sendMessage(Text.of(\"Flag验证成功\"), false);\n player.increaseStat(MCCTF.PLAYER_CONTEST_SCORE,tmpQuestion.getScore());\n ItemStack itemStack1 = new ItemStack(Items.AIR);\n player.setStackInHand(hand, itemStack1);\n }\n else {\n player.sendMessage(Text.of(\"Flag验证失败\"), false);\n }\n } catch (NoSuchAlgorithmException e) {\n throw new RuntimeException(e);\n }\n }\n }\n return ActionResult.SUCCESS;\n\n }\n}"
},
{
"identifier": "BlockFlagGetter",
"path": "src/main/java/darkflow/mcctf/blocks/BlockFlagGetter.java",
"snippet": "public class BlockFlagGetter extends Block {\n public BlockFlagGetter() {\n super(Settings.of(net.minecraft.block.Material.ICE).dropsNothing().strength(-1f,-1f));\n }\n\n @Override\n public ActionResult onUse(BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, BlockHitResult hit) {\n if(!world.isClient) {\n NbtCompound tag = new NbtCompound();\n tag.putString(\"flag\", \"FLAG{TEST}\");\n ItemStack itemStack = new ItemStack(FLAG);\n itemStack.setNbt(tag);\n player.giveItemStack(itemStack);\n }\n// else{\n// player.sendMessage(Text.of(\"要在服务器上跑才可以哦\"));\n// }\n return ActionResult.SUCCESS;\n\n\n }\n}"
},
{
"identifier": "TestCommand",
"path": "src/main/java/darkflow/mcctf/commands/TestCommand.java",
"snippet": "public class TestCommand {\n public static void register(CommandDispatcher<ServerCommandSource> dispatcher){\n dispatcher.register(literal(\"test\")\n .requires(source -> source.hasPermissionLevel(0)) // 只有管理员能够执行命令。命令不会对非操作员或低于 1 级权限的玩家显示在 tab-完成中,也不会让他们执行。\n .then(argument(\"message\", greedyString())\n .executes(ctx -> test(ctx.getSource(), getString(ctx, \"message\"))))); // 你可以在这里处理参数,并处理成命令。\n }\n\n public static int test(ServerCommandSource source, String message) {\n ServerPlayerEntity player=source.getPlayer();\n //获取玩家死亡次数\n StatHandler sh=player.getStatHandler();\n player.increaseStat(PLAYER_CONTEST_SCORE,1);\n player.resetStat(Stats.CUSTOM.getOrCreateStat(PLAYER_CONTEST_SCORE));\n int score=sh.getStat(Stats.CUSTOM.getOrCreateStat(PLAYER_CONTEST_SCORE));\n player.sendMessage(Text.of(\"你的分数是\"+score),false);\n return Command.SINGLE_SUCCESS; // 成功\n }\n}"
},
{
"identifier": "ItemFlag",
"path": "src/main/java/darkflow/mcctf/items/ItemFlag.java",
"snippet": "public class ItemFlag extends Item {\n public ItemFlag() {\n super(new FabricItemSettings().maxCount(1).rarity(Rarity.EPIC));\n }\n\n\n\n @Override\n public ActionResult useOnBlock(ItemUsageContext context) {\n if (!context.getWorld().isClient) {\n if(context.getPlayer()!=null){\n context.getPlayer().sendMessage(Text.of(\"Flag应该放到Flag箱里\"));\n }\n }\n return ActionResult.SUCCESS;\n }\n\n\n// @Override\n// public void appendTooltip(ItemStack itemStack, World world, List<Text> tooltip, TooltipContext tooltipContext) {\n// // 默认为白色文本\n// tooltip.add(Text.of(\"flag{thisisflag}\"));\n// }\n\n}"
},
{
"identifier": "ItemFlagCollecter",
"path": "src/main/java/darkflow/mcctf/items/ItemFlagCollecter.java",
"snippet": "public class ItemFlagCollecter extends BlockItem {\n\n public ItemFlagCollecter(Block block, Item.Settings settings) {\n super(block, settings);\n }\n}"
},
{
"identifier": "ItemFlagGetter",
"path": "src/main/java/darkflow/mcctf/items/ItemFlagGetter.java",
"snippet": "public class ItemFlagGetter extends BlockItem {\n public ItemFlagGetter(Block block, Settings settings) {\n super(block, settings);\n }\n}"
}
] | import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.tree.LiteralCommandNode;
import darkflow.mcctf.blocks.BlockFlagCollecter;
import darkflow.mcctf.blocks.BlockFlagGetter;
import darkflow.mcctf.commands.BroadCastCommand;
import darkflow.mcctf.commands.TestCommand;
import darkflow.mcctf.items.ItemFlag;
import darkflow.mcctf.items.ItemFlagCollecter;
import darkflow.mcctf.items.ItemFlagGetter;
import net.fabricmc.api.ModInitializer;
import net.fabricmc.fabric.api.command.v2.CommandRegistrationCallback;
import net.fabricmc.fabric.api.item.v1.FabricItemSettings;
import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings;
import net.fabricmc.fabric.api.object.builder.v1.block.entity.FabricBlockEntityTypeBuilder;
import net.minecraft.block.AbstractBlock;
import net.minecraft.block.Block;
import net.minecraft.block.Blocks;
import net.minecraft.block.Material;
import net.minecraft.block.entity.BlockEntityType;
import net.minecraft.item.BlockItem;
import net.minecraft.stat.Stats;
import net.minecraft.util.Identifier;
import net.minecraft.util.Rarity;
import net.minecraft.util.registry.Registry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import static net.minecraft.client.render.entity.feature.TridentRiptideFeatureRenderer.BOX; | 1,694 | package darkflow.mcctf;
public class MCCTF implements ModInitializer {
/**
* Runs the mod initializer.
*/
public static final Logger LOGGER = LoggerFactory.getLogger("mcctf");
public static final ItemFlag FLAG=new ItemFlag();
public static final BlockFlagGetter FLAG_GETTER_BLOCK=new BlockFlagGetter();
public static final BlockFlagCollecter FLAG_COLLECTER_BLOCK=new BlockFlagCollecter();
public static final ItemFlagCollecter FLAG_COLLECTER_ITEM=new ItemFlagCollecter(FLAG_COLLECTER_BLOCK,new FabricItemSettings().maxCount(1));
public static final ItemFlagGetter FLAG_GETTER_ITEM=new ItemFlagGetter(FLAG_GETTER_BLOCK,new FabricItemSettings().maxCount(1));
public static final Identifier PLAYER_CONTEST_SCORE = new Identifier("mcctf", "contest_score");
@Override
public void onInitialize() {
CommandRegistrationCallback.EVENT.register((dispatcher, registryAccess, environment) -> BroadCastCommand.register(dispatcher)); | package darkflow.mcctf;
public class MCCTF implements ModInitializer {
/**
* Runs the mod initializer.
*/
public static final Logger LOGGER = LoggerFactory.getLogger("mcctf");
public static final ItemFlag FLAG=new ItemFlag();
public static final BlockFlagGetter FLAG_GETTER_BLOCK=new BlockFlagGetter();
public static final BlockFlagCollecter FLAG_COLLECTER_BLOCK=new BlockFlagCollecter();
public static final ItemFlagCollecter FLAG_COLLECTER_ITEM=new ItemFlagCollecter(FLAG_COLLECTER_BLOCK,new FabricItemSettings().maxCount(1));
public static final ItemFlagGetter FLAG_GETTER_ITEM=new ItemFlagGetter(FLAG_GETTER_BLOCK,new FabricItemSettings().maxCount(1));
public static final Identifier PLAYER_CONTEST_SCORE = new Identifier("mcctf", "contest_score");
@Override
public void onInitialize() {
CommandRegistrationCallback.EVENT.register((dispatcher, registryAccess, environment) -> BroadCastCommand.register(dispatcher)); | CommandRegistrationCallback.EVENT.register((dispatcher, registryAccess, environment) -> TestCommand.register(dispatcher)); | 2 | 2023-11-01 14:11:07+00:00 | 4k |
EB-wilson/TooManyItems | src/main/java/tmi/recipe/parser/DrillParser.java | [
{
"identifier": "Recipe",
"path": "src/main/java/tmi/recipe/Recipe.java",
"snippet": "public class Recipe {\n private static final EffFunc ONE_BASE = getDefaultEff(1);\n private static final EffFunc ZERO_BASE = getDefaultEff(0);\n\n /**该配方的类型,请参阅{@link RecipeType}*/\n public final RecipeType recipeType;\n /**配方的标准耗时,具体来说即该配方在100%的工作效率下执行一次生产的耗时,任意小于0的数字都被认为生产过程是连续的*/\n //meta\n public float time = -1;\n\n /**配方的产出物列表\n * @see RecipeItemStack*/\n public final OrderedMap<RecipeItem<?>, RecipeItemStack> productions = new OrderedMap<>();\n /**配方的输入材料列表\n * @see RecipeItemStack*/\n public final OrderedMap<RecipeItem<?>, RecipeItemStack> materials = new OrderedMap<>();\n\n /**配方的效率计算函数,用于给定一个输入环境参数和配方数据,计算出该配方在这个输入环境下的工作效率*/\n public EffFunc efficiency = getOneEff();\n\n //infos\n /**执行该配方的建筑/方块*/\n public RecipeItem<?> block;\n /**该配方在显示时的附加显示内容构建函数,若不设置则认为不添加任何附加信息*/\n @Nullable public Cons<Table> subInfoBuilder;\n\n public Recipe(RecipeType recipeType) {\n this.recipeType = recipeType;\n }\n\n /**用配方当前使用的效率计算器计算该配方在给定的环境参数下的运行效率*/\n public float calculateEfficiency(EnvParameter parameter) {\n return efficiency.calculateEff(this, parameter, calculateMultiple(parameter));\n }\n\n public float calculateEfficiency(EnvParameter parameter, float multiplier) {\n return efficiency.calculateEff(this, parameter, multiplier);\n }\n\n public float calculateMultiple(EnvParameter parameter) {\n return efficiency.calculateMultiple(this, parameter);\n }\n\n //utils\n\n public RecipeItemStack addMaterial(RecipeItem<?> item, int amount){\n RecipeItemStack res = time > 0?\n new RecipeItemStack(item, amount/time).setIntegerFormat(time):\n new RecipeItemStack(item, amount).setIntegerFormat();\n\n materials.put(item, res);\n return res;\n }\n\n public RecipeItemStack addMaterial(RecipeItem<?> item, float amount){\n RecipeItemStack res = time > 0?\n new RecipeItemStack(item, amount/time).setFloatFormat(time):\n new RecipeItemStack(item, amount).setFloatFormat();\n\n materials.put(item, res);\n return res;\n }\n\n public RecipeItemStack addMaterialPresec(RecipeItem<?> item, float preSeq){\n RecipeItemStack res = new RecipeItemStack(item, preSeq).setPresecFormat();\n materials.put(item, res);\n return res;\n }\n\n public RecipeItemStack addMaterialRaw(RecipeItem<?> item, float amount){\n RecipeItemStack res = new RecipeItemStack(item, amount);\n materials.put(item, res);\n return res;\n }\n\n public RecipeItemStack addProduction(RecipeItem<?> item, int amount){\n RecipeItemStack res = time > 0?\n new RecipeItemStack(item, amount/time).setIntegerFormat(time):\n new RecipeItemStack(item, amount).setIntegerFormat();\n\n productions.put(item, res);\n return res;\n }\n\n public RecipeItemStack addProduction(RecipeItem<?> item, float amount){\n RecipeItemStack res = time > 0?\n new RecipeItemStack(item, amount/time).setFloatFormat(time):\n new RecipeItemStack(item, amount).setFloatFormat();\n\n productions.put(item, res);\n return res;\n }\n\n public RecipeItemStack addProductionPresec(RecipeItem<?> item, float preSeq){\n RecipeItemStack res = new RecipeItemStack(item, preSeq).setPresecFormat();\n productions.put(item, res);\n return res;\n }\n\n public RecipeItemStack addProductionRaw(RecipeItem<?> item, float amount){\n RecipeItemStack res = new RecipeItemStack(item, amount);\n productions.put(item, res);\n return res;\n }\n\n public Recipe setBlock(RecipeItem<?> block){\n this.block = block;\n return this;\n }\n\n public Recipe setTime(float time){\n this.time = time;\n return this;\n }\n\n public Recipe setEfficiency(EffFunc func){\n efficiency = func;\n return this;\n }\n\n public boolean containsProduction(RecipeItem<?> production) {\n return productions.containsKey(production);\n }\n\n public boolean containsMaterial(RecipeItem<?> material) {\n return materials.containsKey(material);\n }\n\n /**@see Recipe#getDefaultEff(float) */\n public static EffFunc getOneEff(){\n return ONE_BASE;\n }\n\n /**@see Recipe#getDefaultEff(float) */\n public static EffFunc getZeroEff(){\n return ZERO_BASE;\n }\n\n /**生成一个适用于vanilla绝大多数工厂与设备的效率计算器,若{@linkplain RecipeParser 配方解析器}正确的解释了方块,这个函数应当能够正确计算方块的实际工作效率*/\n public static EffFunc getDefaultEff(float baseEff){\n ObjectFloatMap<Object> attrGroups = new ObjectFloatMap<>();\n\n return new EffFunc() {\n @Override\n public float calculateEff(Recipe recipe, EnvParameter env, float mul) {\n float eff = 1;\n\n attrGroups.clear();\n\n for (RecipeItemStack stack : recipe.materials.values()) {\n if (stack.isBooster || stack.isAttribute) continue;\n\n if (stack.attributeGroup != null){\n float e = attrGroups.get(stack.attributeGroup, 1)*stack.efficiency*Mathf.clamp(env.getInputs(stack.item)/(stack.amount*mul));\n if (stack.maxAttr) {\n attrGroups.put(stack.attributeGroup, Math.max(attrGroups.get(stack.attributeGroup, 0), e));\n }\n else attrGroups.increment(stack.attributeGroup, 0, e);\n }\n else eff *= Math.max(stack.efficiency*Mathf.clamp(env.getInputs(stack.item)/(stack.amount*mul)), stack.optionalCons? 1: 0);\n }\n\n ObjectFloatMap.Values v = attrGroups.values();\n while (v.hasNext()) {\n eff *= v.next();\n }\n\n return eff*mul;\n }\n\n @Override\n public float calculateMultiple(Recipe recipe, EnvParameter env) {\n attrGroups.clear();\n\n float attr = 0;\n float boost = 1;\n\n for (RecipeItemStack stack : recipe.materials.values()) {\n if (!stack.isBooster && !stack.isAttribute) continue;\n\n if (stack.isAttribute){\n float a = stack.efficiency*Mathf.clamp(env.getAttribute(stack.item)/stack.amount);\n if (stack.maxAttr) attr = Math.max(attr, a);\n else attr += a;\n }\n else {\n if (stack.attributeGroup != null){\n float e = attrGroups.get(stack.attributeGroup, 1)*stack.efficiency*Mathf.clamp(env.getInputs(stack.item)/stack.amount);\n if (stack.maxAttr) {\n attrGroups.put(stack.attributeGroup, Math.max(attrGroups.get(stack.attributeGroup, 0), e));\n }\n else attrGroups.increment(stack.attributeGroup, 0, e);\n }\n else boost *= Math.max(stack.efficiency*Mathf.clamp(env.getInputs(stack.item)/stack.amount), stack.optionalCons? 1: 0);\n }\n }\n\n ObjectFloatMap.Values v = attrGroups.values();\n while (v.hasNext()) {\n boost *= v.next();\n }\n return boost*(baseEff + attr);\n }\n };\n }\n\n @Override\n public boolean equals(Object object) {\n if (this == object) return true;\n if (!(object instanceof Recipe r)) return false;\n if (r.recipeType != recipeType || r.block != block) return false;\n\n if (r.materials.size != materials.size || r.productions.size != productions.size) return false;\n\n return r.materials.equals(materials) && r.productions.equals(productions);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(recipeType, productions.orderedKeys(), materials.orderedKeys(), block);\n }\n\n public interface EffFunc{\n float calculateEff(Recipe recipe, EnvParameter env, float mul);\n float calculateMultiple(Recipe recipe, EnvParameter env);\n }\n}"
},
{
"identifier": "RecipeType",
"path": "src/main/java/tmi/recipe/RecipeType.java",
"snippet": "public abstract class RecipeType {\n public static final Seq<RecipeType> all = new Seq<>();\n\n public static RecipeType factory,\n building,\n collecting,\n generator;\n\n /**生成{@linkplain RecipeView 配方视图}前对上下文数据进行初始化,并计算布局尺寸\n *\n * @return 表示该布局的长宽尺寸的二元向量*/\n public abstract Vec2 initial(Recipe recipe);\n /**为参数传入的{@link RecipeNode}设置坐标以完成布局*/\n public abstract void layout(RecipeNode recipeNode);\n /**生成从给定起始节点到目标节点的{@linkplain tmi.ui.RecipeView.LineMeta 线条信息}*/\n public abstract RecipeView.LineMeta line(RecipeNode from, RecipeNode to);\n public abstract int id();\n /**向配方显示器内添加显示部件的入口*/\n public void buildView(Group view){}\n\n public static void init() {\n factory = new FactoryRecipe();\n building = new BuildingRecipe();\n collecting = new CollectingRecipe();\n generator = new GeneratorRecipe();\n }\n\n public RecipeType(){\n all.add(this);\n }\n\n public void drawLine(RecipeView recipeView) {\n Draw.scl(recipeView.scaleX, recipeView.scaleY);\n\n for (RecipeView.LineMeta line : recipeView.lines) {\n if (line.vertices.size < 2) continue;\n\n float a = Draw.getColor().a;\n Lines.stroke(Scl.scl(5)*recipeView.scaleX, line.color.get());\n Draw.alpha(Draw.getColor().a*a);\n\n if (line.vertices.size <= 4){\n float x1 = line.vertices.items[0] - recipeView.getWidth()/2;\n float y1 = line.vertices.items[1] - recipeView.getHeight()/2;\n float x2 = line.vertices.items[2] - recipeView.getWidth()/2;\n float y2 = line.vertices.items[3] - recipeView.getHeight()/2;\n Lines.line(\n recipeView.x + recipeView.getWidth()/2 + x1*recipeView.scaleX, recipeView.y + recipeView.getHeight()/2 + y1*recipeView.scaleY,\n recipeView.x + recipeView.getWidth()/2 + x2*recipeView.scaleX, recipeView.y + recipeView.getHeight()/2 + y2*recipeView.scaleY\n );\n continue;\n }\n\n Lines.beginLine();\n for (int i = 0; i < line.vertices.size; i += 2) {\n float x1 = line.vertices.items[i] - recipeView.getWidth()/2;\n float y1 = line.vertices.items[i + 1] - recipeView.getHeight()/2;\n\n Lines.linePoint(recipeView.x + recipeView.getWidth()/2 + x1*recipeView.scaleX, recipeView.y + recipeView.getHeight()/2 + y1*recipeView.scaleY);\n }\n Lines.endLine();\n }\n\n Draw.reset();\n }\n\n @Override\n public int hashCode() {\n return id();\n }\n}"
},
{
"identifier": "markerTile",
"path": "src/main/java/tmi/util/Consts.java",
"snippet": "public static Tile markerTile;"
}
] | import arc.math.Mathf;
import arc.struct.ObjectMap;
import arc.struct.ObjectSet;
import arc.struct.Seq;
import arc.util.Strings;
import mindustry.Vars;
import mindustry.core.UI;
import mindustry.type.Item;
import mindustry.world.Block;
import mindustry.world.blocks.environment.Floor;
import mindustry.world.blocks.environment.OreBlock;
import mindustry.world.blocks.production.Drill;
import mindustry.world.consumers.Consume;
import mindustry.world.consumers.ConsumeLiquidBase;
import mindustry.world.meta.StatUnit;
import tmi.recipe.Recipe;
import tmi.recipe.RecipeType;
import static tmi.util.Consts.markerTile; | 3,185 | package tmi.recipe.parser;
public class DrillParser extends ConsumerParser<Drill>{
protected ObjectSet<Floor> itemDrops = new ObjectSet<>();
@Override
public void init() {
for (Block block : Vars.content.blocks()) {
if (block instanceof Floor f && f.itemDrop != null && !f.wallOre) itemDrops.add(f);
}
}
@Override
public boolean isTarget(Block content) {
return content instanceof Drill;
}
@Override | package tmi.recipe.parser;
public class DrillParser extends ConsumerParser<Drill>{
protected ObjectSet<Floor> itemDrops = new ObjectSet<>();
@Override
public void init() {
for (Block block : Vars.content.blocks()) {
if (block instanceof Floor f && f.itemDrop != null && !f.wallOre) itemDrops.add(f);
}
}
@Override
public boolean isTarget(Block content) {
return content instanceof Drill;
}
@Override | public Seq<Recipe> parse(Drill content) { | 0 | 2023-11-05 11:39:21+00:00 | 4k |
dulaiduwang003/DeepSee | microservices/ts-drawing/src/main/java/com/cn/listener/SdTaskListener.java | [
{
"identifier": "PoolCommon",
"path": "microservices/ts-drawing/src/main/java/com/cn/common/PoolCommon.java",
"snippet": "@Component\n@RequiredArgsConstructor\npublic class PoolCommon {\n\n\n private final PoolDefaultConfiguration configuration;\n public static final PoolStructure STRUCTURE = new PoolStructure();\n\n /**\n * 初始化.\n */\n @PostConstruct\n public void init() {\n STRUCTURE\n .setDallConcurrent(configuration.getDallConcurrent())\n .setMaximumTask(configuration.getMaximumTask())\n .setSdConcurrent(configuration.getSdConcurrent());\n }\n\n\n}"
},
{
"identifier": "SdCommon",
"path": "microservices/ts-drawing/src/main/java/com/cn/common/SdCommon.java",
"snippet": "@Component\n@RequiredArgsConstructor\npublic class SdCommon {\n\n\n private final SdDefaultConfiguration configuration;\n public static final SdStructure STRUCTURE = new SdStructure();\n\n\n /**\n * 初始化.\n */\n @PostConstruct\n public void init() {\n STRUCTURE\n .setModelList(configuration.getModelList())\n .setSamplerList(configuration.getSamplerList())\n .setSteps(configuration.getSteps())\n .setRequestUrl(configuration.getRequestUrl());\n }\n\n /**\n * 获取配置\n *\n * @return the config\n */\n public static SdStructure getConfig() {\n return STRUCTURE;\n }\n\n}"
},
{
"identifier": "DrawingConstant",
"path": "microservices/ts-drawing/src/main/java/com/cn/constant/DrawingConstant.java",
"snippet": "public interface DrawingConstant {\n\n\n String TASK = \"TASK:\";\n String SD_TASK_QUEUE = \"SD_TASK_QUEUE\";\n String SD_EXECUTION = \"SD_EXECUTION\";\n\n String DALL_TASK_QUEUE = \"DALL_TASK_QUEUE\";\n String DALL_EXECUTION = \"DALL_EXECUTION\";\n}"
},
{
"identifier": "DrawingStatusConstant",
"path": "microservices/ts-drawing/src/main/java/com/cn/constant/DrawingStatusConstant.java",
"snippet": "public interface DrawingStatusConstant {\n\n String DISUSE = \"DISUSE\";\n String PENDING = \"PENDING\";\n String PROCESSING = \"PROCESSING\";\n String SUCCEED = \"SUCCEED\";\n\n\n}"
},
{
"identifier": "TsGenerateDrawing",
"path": "microservices/ts-drawing/src/main/java/com/cn/entity/TsGenerateDrawing.java",
"snippet": "@Data\n@TableName(value = \"ts_generate_drawing\")\n@Accessors(chain = true)\npublic class TsGenerateDrawing {\n\n @TableId(type = IdType.INPUT)\n private String generateDrawingId;\n\n private String prompt;\n\n private Long userId;\n\n private String status;\n\n private String url;\n\n private String type;\n\n @TableField(fill = FieldFill.INSERT)\n private LocalDateTime createdTime;\n\n @TableField(fill = FieldFill.INSERT_UPDATE)\n private LocalDateTime updateTime;\n\n\n}"
},
{
"identifier": "DrawingTypeEnum",
"path": "microservices/ts-drawing/src/main/java/com/cn/enums/DrawingTypeEnum.java",
"snippet": "@NoArgsConstructor\n@AllArgsConstructor\n@Getter\npublic enum DrawingTypeEnum {\n\n DALL(\"DALL\"),\n\n SD(\"SD\");\n\n\n String dec;\n\n\n}"
},
{
"identifier": "FileEnum",
"path": "microservices/ts-common/src/main/java/com/cn/enums/FileEnum.java",
"snippet": "@Getter\n@ToString\n@NoArgsConstructor\n@AllArgsConstructor\npublic enum FileEnum {\n\n //头像\n AVATAR(\"avatar\"),\n //绘图\n DRAWING(\"drawing\");\n\n String dec;\n\n}"
},
{
"identifier": "TsGenerateDrawingMapper",
"path": "microservices/ts-drawing/src/main/java/com/cn/mapper/TsGenerateDrawingMapper.java",
"snippet": "@Mapper\npublic interface TsGenerateDrawingMapper extends BaseMapper<TsGenerateDrawing> {\n}"
},
{
"identifier": "SdModel",
"path": "microservices/ts-drawing/src/main/java/com/cn/model/SdModel.java",
"snippet": "@Data\n@Accessors(chain = true)\n@SuppressWarnings(\"all\")\npublic class SdModel implements Serializable {\n\n private List<String> init_images;\n\n private String mask;\n//\n// private Double denoising_strength;\n\n private String prompt;\n\n private Long width;\n\n private Long height;\n\n private String sampler_index;\n\n private Integer steps;\n\n private String negative_prompt;\n\n private Override override_settings;\n\n @Data\n @Accessors(chain = true)\n public static class Override implements Serializable {\n\n private String sd_model_checkpoint;\n\n private String sd_vae;\n }\n\n}"
},
{
"identifier": "TaskStructure",
"path": "microservices/ts-drawing/src/main/java/com/cn/structure/TaskStructure.java",
"snippet": "@Data\n@Accessors(chain = true)\npublic class TaskStructure implements Serializable {\n\n private String drawingType;\n\n private String taskId;\n\n private String prompt;\n\n private String imageUrl;\n\n private String status;\n\n private Object extra;\n\n}"
},
{
"identifier": "UploadUtil",
"path": "microservices/ts-common/src/main/java/com/cn/utils/UploadUtil.java",
"snippet": "@Component\n@SuppressWarnings(\"all\")\n@Slf4j\npublic class UploadUtil {\n\n @Value(\"${oss.ali-oss.endpoint}\")\n private String endpoint;\n\n @Value(\"${oss.ali-oss.accessKey}\")\n private String accessKey;\n\n @Value(\"${oss.ali-oss.secretKey}\")\n private String secretKey;\n\n @Value(\"${oss.ali-oss.bucketName}\")\n private String bucketName;\n\n public String uploadFile(final MultipartFile file, final String path) {\n\n OSS ossClient = new OSSClientBuilder()\n .build(endpoint, accessKey, secretKey);\n try (InputStream inputStream = file.getInputStream()) {\n String originalFileName = file.getOriginalFilename();\n\n assert originalFileName != null;\n String fileName;\n fileName = UUID.randomUUID() + originalFileName.substring(originalFileName.lastIndexOf('.'));\n\n String filePath = path + \"/\" + fileName;\n ObjectMetadata objectMetadata = new ObjectMetadata();\n objectMetadata.setContentType(\"image/png\");\n ossClient.putObject(bucketName, filePath, inputStream, objectMetadata);\n return \"/\" + filePath;\n\n } catch (IOException e) {\n throw new OSSException();\n } finally {\n ossClient.shutdown();\n }\n }\n\n public String uploadImageFromUrl(String imageUrl, String path) {\n OSS ossClient = new OSSClientBuilder()\n .build(endpoint, accessKey, secretKey);\n try {\n // 生成随机的图片名称\n String fileName = path + \"/\" + UUID.randomUUID().toString() + \".png\";\n\n\n // 通过URL下载网络图片到本地\n URL url = new URL(imageUrl);\n InputStream inputStream = url.openStream();\n // 上传图片到OSS\n ObjectMetadata objectMetadata = new ObjectMetadata();\n objectMetadata.setContentType(\"image/jpg\");\n ossClient.putObject(bucketName, fileName, inputStream, objectMetadata);\n return \"/\" + fileName;\n } catch (IOException e) {\n throw new OSSException();\n } finally {\n ossClient.shutdown();\n }\n }\n\n public String uploadBase64Image(final String base64Image, String path) {\n OSS ossClient = new OSSClientBuilder().build(endpoint, accessKey, secretKey);\n try {\n // 使用UUID生成新的文件名\n String fileName = path + \"/\" + UUID.randomUUID().toString() + \".jpg\";\n // 将Base64图片转换为字节数组\n byte[] imageBytes = Base64.getDecoder().decode(base64Image);\n ObjectMetadata objectMetadata = new ObjectMetadata();\n objectMetadata.setContentType(\"image/jpg\");\n // 创建PutObjectRequest对象并上传图片\n PutObjectRequest request = new PutObjectRequest(bucketName, fileName, new ByteArrayInputStream(imageBytes), objectMetadata);\n ossClient.putObject(request);\n return \"/\" + fileName;\n } catch (Exception e) {\n throw new OSSException();\n } finally {\n // 关闭OSS客户端\n ossClient.shutdown();\n }\n\n }\n\n public void deletedFile(final String path) {\n OSS ossClient = new OSSClientBuilder()\n .build(endpoint, accessKey, secretKey);\n try {\n\n if (path.startsWith(\"/\")) {\n ossClient.deleteObject(bucketName, path.substring(1));\n } else {\n ossClient.deleteObject(bucketName, path);\n }\n } catch (OSSException | ClientException e) {\n throw new OSSException();\n } finally {\n ossClient.shutdown();\n }\n }\n\n}"
}
] | import com.alibaba.fastjson.JSONObject;
import com.cn.common.PoolCommon;
import com.cn.common.SdCommon;
import com.cn.constant.DrawingConstant;
import com.cn.constant.DrawingStatusConstant;
import com.cn.entity.TsGenerateDrawing;
import com.cn.enums.DrawingTypeEnum;
import com.cn.enums.FileEnum;
import com.cn.mapper.TsGenerateDrawingMapper;
import com.cn.model.SdModel;
import com.cn.structure.TaskStructure;
import com.cn.utils.UploadUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.EventListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.client.WebClient;
import java.util.List;
import java.util.concurrent.Semaphore;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit; | 2,289 | package com.cn.listener;
@Slf4j
@Transactional(rollbackFor = Exception.class)
@RequiredArgsConstructor
@SuppressWarnings("all")
@Configuration
public class SdTaskListener {
private final RedisTemplate<String, Object> redisTemplate;
private final WebClient.Builder webClient;
private Semaphore semaphore;
private final ThreadPoolExecutor threadPoolExecutor;
| package com.cn.listener;
@Slf4j
@Transactional(rollbackFor = Exception.class)
@RequiredArgsConstructor
@SuppressWarnings("all")
@Configuration
public class SdTaskListener {
private final RedisTemplate<String, Object> redisTemplate;
private final WebClient.Builder webClient;
private Semaphore semaphore;
private final ThreadPoolExecutor threadPoolExecutor;
| private final UploadUtil uploadUtil; | 10 | 2023-11-05 16:26:39+00:00 | 4k |
ewolff/microservice-spring | microservice-spring-demo/microservice-spring-order/src/test/java/com/ewolff/microservice/order/logic/OrderWebIntegrationTest.java | [
{
"identifier": "OrderApp",
"path": "microservice-spring-demo/microservice-spring-order/src/main/java/com/ewolff/microservice/order/OrderApp.java",
"snippet": "@SpringBootApplication\npublic class OrderApp {\n\t\n\tprivate CustomerTestDataGenerator customerTestDataGenerator;\n\tprivate ItemTestDataGenerator itemTestDataGenerator;\n\t\n\tpublic OrderApp(CustomerTestDataGenerator customerTestDataGenerator, ItemTestDataGenerator itemTestDataGenerator) {\n\t\tsuper();\n\t\tthis.customerTestDataGenerator = customerTestDataGenerator;\n\t\tthis.itemTestDataGenerator = itemTestDataGenerator;\n\t}\n\n\t@PostConstruct\n\tpublic void generateTestData() {\n\t\tcustomerTestDataGenerator.generateTestData();\n\t\titemTestDataGenerator.generateTestData();\n\t}\n\t\n\tpublic static void main(String[] args) {\n\t\tSpringApplication.run(OrderApp.class, args);\n\t}\n\n}"
},
{
"identifier": "Customer",
"path": "microservice-spring-demo/microservice-spring-order/src/main/java/com/ewolff/microservice/order/customer/Customer.java",
"snippet": "@Entity\npublic class Customer {\n\n\t@Id\n\t@GeneratedValue\n\tprivate Long customerId;\n\n\t@Column(nullable = false)\n\tprivate String name;\n\n\t@Column(nullable = false)\n\tprivate String firstname;\n\n\t@Column(nullable = false)\n\tprivate String email;\n\n\tpublic Customer() {\n\t\tsuper();\n\t\tcustomerId = 0l;\n\t}\n\n\tpublic Customer(String firstname, String name, String email, String street, String city) {\n\t\tsuper();\n\t\tthis.name = name;\n\t\tthis.firstname = firstname;\n\t\tthis.email = email;\n\t}\n\n\tpublic String getEmail() {\n\t\treturn email;\n\t}\n\n\tpublic void setEmail(String email) {\n\t\tthis.email = email;\n\t}\n\n\tpublic String getName() {\n\t\treturn name;\n\t}\n\n\tpublic void setName(String name) {\n\t\tthis.name = name;\n\t}\n\n\tpublic String getFirstname() {\n\t\treturn firstname;\n\t}\n\n\tpublic void setFirstname(String firstname) {\n\t\tthis.firstname = firstname;\n\t}\n\n\tpublic Long getCustomerId() {\n\t\treturn customerId;\n\t}\n\n\tpublic void setCustomerId(Long id) {\n\t\tthis.customerId = id;\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\tfinal int prime = 31;\n\t\tint result = 1;\n\t\tresult = prime * result + ((customerId == null) ? 0 : customerId.hashCode());\n\t\tresult = prime * result + ((email == null) ? 0 : email.hashCode());\n\t\tresult = prime * result + ((firstname == null) ? 0 : firstname.hashCode());\n\t\tresult = prime * result + ((name == null) ? 0 : name.hashCode());\n\t\treturn result;\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj)\n\t\t\treturn true;\n\t\tif (obj == null)\n\t\t\treturn false;\n\t\tif (getClass() != obj.getClass())\n\t\t\treturn false;\n\t\tCustomer other = (Customer) obj;\n\t\tif (customerId == null) {\n\t\t\tif (other.customerId != null)\n\t\t\t\treturn false;\n\t\t} else if (!customerId.equals(other.customerId))\n\t\t\treturn false;\n\t\tif (email == null) {\n\t\t\tif (other.email != null)\n\t\t\t\treturn false;\n\t\t} else if (!email.equals(other.email))\n\t\t\treturn false;\n\t\tif (firstname == null) {\n\t\t\tif (other.firstname != null)\n\t\t\t\treturn false;\n\t\t} else if (!firstname.equals(other.firstname))\n\t\t\treturn false;\n\t\tif (name == null) {\n\t\t\tif (other.name != null)\n\t\t\t\treturn false;\n\t\t} else if (!name.equals(other.name))\n\t\t\treturn false;\n\t\treturn true;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"Customer [customerId=\" + customerId + \", name=\" + name + \", firstname=\" + firstname + \", email=\" + email\n\t\t\t\t+ \"]\";\n\t}\n\n\n}"
},
{
"identifier": "CustomerRepository",
"path": "microservice-spring-demo/microservice-spring-order/src/main/java/com/ewolff/microservice/order/customer/CustomerRepository.java",
"snippet": "public interface CustomerRepository extends PagingAndSortingRepository<Customer, Long>, CrudRepository<Customer, Long> {\n\n\tList<Customer> findByName(@Param(\"name\") String name);\n\n}"
},
{
"identifier": "Item",
"path": "microservice-spring-demo/microservice-spring-order/src/main/java/com/ewolff/microservice/order/item/Item.java",
"snippet": "@Entity\npublic class Item {\n\n\t@Id\n\t@GeneratedValue\n\tprivate Long itemId;\n\n\t@Column(nullable = false)\n\tprivate String name;\n\n\t@Column(nullable = false)\n\tprivate double price;\n\n\tpublic Item() {\n\t\tsuper();\n\t\titemId = 0l;\n\t}\n\n\tpublic Item(String name, double price) {\n\t\tsuper();\n\t\tthis.name = name;\n\t\tthis.price = price;\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 double getPrice() {\n\t\treturn price;\n\t}\n\n\tpublic void setPrice(double price) {\n\t\tthis.price = price;\n\t}\n\n\tpublic Long getItemId() {\n\t\treturn itemId;\n\t}\n\n\tpublic void setItemId(Long id) {\n\t\tthis.itemId = id;\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\tfinal int prime = 31;\n\t\tint result = 1;\n\t\tresult = prime * result + ((itemId == null) ? 0 : itemId.hashCode());\n\t\tresult = prime * result + ((name == null) ? 0 : name.hashCode());\n\t\tlong temp;\n\t\ttemp = Double.doubleToLongBits(price);\n\t\tresult = prime * result + (int) (temp ^ (temp >>> 32));\n\t\treturn result;\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj)\n\t\t\treturn true;\n\t\tif (obj == null)\n\t\t\treturn false;\n\t\tif (getClass() != obj.getClass())\n\t\t\treturn false;\n\t\tItem other = (Item) obj;\n\t\tif (itemId == null) {\n\t\t\tif (other.itemId != null)\n\t\t\t\treturn false;\n\t\t} else if (!itemId.equals(other.itemId))\n\t\t\treturn false;\n\t\tif (name == null) {\n\t\t\tif (other.name != null)\n\t\t\t\treturn false;\n\t\t} else if (!name.equals(other.name))\n\t\t\treturn false;\n\t\tif (Double.doubleToLongBits(price) != Double.doubleToLongBits(other.price))\n\t\t\treturn false;\n\t\treturn true;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"Item [itemId=\" + itemId + \", name=\" + name + \", price=\" + price + \"]\";\n\t}\n\n\n\t\n}"
},
{
"identifier": "ItemRepository",
"path": "microservice-spring-demo/microservice-spring-order/src/main/java/com/ewolff/microservice/order/item/ItemRepository.java",
"snippet": "public interface ItemRepository extends PagingAndSortingRepository<Item, Long>, CrudRepository<Item, Long> {\n\n\tList<Item> findByName(@Param(\"name\") String name);\n\n\tList<Item> findByNameContaining(@Param(\"name\") String name);\n\n\t@Query(\"SELECT price FROM Item i WHERE i.itemId=?1\")\n\tdouble price(long itemId);\n\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 java.util.stream.StreamSupport;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import org.junit.jupiter.api.TestInstance.Lifecycle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.web.server.LocalServerPort;
import org.springframework.data.domain.Sort;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import com.ewolff.microservice.order.OrderApp;
import com.ewolff.microservice.order.customer.Customer;
import com.ewolff.microservice.order.customer.CustomerRepository;
import com.ewolff.microservice.order.item.Item;
import com.ewolff.microservice.order.item.ItemRepository; | 2,079 | package com.ewolff.microservice.order.logic;
@SpringBootTest(classes = OrderApp.class, webEnvironment = WebEnvironment.DEFINED_PORT)
@ActiveProfiles("test")
@TestInstance(Lifecycle.PER_CLASS)
class OrderWebIntegrationTest {
private RestTemplate restTemplate = new RestTemplate();
@LocalServerPort
private long serverPort;
@Autowired | package com.ewolff.microservice.order.logic;
@SpringBootTest(classes = OrderApp.class, webEnvironment = WebEnvironment.DEFINED_PORT)
@ActiveProfiles("test")
@TestInstance(Lifecycle.PER_CLASS)
class OrderWebIntegrationTest {
private RestTemplate restTemplate = new RestTemplate();
@LocalServerPort
private long serverPort;
@Autowired | private ItemRepository itemRepository; | 4 | 2023-11-03 17:36:15+00:00 | 4k |
LaughingMuffin/apk-killer-java-mod-menu | app/src/main/java/com/muffin/whale/xposed/XposedBridge.java | [
{
"identifier": "WhaleRuntime",
"path": "app/src/main/java/com/muffin/whale/WhaleRuntime.java",
"snippet": "public class WhaleRuntime {\n private static String getShorty(Member member) {\n return VMHelper.getShorty(member);\n }\n\n public static long[] countInstancesOfClasses(Class[] classes, boolean assignable) {\n if (Build.VERSION.SDK_INT < 27) {\n throw new UnsupportedOperationException(\"Not support countInstancesOfClasses on your device yet.\");\n }\n try {\n Class<?> clazz = Class.forName(\"dalvik.system.VMDebug\");\n Method method = clazz.getDeclaredMethod(\"countInstancesOfClasses\", Class[].class, boolean.class);\n return (long[]) method.invoke(null, classes, assignable);\n } catch (Throwable e) {\n throw new IllegalStateException(e);\n }\n }\n\n public static Object[][] getInstancesOfClasses(Class[] classes, boolean assignable) {\n if (Build.VERSION.SDK_INT < 28) {\n throw new UnsupportedOperationException(\"Not support getInstancesOfClasses on your device yet.\");\n }\n try {\n Class<?> clazz = Class.forName(\"dalvik.system.VMDebug\");\n Method method = clazz.getDeclaredMethod(\"getInstancesOfClasses\", Class[].class, boolean.class);\n return (Object[][]) method.invoke(null, classes, assignable);\n } catch (Throwable e) {\n throw new IllegalStateException(e);\n }\n }\n\n public static Object handleHookedMethod(Member member, long slot, Object additionInfo, Object thisObject, Object[] args) throws Throwable {\n return XposedBridge.handleHookedMethod(member, slot, additionInfo, thisObject, args);\n }\n\n public static native Object invokeOriginalMethodNative(long slot, Object thisObject, Object[] args)\n throws IllegalAccessException, IllegalArgumentException, InvocationTargetException;\n\n public static native long getMethodSlot(Member member) throws IllegalArgumentException;\n\n public static native long hookMethodNative(Class<?> declClass, Member method, Object additionInfo);\n\n public static native void setObjectClassNative(Object object, Class<?> parent);\n\n public static native Object cloneToSubclassNative(Object object, Class<?> subClass);\n\n public static native void removeFinalFlagNative(Class<?> cl);\n\n public static native void enforceDisableHiddenAPIPolicy();\n\n private static native void reserved0();\n\n private static native void reserved1();\n}"
},
{
"identifier": "MethodHookParam",
"path": "app/src/main/java/com/muffin/whale/xposed/XC_MethodHook.java",
"snippet": "@SuppressWarnings({\"unused\", \"WeakerAccess\"})\npublic static final class MethodHookParam extends Param {\n /**\n * Backup method slot.\n */\n public int slot;\n\n /**\n * The hooked method/constructor.\n */\n public Member method;\n\n /**\n * The {@code this} reference for an instance method, or {@code null} for static methods.\n */\n public Object thisObject;\n\n /**\n * Arguments to the method call.\n */\n public Object[] args;\n\n private Object result = null;\n private Throwable throwable = null;\n /* package */ boolean returnEarly = false;\n\n /**\n * Returns the result of the method call.\n */\n public Object getResult() {\n return result;\n }\n\n /**\n * Modify the result of the method call.\n * <p>\n * <p>If called from {@link #beforeHookedMethod}, it prevents the call to the original method.\n */\n public void setResult(final Object result) {\n this.result = result;\n this.throwable = null;\n this.returnEarly = true;\n }\n\n /**\n * Returns the {@link Throwable} thrown by the method, or {@code null}.\n */\n public Throwable getThrowable() {\n return throwable;\n }\n\n /**\n * Returns true if an exception was thrown by the method.\n */\n public boolean hasThrowable() {\n return throwable != null;\n }\n\n /**\n * Modify the exception thrown of the method call.\n * <p>\n * <p>If called from {@link #beforeHookedMethod}, it prevents the call to the original method.\n */\n public void setThrowable(final Throwable throwable) {\n this.throwable = throwable;\n this.result = null;\n this.returnEarly = true;\n }\n\n /**\n * Returns the result of the method call, or throws the Throwable caused by it.\n */\n public Object getResultOrThrowable() throws Throwable {\n if (throwable != null)\n throw throwable;\n return result;\n }\n}"
}
] | import android.util.Log;
import com.muffin.whale.WhaleRuntime;
import com.muffin.whale.xposed.XC_MethodHook.MethodHookParam;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map; | 2,918 | package com.muffin.whale.xposed;
/**
* This class contains most of Xposed's central logic, such as initialization and callbacks used by
* the native side. It also includes methods to add new hooks.
* <p>
* Latest Update 2018/04/20
*/
@SuppressWarnings("WeakerAccess")
public final class XposedBridge {
/**
* The system class loader which can be used to locate Android framework classes.
* Application classes cannot be retrieved from it.
*
* @see ClassLoader#getSystemClassLoader
*/
@SuppressWarnings("unused")
public static final ClassLoader BOOTCLASSLOADER = ClassLoader.getSystemClassLoader();
public static final String TAG = "Whale-Buildin-Xposed";
/*package*/ static boolean disableHooks = false;
private static final Object[] EMPTY_ARRAY = new Object[0];
// built-in handlers
private static final Map<Member, CopyOnWriteSortedSet<XC_MethodHook>> sHookedMethodCallbacks = new HashMap<>();
private static final Map<Member, Long> sHookedMethodSlotMap = new HashMap<>();
/**
* Writes a message to the logcat error log.
*
* @param text The log message.
*/
@SuppressWarnings("unused")
public static void log(final String text) {
Log.i(TAG, text);
}
/**
* Logs a stack trace to the logcat error log.
*
* @param t The Throwable object for the stack trace.
*/
public static void log(final Throwable t) {
Log.e(TAG, Log.getStackTraceString(t));
}
/**
* Hook any method (or constructor) with the specified callback. See below for some wrappers
* that make it easier to find a method/constructor in one step.
*
* @param hookMethod The method to be hooked.
* @param callback The callback to be executed when the hooked method is called.
* @return An object that can be used to remove the hook.
* @see XposedHelpers#findAndHookMethod(String, ClassLoader, String, Object...)
* @see XposedHelpers#findAndHookMethod(Class, String, Object...)
* @see #hookAllMethods
* @see XposedHelpers#findAndHookConstructor(String, ClassLoader, Object...)
* @see XposedHelpers#findAndHookConstructor(Class, Object...)
* @see #hookAllConstructors
*/
public static XC_MethodHook.Unhook hookMethod(final Member hookMethod, final XC_MethodHook callback) {
if (!(hookMethod instanceof Method) && !(hookMethod instanceof Constructor<?>)) {
throw new IllegalArgumentException("Only methods and constructors can be hooked: " + hookMethod.toString());
} else if (hookMethod.getDeclaringClass().isInterface()) {
throw new IllegalArgumentException("Cannot hook interfaces: " + hookMethod.toString());
} else if (Modifier.isAbstract(hookMethod.getModifiers())) {
throw new IllegalArgumentException("Cannot hook abstract methods: " + hookMethod.toString());
}
boolean newMethod = false;
CopyOnWriteSortedSet<XC_MethodHook> callbacks;
synchronized (sHookedMethodCallbacks) {
callbacks = sHookedMethodCallbacks.get(hookMethod);
if (callbacks == null) {
callbacks = new CopyOnWriteSortedSet<>();
sHookedMethodCallbacks.put(hookMethod, callbacks);
newMethod = true;
}
}
callbacks.add(callback);
if (newMethod) {
XposedHelpers.resolveStaticMethod(hookMethod);
AdditionalHookInfo additionalInfo = new AdditionalHookInfo(callbacks);
long slot = WhaleRuntime.hookMethodNative(hookMethod.getDeclaringClass(), hookMethod, additionalInfo);
if (slot <= 0) {
throw new IllegalStateException("Failed to hook method: " + hookMethod);
}
synchronized (sHookedMethodSlotMap) {
sHookedMethodSlotMap.put(hookMethod, slot);
}
}
return callback.new Unhook(hookMethod);
}
/**
* Removes the callback for a hooked method/constructor.
*
* @param hookMethod The method for which the callback should be removed.
* @param callback The reference to the callback as specified in {@link #hookMethod}.
*/
@SuppressWarnings("all")
public static void unhookMethod(final Member hookMethod, final XC_MethodHook callback) {
synchronized (sHookedMethodSlotMap) {
sHookedMethodSlotMap.remove(hookMethod);
}
CopyOnWriteSortedSet<XC_MethodHook> callbacks;
synchronized (sHookedMethodCallbacks) {
callbacks = sHookedMethodCallbacks.get(hookMethod);
if (callbacks == null)
return;
}
callbacks.remove(callback);
}
/**
* Hooks all methods that were declared in the specified class. Inherited
* methods and constructors are not considered. For constructors, use
* {@link #hookAllConstructors} instead.
* <p>
* AndHook extension function.
*
* @param hookClass The class to check for declared methods.
* @param callback The callback to be executed when the hooked methods are called.
* @return A set containing one object for each found method which can be used to unhook it.
*/
@SuppressWarnings("all")
public static HashSet<XC_MethodHook.Unhook> hookAllMethods(final Class<?> hookClass,
final XC_MethodHook callback) {
final HashSet<XC_MethodHook.Unhook> unhooks = new HashSet<>();
for (final Member method : hookClass.getDeclaredMethods())
unhooks.add(hookMethod(method, callback));
return unhooks;
}
/**
* Hooks all methods with a certain name that were declared in the specified class. Inherited
* methods and constructors are not considered. For constructors, use
* {@link #hookAllConstructors} instead.
*
* @param hookClass The class to check for declared methods.
* @param methodName The name of the method(s) to hook.
* @param callback The callback to be executed when the hooked methods are called.
* @return A set containing one object for each found method which can be used to unhook it.
*/
@SuppressWarnings("all")
public static HashSet<XC_MethodHook.Unhook> hookAllMethods(final Class<?> hookClass,
final String methodName,
final XC_MethodHook callback) {
final HashSet<XC_MethodHook.Unhook> unhooks = new HashSet<>();
for (final Member method : hookClass.getDeclaredMethods())
if (method.getName().equals(methodName))
unhooks.add(hookMethod(method, callback));
return unhooks;
}
/**
* Hook all constructors of the specified class.
*
* @param hookClass The class to check for constructors.
* @param callback The callback to be executed when the hooked constructors are called.
* @return A set containing one object for each found constructor which can be used to unhook it.
*/
@SuppressWarnings("all")
public static HashSet<XC_MethodHook.Unhook> hookAllConstructors(final Class<?> hookClass,
final XC_MethodHook callback) {
final HashSet<XC_MethodHook.Unhook> unhooks = new HashSet<>();
for (final Member constructor : hookClass.getDeclaredConstructors())
unhooks.add(hookMethod(constructor, callback));
return unhooks;
}
/**
* This method is called as a replacement for hooked methods.
*/
public static Object handleHookedMethod(Member method, long slot, Object additionalInfoObj,
Object thisObject, Object[] args) throws Throwable {
AdditionalHookInfo additionalInfo = (AdditionalHookInfo) additionalInfoObj;
if (disableHooks) {
try {
return invokeOriginalMethod(slot, thisObject, args);
} catch (InvocationTargetException e) {
throw e.getCause();
}
}
Object[] callbacksSnapshot = additionalInfo.callbacks.getSnapshot();
final int callbacksLength = callbacksSnapshot.length;
if (callbacksLength == 0) {
try {
return invokeOriginalMethod(slot, thisObject, args);
} catch (InvocationTargetException e) {
throw e.getCause();
}
}
| package com.muffin.whale.xposed;
/**
* This class contains most of Xposed's central logic, such as initialization and callbacks used by
* the native side. It also includes methods to add new hooks.
* <p>
* Latest Update 2018/04/20
*/
@SuppressWarnings("WeakerAccess")
public final class XposedBridge {
/**
* The system class loader which can be used to locate Android framework classes.
* Application classes cannot be retrieved from it.
*
* @see ClassLoader#getSystemClassLoader
*/
@SuppressWarnings("unused")
public static final ClassLoader BOOTCLASSLOADER = ClassLoader.getSystemClassLoader();
public static final String TAG = "Whale-Buildin-Xposed";
/*package*/ static boolean disableHooks = false;
private static final Object[] EMPTY_ARRAY = new Object[0];
// built-in handlers
private static final Map<Member, CopyOnWriteSortedSet<XC_MethodHook>> sHookedMethodCallbacks = new HashMap<>();
private static final Map<Member, Long> sHookedMethodSlotMap = new HashMap<>();
/**
* Writes a message to the logcat error log.
*
* @param text The log message.
*/
@SuppressWarnings("unused")
public static void log(final String text) {
Log.i(TAG, text);
}
/**
* Logs a stack trace to the logcat error log.
*
* @param t The Throwable object for the stack trace.
*/
public static void log(final Throwable t) {
Log.e(TAG, Log.getStackTraceString(t));
}
/**
* Hook any method (or constructor) with the specified callback. See below for some wrappers
* that make it easier to find a method/constructor in one step.
*
* @param hookMethod The method to be hooked.
* @param callback The callback to be executed when the hooked method is called.
* @return An object that can be used to remove the hook.
* @see XposedHelpers#findAndHookMethod(String, ClassLoader, String, Object...)
* @see XposedHelpers#findAndHookMethod(Class, String, Object...)
* @see #hookAllMethods
* @see XposedHelpers#findAndHookConstructor(String, ClassLoader, Object...)
* @see XposedHelpers#findAndHookConstructor(Class, Object...)
* @see #hookAllConstructors
*/
public static XC_MethodHook.Unhook hookMethod(final Member hookMethod, final XC_MethodHook callback) {
if (!(hookMethod instanceof Method) && !(hookMethod instanceof Constructor<?>)) {
throw new IllegalArgumentException("Only methods and constructors can be hooked: " + hookMethod.toString());
} else if (hookMethod.getDeclaringClass().isInterface()) {
throw new IllegalArgumentException("Cannot hook interfaces: " + hookMethod.toString());
} else if (Modifier.isAbstract(hookMethod.getModifiers())) {
throw new IllegalArgumentException("Cannot hook abstract methods: " + hookMethod.toString());
}
boolean newMethod = false;
CopyOnWriteSortedSet<XC_MethodHook> callbacks;
synchronized (sHookedMethodCallbacks) {
callbacks = sHookedMethodCallbacks.get(hookMethod);
if (callbacks == null) {
callbacks = new CopyOnWriteSortedSet<>();
sHookedMethodCallbacks.put(hookMethod, callbacks);
newMethod = true;
}
}
callbacks.add(callback);
if (newMethod) {
XposedHelpers.resolveStaticMethod(hookMethod);
AdditionalHookInfo additionalInfo = new AdditionalHookInfo(callbacks);
long slot = WhaleRuntime.hookMethodNative(hookMethod.getDeclaringClass(), hookMethod, additionalInfo);
if (slot <= 0) {
throw new IllegalStateException("Failed to hook method: " + hookMethod);
}
synchronized (sHookedMethodSlotMap) {
sHookedMethodSlotMap.put(hookMethod, slot);
}
}
return callback.new Unhook(hookMethod);
}
/**
* Removes the callback for a hooked method/constructor.
*
* @param hookMethod The method for which the callback should be removed.
* @param callback The reference to the callback as specified in {@link #hookMethod}.
*/
@SuppressWarnings("all")
public static void unhookMethod(final Member hookMethod, final XC_MethodHook callback) {
synchronized (sHookedMethodSlotMap) {
sHookedMethodSlotMap.remove(hookMethod);
}
CopyOnWriteSortedSet<XC_MethodHook> callbacks;
synchronized (sHookedMethodCallbacks) {
callbacks = sHookedMethodCallbacks.get(hookMethod);
if (callbacks == null)
return;
}
callbacks.remove(callback);
}
/**
* Hooks all methods that were declared in the specified class. Inherited
* methods and constructors are not considered. For constructors, use
* {@link #hookAllConstructors} instead.
* <p>
* AndHook extension function.
*
* @param hookClass The class to check for declared methods.
* @param callback The callback to be executed when the hooked methods are called.
* @return A set containing one object for each found method which can be used to unhook it.
*/
@SuppressWarnings("all")
public static HashSet<XC_MethodHook.Unhook> hookAllMethods(final Class<?> hookClass,
final XC_MethodHook callback) {
final HashSet<XC_MethodHook.Unhook> unhooks = new HashSet<>();
for (final Member method : hookClass.getDeclaredMethods())
unhooks.add(hookMethod(method, callback));
return unhooks;
}
/**
* Hooks all methods with a certain name that were declared in the specified class. Inherited
* methods and constructors are not considered. For constructors, use
* {@link #hookAllConstructors} instead.
*
* @param hookClass The class to check for declared methods.
* @param methodName The name of the method(s) to hook.
* @param callback The callback to be executed when the hooked methods are called.
* @return A set containing one object for each found method which can be used to unhook it.
*/
@SuppressWarnings("all")
public static HashSet<XC_MethodHook.Unhook> hookAllMethods(final Class<?> hookClass,
final String methodName,
final XC_MethodHook callback) {
final HashSet<XC_MethodHook.Unhook> unhooks = new HashSet<>();
for (final Member method : hookClass.getDeclaredMethods())
if (method.getName().equals(methodName))
unhooks.add(hookMethod(method, callback));
return unhooks;
}
/**
* Hook all constructors of the specified class.
*
* @param hookClass The class to check for constructors.
* @param callback The callback to be executed when the hooked constructors are called.
* @return A set containing one object for each found constructor which can be used to unhook it.
*/
@SuppressWarnings("all")
public static HashSet<XC_MethodHook.Unhook> hookAllConstructors(final Class<?> hookClass,
final XC_MethodHook callback) {
final HashSet<XC_MethodHook.Unhook> unhooks = new HashSet<>();
for (final Member constructor : hookClass.getDeclaredConstructors())
unhooks.add(hookMethod(constructor, callback));
return unhooks;
}
/**
* This method is called as a replacement for hooked methods.
*/
public static Object handleHookedMethod(Member method, long slot, Object additionalInfoObj,
Object thisObject, Object[] args) throws Throwable {
AdditionalHookInfo additionalInfo = (AdditionalHookInfo) additionalInfoObj;
if (disableHooks) {
try {
return invokeOriginalMethod(slot, thisObject, args);
} catch (InvocationTargetException e) {
throw e.getCause();
}
}
Object[] callbacksSnapshot = additionalInfo.callbacks.getSnapshot();
final int callbacksLength = callbacksSnapshot.length;
if (callbacksLength == 0) {
try {
return invokeOriginalMethod(slot, thisObject, args);
} catch (InvocationTargetException e) {
throw e.getCause();
}
}
| MethodHookParam param = new MethodHookParam(); | 1 | 2023-11-08 09:47:46+00:00 | 4k |
xsreality/spring-modulith-with-ddd | src/test/java/example/borrow/LoanIntegrationTests.java | [
{
"identifier": "Book",
"path": "src/main/java/example/borrow/book/domain/Book.java",
"snippet": "@AggregateRoot\n@Entity\n@Getter\n@NoArgsConstructor\n@Table(name = \"borrow_books\", uniqueConstraints = @UniqueConstraint(columnNames = {\"barcode\"}))\npublic class Book {\n\n @Identity\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private Long id;\n\n private String title;\n\n @Embedded\n private Barcode inventoryNumber;\n\n private String isbn;\n\n @Enumerated(EnumType.STRING)\n private BookStatus status;\n\n @Version\n private Long version;\n\n @ValueObject\n public record Barcode(String barcode) {\n }\n\n public boolean available() {\n return BookStatus.AVAILABLE.equals(this.status);\n }\n\n public boolean onHold() {\n return BookStatus.ON_HOLD.equals(this.status);\n }\n\n public boolean issued() {\n return BookStatus.ISSUED.equals(this.status);\n }\n\n public Book(String title, Barcode inventoryNumber, String isbn) {\n this.title = title;\n this.inventoryNumber = inventoryNumber;\n this.isbn = isbn;\n this.status = BookStatus.AVAILABLE;\n }\n\n public Book markIssued() {\n if (issued()) {\n throw new IllegalStateException(\"Book is already issued!\");\n }\n this.status = BookStatus.ISSUED;\n return this;\n }\n\n public Book markOnHold() {\n if (onHold()) {\n throw new IllegalStateException(\"Book is already available!\");\n }\n this.status = BookStatus.ON_HOLD;\n return this;\n }\n\n public Book markAvailable() {\n if (available()) {\n throw new IllegalStateException(\"Book is already available!\");\n }\n this.status = BookStatus.AVAILABLE;\n return this;\n }\n\n @ValueObject\n public enum BookStatus {\n AVAILABLE, ON_HOLD, ISSUED\n }\n}"
},
{
"identifier": "BookRepository",
"path": "src/main/java/example/borrow/book/domain/BookRepository.java",
"snippet": "public interface BookRepository extends JpaRepository<Book, Long> {\n\n Optional<Book> findByInventoryNumber(Barcode inventoryNumber);\n}"
},
{
"identifier": "LoanStatus",
"path": "src/main/java/example/borrow/loan/domain/Loan.java",
"snippet": "@ValueObject\npublic enum LoanStatus {\n HOLDING, ACTIVE, OVERDUE, COMPLETED\n}"
},
{
"identifier": "LoanManagement",
"path": "src/main/java/example/borrow/loan/application/LoanManagement.java",
"snippet": "@Transactional\n@Service\n@RequiredArgsConstructor\npublic class LoanManagement {\n\n private final LoanRepository loans;\n private final BookRepository books;\n private final ApplicationEventPublisher events;\n private final LoanMapper mapper;\n\n /**\n * Place a book on hold.\n *\n * @param barcode Unique identifier of the book\n */\n public LoanDto hold(String barcode, Long patronId) {\n var book = books.findByInventoryNumber(new Barcode(barcode))\n .orElseThrow(() -> new IllegalArgumentException(\"Book not found!\"));\n\n if (!book.available()) {\n throw new IllegalStateException(\"Book not available!\");\n }\n\n var dateOfHold = LocalDate.now();\n var loan = Loan.of(barcode, dateOfHold, patronId);\n var dto = mapper.toDto(loans.save(loan));\n events.publishEvent(\n new BookPlacedOnHold(\n book.getId(),\n book.getIsbn(),\n book.getInventoryNumber().barcode(),\n loan.getPatronId(),\n dateOfHold));\n return dto;\n }\n\n /**\n * Collect a book previously placed on hold.\n *\n * @param loanId Unique identifier of the book loan\n */\n public LoanDto checkout(Long loanId) {\n var loan = loans.findById(loanId)\n .orElseThrow(() -> new IllegalArgumentException(\"No loan found\"));\n\n var book = books.findByInventoryNumber(loan.getBookBarcode())\n .orElseThrow(() -> new IllegalArgumentException(\"Book not found!\"));\n\n if (!book.onHold()) {\n throw new IllegalStateException(\"Book is not on hold!\");\n }\n\n var dateOfCheckout = LocalDate.now();\n loan.activate(dateOfCheckout);\n var dto = mapper.toDto(loans.save(loan));\n events.publishEvent(new BookCollected(book.getId(), book.getIsbn(), book.getInventoryNumber().barcode(), loan.getPatronId(), dateOfCheckout));\n return dto;\n }\n\n /**\n * Return a borrowed book.\n *\n * @param loanId Unique identifier of the book loan\n */\n public LoanDto checkin(Long loanId) {\n var dateOfCheckin = LocalDate.now();\n\n var loan = loans.findById(loanId)\n .orElseThrow(() -> new IllegalArgumentException(\"No loan found\"));\n loan.complete(dateOfCheckin);\n var dto = mapper.toDto(loans.save(loan));\n\n var book = books.findByInventoryNumber(loan.getBookBarcode())\n .orElseThrow(() -> new IllegalArgumentException(\"Book not found!\"));\n events.publishEvent(new BookReturned(book.getId(), book.getIsbn(), book.getInventoryNumber().barcode(), loan.getPatronId(), dateOfCheckin));\n return dto;\n }\n\n @Transactional(readOnly = true)\n public List<LoanDto> activeLoans() {\n return loans.findLoanByStatus(LoanStatus.ACTIVE)\n .stream()\n .map(mapper::toDto)\n .toList();\n }\n\n @Transactional(readOnly = true)\n public List<LoanDto> onHoldLoans() {\n return loans.findLoanByStatus(LoanStatus.HOLDING)\n .stream()\n .map(mapper::toDto)\n .toList();\n }\n\n @Transactional(readOnly = true)\n public Optional<LoanDto> locate(Long loanId) {\n return loans.findById(loanId)\n .map(mapper::toDto);\n }\n}"
}
] | import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.modulith.test.ApplicationModuleTest;
import org.springframework.modulith.test.Scenario;
import org.springframework.test.context.DynamicPropertyRegistry;
import org.springframework.test.context.DynamicPropertySource;
import org.springframework.transaction.annotation.Transactional;
import java.time.Duration;
import example.borrow.book.domain.Book;
import example.borrow.book.domain.BookCollected;
import example.borrow.book.domain.BookPlacedOnHold;
import example.borrow.book.domain.BookRepository;
import example.borrow.book.domain.BookReturned;
import example.borrow.loan.domain.Loan.LoanStatus;
import example.borrow.loan.application.LoanManagement;
import example.catalog.BookAddedToCatalog;
import static org.assertj.core.api.Assertions.assertThat; | 1,614 | package example.borrow;
@Transactional
@ApplicationModuleTest
class LoanIntegrationTests {
@DynamicPropertySource
static void initializeData(DynamicPropertyRegistry registry) {
registry.add("spring.sql.init.data-locations", () -> "classpath:borrow.sql");
}
@Autowired | package example.borrow;
@Transactional
@ApplicationModuleTest
class LoanIntegrationTests {
@DynamicPropertySource
static void initializeData(DynamicPropertyRegistry registry) {
registry.add("spring.sql.init.data-locations", () -> "classpath:borrow.sql");
}
@Autowired | LoanManagement loans; | 3 | 2023-11-03 22:21:01+00:00 | 4k |
daominh-studio/quick-mem | app/src/main/java/com/daominh/quickmem/adapter/group/MyViewClassAdapter.java | [
{
"identifier": "ViewMembersFragment",
"path": "app/src/main/java/com/daominh/quickmem/ui/activities/classes/ViewMembersFragment.java",
"snippet": "public class ViewMembersFragment extends Fragment {\n private FragmentViewMembersBinding binding;\n private UserSharePreferences userSharePreferences;\n private UserDAO userDAO;\n private GroupDAO groupDAO;\n\n @Override\n public void onCreate(@Nullable Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n userSharePreferences = new UserSharePreferences(requireActivity());\n userDAO = new UserDAO(requireContext());\n groupDAO = new GroupDAO(requireContext());\n }\n\n @Override\n public View onCreateView(@NotNull LayoutInflater inflater, ViewGroup container,\n Bundle savedInstanceState) {\n binding = FragmentViewMembersBinding.inflate(inflater, container, false);\n return binding.getRoot();\n }\n\n @SuppressLint(\"NotifyDataSetChanged\")\n @Override\n public void onViewCreated(@NonNull @NotNull View view, @Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {\n super.onViewCreated(view, savedInstanceState);\n\n Group group = groupDAO.getGroupById(userSharePreferences.getClassId());\n ArrayList<User> users = new ArrayList<>();\n users.add(userDAO.getUserByIdClass(group.getUser_id()));\n users.addAll(userDAO.getListUserByIdClass(userSharePreferences.getClassId()));\n\n UserClassAdapter userClassAdapter = new UserClassAdapter(users, false, group.getId());\n LinearLayoutManager linearLayoutManager = new LinearLayoutManager(requireContext(), LinearLayoutManager.VERTICAL, false);\n binding.membersRv.setLayoutManager(linearLayoutManager);\n binding.membersRv.setAdapter(userClassAdapter);\n binding.membersRv.setHasFixedSize(true);\n userClassAdapter.notifyDataSetChanged();\n\n }\n}"
},
{
"identifier": "ViewSetsFragment",
"path": "app/src/main/java/com/daominh/quickmem/ui/activities/classes/ViewSetsFragment.java",
"snippet": "public class ViewSetsFragment extends Fragment {\n private FragmentViewSetsBinding binding;\n private UserSharePreferences userSharePreferences;\n private final ArrayList<FlashCard> flashCards = new ArrayList<>();\n private FlashCardDAO flashCardDAO;\n private GroupDAO groupDAO;\n\n @Override\n public void onCreate(@Nullable Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n flashCardDAO = new FlashCardDAO(requireActivity());\n groupDAO = new GroupDAO(requireActivity());\n userSharePreferences = new UserSharePreferences(requireActivity());\n }\n\n @Override\n public View onCreateView(@NotNull LayoutInflater inflater, ViewGroup container,\n Bundle savedInstanceState) {\n binding = FragmentViewSetsBinding.inflate(getLayoutInflater());\n return binding.getRoot();\n }\n\n @Override\n public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {\n super.onViewCreated(view, savedInstanceState);\n userSharePreferences = new UserSharePreferences(requireActivity());\n binding.addSetsBtn.setOnClickListener(view1 -> {\n\n });\n\n fetchFlashCards();\n setupVisibility();\n setupRecyclerView();\n\n binding.addSetsBtn.setOnClickListener(v -> {\n Intent intent = new Intent(requireActivity(), AddFlashCardToClassActivity.class);\n intent.putExtra(\"flashcard_id\", userSharePreferences.getClassId());\n startActivity(intent);\n });\n }\n\n private void fetchFlashCards() {\n ArrayList<String> listId = groupDAO.getAllFlashCardInClass(userSharePreferences.getClassId());\n for (String id : listId) {\n flashCards.add(flashCardDAO.getFlashCardById(id));\n }\n }\n\n private void setupVisibility() {\n if (flashCards.isEmpty()) {\n binding.setsLl.setVisibility(View.VISIBLE);\n binding.setsRv.setVisibility(View.GONE);\n } else {\n binding.setsLl.setVisibility(View.GONE);\n binding.setsRv.setVisibility(View.VISIBLE);\n }\n }\n\n @SuppressLint(\"NotifyDataSetChanged\")\n private void setupRecyclerView() {\n SetCopyAdapter setsAdapter = new SetCopyAdapter(requireActivity(), flashCards);\n LinearLayoutManager linearLayoutManager = new LinearLayoutManager(requireContext(), LinearLayoutManager.VERTICAL, false);\n binding.setsRv.setLayoutManager(linearLayoutManager);\n binding.setsRv.setAdapter(setsAdapter);\n binding.setsRv.setHasFixedSize(true);\n setsAdapter.notifyDataSetChanged();\n }\n\n @Override\n public void onResume() {\n super.onResume();\n setupRecyclerView();\n }\n\n @Override\n public void onPause() {\n super.onPause();\n setupRecyclerView();\n }\n}"
},
{
"identifier": "FoldersFragment",
"path": "app/src/main/java/com/daominh/quickmem/ui/fragments/library/FoldersFragment.java",
"snippet": "public class FoldersFragment extends Fragment {\n private FragmentFoldersBinding binding;\n private UserSharePreferences userSharePreferences;\n private ArrayList<Folder> folders;\n private FolderCopyAdapter folderAdapter;\n private FolderDAO folderDAO;\n private String idUser;\n\n @Override\n public void onCreate(@Nullable Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n userSharePreferences = new UserSharePreferences(requireActivity());\n idUser = userSharePreferences.getId();\n folderDAO = new FolderDAO(requireActivity());\n }\n\n @Override\n public View onCreateView(@NotNull LayoutInflater inflater, ViewGroup container,\n Bundle savedInstanceState) {\n binding = FragmentFoldersBinding.inflate(inflater, container, false);\n return binding.getRoot();\n }\n\n @Override\n public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {\n super.onViewCreated(view, savedInstanceState);\n setupUserPreferences();\n setupCreateButton();\n setupFolders();\n setupRecyclerView();\n }\n\n private void setupUserPreferences() {\n userSharePreferences = new UserSharePreferences(requireActivity());\n idUser = userSharePreferences.getId();\n }\n\n private void setupCreateButton() {\n binding.createSetBtn.setOnClickListener(view1 -> startActivity(new Intent(getActivity(), CreateFolderActivity.class)));\n }\n\n private void setupFolders() {\n folders = folderDAO.getAllFolderByUserId(idUser);\n if (folders.isEmpty()) {\n binding.folderCl.setVisibility(View.VISIBLE);\n binding.foldersRv.setVisibility(View.GONE);\n } else {\n binding.folderCl.setVisibility(View.GONE);\n binding.foldersRv.setVisibility(View.VISIBLE);\n }\n }\n\n @SuppressLint(\"NotifyDataSetChanged\")\n private void setupRecyclerView() {\n folderAdapter = new FolderCopyAdapter(requireActivity(), folders);\n LinearLayoutManager linearLayoutManager1 = new LinearLayoutManager(requireActivity(), RecyclerView.VERTICAL, false);\n binding.foldersRv.setLayoutManager(linearLayoutManager1);\n binding.foldersRv.setAdapter(folderAdapter);\n folderAdapter.notifyDataSetChanged();\n }\n\n @Override\n public void onResume() {\n super.onResume();\n refreshData();\n }\n\n @SuppressLint(\"NotifyDataSetChanged\")\n private void refreshData() {\n folders = folderDAO.getAllFolderByUserId(idUser);\n\n folderAdapter = new FolderCopyAdapter(requireActivity(), folders);\n binding.foldersRv.setAdapter(folderAdapter);\n folderAdapter.notifyDataSetChanged();\n\n if (folders.isEmpty()) {\n binding.folderCl.setVisibility(View.VISIBLE);\n binding.foldersRv.setVisibility(View.GONE);\n } else {\n binding.folderCl.setVisibility(View.GONE);\n binding.foldersRv.setVisibility(View.VISIBLE);\n }\n }\n}"
},
{
"identifier": "MyClassesFragment",
"path": "app/src/main/java/com/daominh/quickmem/ui/fragments/library/MyClassesFragment.java",
"snippet": "public class MyClassesFragment extends Fragment {\n\n private FragmentMyClassesBinding binding;\n private UserSharePreferences userSharePreferences;\n private ArrayList<Group> classes;\n private GroupDAO groupDAO;\n private ClassCopyAdapter classAdapter;\n private String idUser;\n\n @Override\n public void onCreate(@Nullable Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n userSharePreferences = new UserSharePreferences(requireActivity());\n idUser = userSharePreferences.getId();\n groupDAO = new GroupDAO(requireActivity());\n }\n\n @Override\n public View onCreateView(@NotNull LayoutInflater inflater, ViewGroup container,\n Bundle savedInstanceState) {\n binding = FragmentMyClassesBinding.inflate(inflater, container, false);\n return binding.getRoot();\n }\n\n @SuppressLint(\"NotifyDataSetChanged\")\n @Override\n public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {\n super.onViewCreated(view, savedInstanceState);\n setupUserPreferences();\n setupCreateButton();\n setupClasses();\n setupRecyclerView();\n }\n\n private void setupUserPreferences() {\n userSharePreferences = new UserSharePreferences(requireActivity());\n idUser = userSharePreferences.getId();\n }\n\n private void setupCreateButton() {\n UserDAO userDAO = new UserDAO(getContext());\n User user = userDAO.getUserById(idUser);\n if (user.getRole() == 2) {\n binding.createSetBtn.setVisibility(View.GONE);\n }\n binding.createSetBtn.setOnClickListener(view1 -> startActivity(new Intent(getActivity(), CreateClassActivity.class)));\n }\n\n private void setupClasses() {\n classes = groupDAO.getClassesOwnedByUser(idUser);\n classes.addAll(groupDAO.getClassesUserIsMemberOf(idUser));\n if (classes.isEmpty()) {\n binding.classesCl.setVisibility(View.VISIBLE);\n binding.classesRv.setVisibility(View.GONE);\n } else {\n binding.classesCl.setVisibility(View.GONE);\n binding.classesRv.setVisibility(View.VISIBLE);\n }\n }\n\n @SuppressLint(\"NotifyDataSetChanged\")\n private void setupRecyclerView() {\n classAdapter = new ClassCopyAdapter(requireActivity(), classes);\n LinearLayoutManager linearLayoutManager2 = new LinearLayoutManager(requireActivity(), RecyclerView.VERTICAL, false);\n binding.classesRv.setLayoutManager(linearLayoutManager2);\n binding.classesRv.setAdapter(classAdapter);\n classAdapter.notifyDataSetChanged();\n }\n @Override\n public void onResume() {\n super.onResume();\n refreshData();\n }\n\n @SuppressLint(\"NotifyDataSetChanged\")\n private void refreshData() {\n classes = groupDAO.getClassesOwnedByUser(idUser);\n classes.addAll(groupDAO.getClassesUserIsMemberOf(idUser));\n\n classAdapter = new ClassCopyAdapter(requireActivity(), classes);\n binding.classesRv.setAdapter(classAdapter);\n classAdapter.notifyDataSetChanged();\n\n if (classes.isEmpty()) {\n binding.classesCl.setVisibility(View.VISIBLE);\n binding.classesRv.setVisibility(View.GONE);\n } else {\n binding.classesCl.setVisibility(View.GONE);\n binding.classesRv.setVisibility(View.VISIBLE);\n }\n }\n}"
},
{
"identifier": "StudySetsFragment",
"path": "app/src/main/java/com/daominh/quickmem/ui/fragments/library/StudySetsFragment.java",
"snippet": "public class StudySetsFragment extends Fragment {\n private FragmentStudySetsBinding binding;\n private ArrayList<FlashCard> flashCards;\n private FlashCardDAO flashCardDAO;\n private SetCopyAdapter setsAdapter;\n private String idUser;\n\n @Override\n public void onCreate(@Nullable Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n flashCardDAO = new FlashCardDAO(requireActivity());\n }\n\n @Override\n public View onCreateView(@NotNull LayoutInflater inflater, ViewGroup container,\n Bundle savedInstanceState) {\n binding = FragmentStudySetsBinding.inflate(inflater, container, false);\n return binding.getRoot();\n }\n\n @SuppressLint(\"NotifyDataSetChanged\")\n @Override\n public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {\n super.onViewCreated(view, savedInstanceState);\n setupView();\n }\n\n private void setupView() {\n UserSharePreferences userSharePreferences = new UserSharePreferences(requireActivity());\n idUser = userSharePreferences.getId();\n binding.createSetBtn.setOnClickListener(view1 -> startActivity(new Intent(getActivity(), CreateSetActivity.class)));\n flashCards = flashCardDAO.getAllFlashCardByUserId(idUser);\n updateVisibility();\n setupRecyclerView();\n }\n\n private void updateVisibility() {\n if (flashCards.isEmpty()) {\n binding.setsCl.setVisibility(View.VISIBLE);\n binding.setsRv.setVisibility(View.GONE);\n } else {\n binding.setsCl.setVisibility(View.GONE);\n binding.setsRv.setVisibility(View.VISIBLE);\n }\n }\n\n @SuppressLint(\"NotifyDataSetChanged\")\n private void setupRecyclerView() {\n LinearLayoutManager linearLayoutManager = new LinearLayoutManager(requireActivity(), RecyclerView.VERTICAL, false);\n binding.setsRv.setLayoutManager(linearLayoutManager);\n setsAdapter = new SetCopyAdapter(requireActivity(), flashCards);\n binding.setsRv.setAdapter(setsAdapter);\n setsAdapter.notifyDataSetChanged();\n }\n\n @Override\n public void onResume() {\n super.onResume();\n refreshData();\n }\n\n @SuppressLint(\"NotifyDataSetChanged\")\n private void refreshData() {\n flashCards.clear();\n flashCards.addAll(flashCardDAO.getAllFlashCardByUserId(idUser));\n setsAdapter.notifyDataSetChanged();\n updateVisibility();\n }\n}"
}
] | import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentStatePagerAdapter;
import com.daominh.quickmem.ui.activities.classes.ViewMembersFragment;
import com.daominh.quickmem.ui.activities.classes.ViewSetsFragment;
import com.daominh.quickmem.ui.fragments.library.FoldersFragment;
import com.daominh.quickmem.ui.fragments.library.MyClassesFragment;
import com.daominh.quickmem.ui.fragments.library.StudySetsFragment; | 3,101 | package com.daominh.quickmem.adapter.group;
public class MyViewClassAdapter extends FragmentStatePagerAdapter {
public MyViewClassAdapter(@NonNull FragmentManager fm, int behavior) {
super(fm, behavior);
}
@NonNull
@Override
public Fragment getItem(int position) {
return switch (position) {
case 1 -> new ViewMembersFragment(); | package com.daominh.quickmem.adapter.group;
public class MyViewClassAdapter extends FragmentStatePagerAdapter {
public MyViewClassAdapter(@NonNull FragmentManager fm, int behavior) {
super(fm, behavior);
}
@NonNull
@Override
public Fragment getItem(int position) {
return switch (position) {
case 1 -> new ViewMembersFragment(); | default -> new ViewSetsFragment(); | 1 | 2023-11-07 16:56:39+00:00 | 4k |
walidbosso/SpringBoot_Football_Matches | src/main/java/spring/tp/controllers/EquipeController.java | [
{
"identifier": "Joueur",
"path": "src/main/java/spring/tp/entities/Joueur.java",
"snippet": "@Data\n@AllArgsConstructor\n@NoArgsConstructor\n@Entity\npublic class Joueur {\n\t@Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n\tLong id;\n\tString nom;\n\tString poste;\n\n\t@ManyToOne\n\tEquipe equipe; \n}"
},
{
"identifier": "Matche",
"path": "src/main/java/spring/tp/entities/Matche.java",
"snippet": "@Data\n@AllArgsConstructor\n@NoArgsConstructor\n@Entity\npublic class Matche {\n\t@Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n\tLong id;\n\t@Temporal(TemporalType.DATE)\n private Date dateMatch;\n\n private String hourMatch;\n\n @ManyToOne\n private Stade stade;\n\n @ManyToOne\n @JoinColumn(name = \"equipe1_id\")\n private Equipe equipe1;\n\n @ManyToOne\n @JoinColumn(name = \"equipe2_id\")\n private Equipe equipe2;\n\n @ManyToOne\n private Arbitre arbitre; \n}"
},
{
"identifier": "Equipe",
"path": "src/main/java/spring/tp/entities/Equipe.java",
"snippet": "@Data\n@AllArgsConstructor\n@NoArgsConstructor\n@Entity\npublic class Equipe {\n\t@Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n\tLong id; \n\tString nom;\n\tString pays;\n\t \n\t@OneToMany(mappedBy = \"equipe1\")\n\t@JsonIgnore\n List<Matche> matchesAsEquipe1;\n\n @OneToMany(mappedBy = \"equipe2\")\n @JsonIgnore\n List<Matche> matchesAsEquipe2;\n \n\t@OneToMany(mappedBy = \"equipe\") \n\t@JsonIgnore //on recupere list de groups we ignore the students, because if we want to recupere a student it will recupere id nom et note et son groupe ( et groupe contient id nom and students, we ignore students)\n\tList<Joueur> joueurs; \n}"
},
{
"identifier": "EquipeService",
"path": "src/main/java/spring/tp/services/EquipeService.java",
"snippet": "@Service\npublic class EquipeService {\n\n\t@Autowired\n\tEquipeRepository er;\n\t@Autowired\n\tJoueurRepository jr;\n\t@Autowired\n\tMatcheRepository mr;\n\t\n\tpublic Equipe addEquipe( Equipe e) {\n\t\treturn er.save(e);\n\t}\n\t\n\tpublic List<Equipe> getAllEquipes(){\n\t\treturn er.findAll();\n\t}\t\n\t\n\tpublic Equipe getEquipeById( Long id) {\n\t\treturn er.findById(id).get(); \n\t}\n\t\n\t//we'll add player to equipe with id in url\n\tpublic Joueur addJoueurToEquipe( Long id, Joueur m) {\n\t\tEquipe e= er.findById(id).get(); \n\t\tm.setEquipe(e);\n\t\treturn jr.save(m);\n\t}\n\t\n\tpublic List<Equipe> findByPays() {\n\t\t\n\t\treturn er.findByPaysIgnoreCase(\"Maroc\");\n\t}\n\t\n\t//show list of players that belongs to an equipe with id url\n\tpublic List<Joueur> getJoueurByEquipeId( Long id) {\n\t\tEquipe e = er.findById(id).get();\n\t\treturn jr.findByEquipe(e); \n\t}\n\t\n\t//show list of players that belongs to an equipe with nom in url\n\t\tpublic List<Joueur> getJoueurByEquipeNom( String nom) {\n\t\t\tEquipe e = er.findByNom(nom);\n\t\t\treturn jr.findByEquipe(e); \n\t\t}\n\t\t\n\t\tpublic List<Joueur> getJoueurByEquipeNomAndPost( String nom, String post) {\n\t\t\tEquipe e = er.findByNom(nom);\n\t\t\t//System.out.println(e.getNom());\n\t\t\t\n\t\t\tList<Joueur> joueurs= jr.findByEquipe(e); \n\t\t\tSystem.out.println(joueurs.isEmpty());\n\t\t\tList<Joueur> attaquants = new ArrayList<>();\n\t\t\tjoueurs.forEach(m->{//expression lambda\n\t\t\t\tif(m.getPoste().equals(post)) attaquants.add(m);\n\t\t\t});\n\t\t\t\n\t\t\treturn attaquants;\n\t\t\t\n\t\t}\n\t\n\t//we'll add a match to an equipe, as an equipe1, match will save all infos of that equipe as an equipe1\n\tpublic Matche addMatcheToEquipe1( Long id, Matche m, Long id2) {\n\t\t//we see if that equipe with first id in url exists we fetch the whole equipe\n\t\tEquipe e= er.findById(id).orElseThrow(() -> new EntityNotFoundException(\"Equipe not found\"));\n\t\t//we check if that match already exists, we extract the whole match\n\t\tMatche m2= mr.findById(id2).orElse(null);\n\t\t//System.out.println(m2);\n\t\t//if the match doesn't exist, we take the Matche from body, add equipe 1 and save to bd\n\t\tif(m2==null) {m.setEquipe1(e); return mr.save(m);}\n\t\t//or else we take the already ex match, add equipe1 to it and update it\n\t\telse {m2.setEquipe1(e);\n\t\treturn mr.save(m2);}\n\t}\n\n\tpublic Matche addMatcheToEquipe2( Long id, Matche m, Long id2) {\n\t\tEquipe e= er.findById(id).orElseThrow(() -> new EntityNotFoundException(\"Equipe not found\"));\n\t\tMatche m2= mr.findById(id2).orElse(null);\n\t\t//System.out.println(m2);\n\t\tif(m2==null) {m.setEquipe2(e); return mr.save(m);}\n\t\telse m2.setEquipe2(e);\n\t\treturn mr.save(m2);\n\t}\n\t\n\tpublic List<Matche> getMatchByEquipe1Id( Long id) {\n\tEquipe e = er.findById(id).get();\n\treturn mr.findByEquipe1(e); \n\t}\n\t\n\t\n\tpublic List<Matche> getMatchByEquipe2Id( Long id) {\n\tEquipe e = er.findById(id).get();\n\treturn mr.findByEquipe2(e); \n\t}\n\t\n\tpublic Equipe updateEquipe( Equipe e) {\n\treturn er.save(e);\n\t}\n\t\n\t\n\tpublic void deleteEquipe( Long id) {\n\t\n\tList<Joueur> joueurs=getJoueurByEquipeId(id); \n\tList<Matche> matches1=getMatchByEquipe1Id(id);\n\tList<Matche> matches2=getMatchByEquipe2Id(id);\n\t\n\tjoueurs.forEach(m->{//expression lambda\n\t\tm.setEquipe(null);\n\t});\n\tmatches1.forEach(m->{\n\t\tm.setEquipe1(null);\n\t});\n\tmatches2.forEach(m->{\n\t\tm.setEquipe2(null);\n\t});\n\t\n\ter.deleteById(id);\n\t}\n}"
}
] | import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
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.RestController;
import spring.tp.entities.Joueur;
import spring.tp.entities.Matche;
import spring.tp.entities.Equipe;
import spring.tp.services.EquipeService; | 1,898 | package spring.tp.controllers;
@RestController
public class EquipeController {
@Autowired
EquipeService es;
@PostMapping("equipe")
public Equipe addEquipe(@RequestBody Equipe e) {
return es.addEquipe(e);
}
@GetMapping("equipe")
List<Equipe> getAllEquipes(){
return es.getAllEquipes();
}
@GetMapping("equipe/{id}")
public Equipe getEquipeById(@PathVariable Long id) {
return es.getEquipeById(id);
}
//we'll add player to equipe with id in url
@PostMapping("equipe/{id}/joueur") | package spring.tp.controllers;
@RestController
public class EquipeController {
@Autowired
EquipeService es;
@PostMapping("equipe")
public Equipe addEquipe(@RequestBody Equipe e) {
return es.addEquipe(e);
}
@GetMapping("equipe")
List<Equipe> getAllEquipes(){
return es.getAllEquipes();
}
@GetMapping("equipe/{id}")
public Equipe getEquipeById(@PathVariable Long id) {
return es.getEquipeById(id);
}
//we'll add player to equipe with id in url
@PostMapping("equipe/{id}/joueur") | public Joueur addJoueurToEquipe(@PathVariable Long id, @RequestBody Joueur m) { | 0 | 2023-11-07 21:46:09+00:00 | 4k |
FRCTeam2910/2023CompetitionRobot-Public | src/main/java/org/frcteam2910/c2023/subsystems/arm/ArmIOSim.java | [
{
"identifier": "Robot",
"path": "src/main/java/org/frcteam2910/c2023/Robot.java",
"snippet": "public class Robot extends LoggedRobot {\n private RobotContainer robotContainer;\n\n private final PowerDistribution powerDistribution = new PowerDistribution();\n private final LinearFilter average = LinearFilter.movingAverage(50);\n\n @Override\n public void robotInit() {\n Logger logger = Logger.getInstance();\n\n // Record metadata\n logger.recordMetadata(\"GitRevision\", String.valueOf(BuildInfo.GIT_REVISION));\n logger.recordMetadata(\"GitSHA\", BuildInfo.GIT_SHA);\n logger.recordMetadata(\"GitDate\", BuildInfo.GIT_DATE);\n logger.recordMetadata(\"GitBranch\", BuildInfo.GIT_BRANCH);\n logger.recordMetadata(\"BuildDate\", BuildInfo.BUILD_DATE);\n logger.recordMetadata(\"BuildUnixTime\", String.valueOf(BuildInfo.BUILD_UNIX_TIME));\n switch (BuildInfo.DIRTY) {\n case 0:\n logger.recordMetadata(\"GitDirty\", \"Clean\");\n break;\n case 1:\n logger.recordMetadata(\"GitDirty\", \"Dirty\");\n break;\n default:\n logger.recordMetadata(\"GitDirty\", \"Error\");\n break;\n }\n logger.recordMetadata(\"Robot Name\", RobotIdentity.getIdentity().toString());\n logger.recordMetadata(\"Robot MAC Address\", MacAddressUtil.getMACAddress());\n\n // Set up data receivers & replay sources\n switch (RobotConfiguration.getMode()) {\n // Running on a real robot, log to a USB stick\n case REAL:\n logger.addDataReceiver(new WPILOGWriter(\"/media/sda1/\"));\n logger.addDataReceiver(new NT4Publisher());\n break;\n\n // Running a physics simulator, log to NetworkTables\n case SIM:\n logger.addDataReceiver(new NT4Publisher());\n break;\n\n // Replaying a log, set up replay source\n case REPLAY:\n setUseTiming(false); // Run as fast as possible\n String logPath = LogFileUtil.findReplayLog();\n logger.setReplaySource(new WPILOGReader(logPath));\n logger.addDataReceiver(new WPILOGWriter(LogFileUtil.addPathSuffix(logPath, \"_sim\")));\n }\n\n // Start AdvantageKit logger\n logger.start();\n\n robotContainer = new RobotContainer();\n }\n\n @SuppressWarnings(\"unused\")\n private final DriverReadouts driverReadout = new DriverReadouts(robotContainer);\n\n @Override\n public void robotPeriodic() {\n double start = System.currentTimeMillis();\n CommandScheduler.getInstance().run();\n double end = System.currentTimeMillis();\n double commandSchedulerTime = end - start;\n Logger.getInstance().recordOutput(\"Times/CommandSchedulerMs\", commandSchedulerTime);\n Logger.getInstance().recordOutput(\"Times/CommandSchedulerMsAverage\", average.calculate(commandSchedulerTime));\n\n start = System.currentTimeMillis();\n robotContainer.getOperatorDashboard().update();\n end = System.currentTimeMillis();\n Logger.getInstance().recordOutput(\"Times/OperatorDashboardMs\", end - start);\n\n start = System.currentTimeMillis();\n robotContainer.getSuperstructure().update();\n end = System.currentTimeMillis();\n Logger.getInstance().recordOutput(\"Times/SuperstructureMs\", end - start);\n\n start = System.currentTimeMillis();\n FieldConstants.update();\n end = System.currentTimeMillis();\n Logger.getInstance().recordOutput(\"Times/FieldConstantsMs\", end - start);\n }\n\n @Override\n public void disabledPeriodic() {\n if (robotContainer.getArmSubsystem().isZeroed()) {\n robotContainer.getLedSubsystem().setWantedAction(LEDSubsystem.WantedAction.DISPLAY_ROBOT_ARM_ZEROED);\n } else {\n robotContainer.getLedSubsystem().setWantedAction(LEDSubsystem.WantedAction.DISPLAY_ROBOT_ARM_NOT_ZEROED);\n }\n }\n\n @Override\n public void teleopPeriodic() {\n if (robotContainer.getArmSubsystem().isZeroed()\n && !robotContainer.getLedSubsystem().getIsBadAlign()\n && !robotContainer.getLedSubsystem().getIsFlashing()) {\n if (robotContainer.getOperatorDashboard().getSelectedGamePiece() == GamePiece.CONE) {\n robotContainer.getLedSubsystem().setWantedAction(LEDSubsystem.WantedAction.DISPLAY_GETTING_CONE);\n } else {\n robotContainer.getLedSubsystem().setWantedAction(LEDSubsystem.WantedAction.DISPLAY_GETTING_CUBE);\n }\n }\n }\n\n @Override\n public void autonomousInit() {\n robotContainer.getAutonomousCommand().schedule();\n }\n}"
},
{
"identifier": "Interpolation",
"path": "src/main/java/org/frcteam2910/c2023/util/Interpolation.java",
"snippet": "public class Interpolation {\n /**\n * Gives me the \"t\" value needed to calculate moment of inertia\n * @param startValue Minimum extension length\n * @param endValue Maximum extension length\n * @param x Current extension length\n * @return The t value\n */\n public static double inverseInterpolate(double startValue, double endValue, double x) {\n return (x - startValue) / (endValue - startValue);\n }\n}"
}
] | import edu.wpi.first.math.MathUtil;
import edu.wpi.first.math.Matrix;
import edu.wpi.first.math.VecBuilder;
import edu.wpi.first.math.controller.PIDController;
import edu.wpi.first.math.geometry.Rotation2d;
import edu.wpi.first.math.geometry.Translation2d;
import edu.wpi.first.math.numbers.N1;
import edu.wpi.first.math.numbers.N3;
import edu.wpi.first.math.numbers.N6;
import edu.wpi.first.math.system.NumericalIntegration;
import edu.wpi.first.math.system.plant.DCMotor;
import edu.wpi.first.math.util.Units;
import org.frcteam2910.c2023.Robot;
import org.frcteam2910.c2023.util.Interpolation; | 2,412 | package org.frcteam2910.c2023.subsystems.arm;
public class ArmIOSim implements ArmIO {
private static final DCMotor SHOULDER_MOTOR = DCMotor.getFalcon500(4).withReduction(100.0);
private static final DCMotor WRIST_MOTOR = DCMotor.getFalcon500(1).withReduction(1.0);
private static final DCMotor EXTENSION_MOTOR = DCMotor.getFalcon500(2).withReduction(1.0);
private static final double SHOULDER_CURRENT_LIMIT_AMPS = 40.0;
private static final double SHOULDER_MINIMUM_MOMENT_OF_INERTIA = 1.0;
private static final double SHOULDER_MASS_KG = Units.lbsToKilograms(20);
private static final Translation2d SHOULDER_CG_OFFSET = new Translation2d();
private static final double SHOULDER_AXLE_OFFSET = 0;
private static final double EXTENSION_CURRENT_LIMIT_AMPS = 20;
private static final double EXTENSION_PULLEY_RADIUS_METERS = Units.inchesToMeters(3);
private static final double EXTENSION_MINIMUM_MOMENT_OF_INERTIA = 1.0;
private static final double EXTENSION_MAXIMUM_MOMENT_OF_INERTIA = 2.0;
private static final double EXTENSION_MINIMUM_LENGTH_METERS = Units.inchesToMeters(20);
private static final double EXTENSION_MAXIMUM_LENGTH_METERS = Units.inchesToMeters(40);
private static final double EXTENSION_MASS_KG = Units.lbsToKilograms(20);
private static final double EXTENSION_CG_OFFSET = Units.inchesToMeters(5);
private static final Translation2d EXTENSION_MINIMUM_CG = new Translation2d();
private static final Translation2d EXTENSION_MAXIMUM_CG = new Translation2d();
private static final double WRIST_CURRENT_LIMIT_AMPS = 10;
private static final double WRIST_MINIMUM_MOMENT_OF_INERTIA = 1.0;
private static final double WRIST_MASS_KG = Units.lbsToKilograms(5);
private static final Translation2d WRIST_CG_OFFSET = new Translation2d();
private static final Translation2d WRIST_AXLE_OFFSET = new Translation2d();
private final PIDController shoulderFeedback = new PIDController(1, 0, 0);
private final PIDController wristFeedback = new PIDController(1, 0, 0);
private final PIDController extensionFeedback = new PIDController(1, 0, 0);
@Override
public void updateInputs(ArmIOInputs inputs) {
Matrix<N6, N1> systemStates = VecBuilder.fill(
inputs.shoulderAngleRad,
inputs.shoulderAngularVelocityRadPerSec,
inputs.extensionPositionMeters,
inputs.extensionVelocityMetersPerSec,
inputs.wristAngleRad,
inputs.wristAngularVelocityRadPerSec);
Matrix<N3, N1> systemInputs = VecBuilder.fill(
shoulderFeedback.calculate(inputs.shoulderAngleRad),
extensionFeedback.calculate(inputs.extensionPositionMeters),
wristFeedback.calculate(inputs.wristAngleRad));
Matrix<N6, N1> nextState =
NumericalIntegration.rk4(this::calculateSystem, systemStates, systemInputs, Robot.defaultPeriodSecs);
inputs.shoulderAngleRad = nextState.get(0, 0);
inputs.shoulderAngularVelocityRadPerSec = nextState.get(1, 0);
inputs.shoulderAppliedVolts = systemInputs.get(0, 0);
inputs.shoulderCurrentDrawAmps = Math.min(
Math.abs(SHOULDER_MOTOR.getCurrent(
inputs.shoulderAngularVelocityRadPerSec, inputs.shoulderAppliedVolts)),
SHOULDER_CURRENT_LIMIT_AMPS);
inputs.extensionPositionMeters = nextState.get(2, 0);
inputs.extensionVelocityMetersPerSec = nextState.get(3, 0);
inputs.extensionAppliedVolts = systemInputs.get(1, 0);
inputs.extensionCurrentDrawAmps = Math.min(
Math.abs(
EXTENSION_MOTOR.getCurrent(inputs.extensionVelocityMetersPerSec, inputs.extensionAppliedVolts)),
EXTENSION_CURRENT_LIMIT_AMPS);
inputs.wristAngleRad = nextState.get(4, 0);
inputs.wristAngularVelocityRadPerSec = nextState.get(5, 0);
inputs.wristAppliedVolts = systemInputs.get(2, 0);
inputs.wristCurrentDrawAmps = Math.min(
Math.abs(WRIST_MOTOR.getCurrent(inputs.wristAngularVelocityRadPerSec, inputs.wristAppliedVolts)),
WRIST_CURRENT_LIMIT_AMPS);
}
private double calculateShoulderAngularMomentOfInertia(
double shoulderAngle, double extensionLength, double wristAngle) { | package org.frcteam2910.c2023.subsystems.arm;
public class ArmIOSim implements ArmIO {
private static final DCMotor SHOULDER_MOTOR = DCMotor.getFalcon500(4).withReduction(100.0);
private static final DCMotor WRIST_MOTOR = DCMotor.getFalcon500(1).withReduction(1.0);
private static final DCMotor EXTENSION_MOTOR = DCMotor.getFalcon500(2).withReduction(1.0);
private static final double SHOULDER_CURRENT_LIMIT_AMPS = 40.0;
private static final double SHOULDER_MINIMUM_MOMENT_OF_INERTIA = 1.0;
private static final double SHOULDER_MASS_KG = Units.lbsToKilograms(20);
private static final Translation2d SHOULDER_CG_OFFSET = new Translation2d();
private static final double SHOULDER_AXLE_OFFSET = 0;
private static final double EXTENSION_CURRENT_LIMIT_AMPS = 20;
private static final double EXTENSION_PULLEY_RADIUS_METERS = Units.inchesToMeters(3);
private static final double EXTENSION_MINIMUM_MOMENT_OF_INERTIA = 1.0;
private static final double EXTENSION_MAXIMUM_MOMENT_OF_INERTIA = 2.0;
private static final double EXTENSION_MINIMUM_LENGTH_METERS = Units.inchesToMeters(20);
private static final double EXTENSION_MAXIMUM_LENGTH_METERS = Units.inchesToMeters(40);
private static final double EXTENSION_MASS_KG = Units.lbsToKilograms(20);
private static final double EXTENSION_CG_OFFSET = Units.inchesToMeters(5);
private static final Translation2d EXTENSION_MINIMUM_CG = new Translation2d();
private static final Translation2d EXTENSION_MAXIMUM_CG = new Translation2d();
private static final double WRIST_CURRENT_LIMIT_AMPS = 10;
private static final double WRIST_MINIMUM_MOMENT_OF_INERTIA = 1.0;
private static final double WRIST_MASS_KG = Units.lbsToKilograms(5);
private static final Translation2d WRIST_CG_OFFSET = new Translation2d();
private static final Translation2d WRIST_AXLE_OFFSET = new Translation2d();
private final PIDController shoulderFeedback = new PIDController(1, 0, 0);
private final PIDController wristFeedback = new PIDController(1, 0, 0);
private final PIDController extensionFeedback = new PIDController(1, 0, 0);
@Override
public void updateInputs(ArmIOInputs inputs) {
Matrix<N6, N1> systemStates = VecBuilder.fill(
inputs.shoulderAngleRad,
inputs.shoulderAngularVelocityRadPerSec,
inputs.extensionPositionMeters,
inputs.extensionVelocityMetersPerSec,
inputs.wristAngleRad,
inputs.wristAngularVelocityRadPerSec);
Matrix<N3, N1> systemInputs = VecBuilder.fill(
shoulderFeedback.calculate(inputs.shoulderAngleRad),
extensionFeedback.calculate(inputs.extensionPositionMeters),
wristFeedback.calculate(inputs.wristAngleRad));
Matrix<N6, N1> nextState =
NumericalIntegration.rk4(this::calculateSystem, systemStates, systemInputs, Robot.defaultPeriodSecs);
inputs.shoulderAngleRad = nextState.get(0, 0);
inputs.shoulderAngularVelocityRadPerSec = nextState.get(1, 0);
inputs.shoulderAppliedVolts = systemInputs.get(0, 0);
inputs.shoulderCurrentDrawAmps = Math.min(
Math.abs(SHOULDER_MOTOR.getCurrent(
inputs.shoulderAngularVelocityRadPerSec, inputs.shoulderAppliedVolts)),
SHOULDER_CURRENT_LIMIT_AMPS);
inputs.extensionPositionMeters = nextState.get(2, 0);
inputs.extensionVelocityMetersPerSec = nextState.get(3, 0);
inputs.extensionAppliedVolts = systemInputs.get(1, 0);
inputs.extensionCurrentDrawAmps = Math.min(
Math.abs(
EXTENSION_MOTOR.getCurrent(inputs.extensionVelocityMetersPerSec, inputs.extensionAppliedVolts)),
EXTENSION_CURRENT_LIMIT_AMPS);
inputs.wristAngleRad = nextState.get(4, 0);
inputs.wristAngularVelocityRadPerSec = nextState.get(5, 0);
inputs.wristAppliedVolts = systemInputs.get(2, 0);
inputs.wristCurrentDrawAmps = Math.min(
Math.abs(WRIST_MOTOR.getCurrent(inputs.wristAngularVelocityRadPerSec, inputs.wristAppliedVolts)),
WRIST_CURRENT_LIMIT_AMPS);
}
private double calculateShoulderAngularMomentOfInertia(
double shoulderAngle, double extensionLength, double wristAngle) { | double t = Interpolation.inverseInterpolate( | 1 | 2023-11-03 02:12:12+00:00 | 4k |
YunaBraska/type-map | src/main/java/berlin/yuna/typemap/logic/JsonEncoder.java | [
{
"identifier": "arrayOf",
"path": "src/main/java/berlin/yuna/typemap/logic/TypeConverter.java",
"snippet": "public static <E> E[] arrayOf(final Object object, final E[] typeIndicator, final Class<E> componentType) {\n ArrayList<E> result = collectionOf(object, ArrayList::new, componentType);\n result = result == null ? new ArrayList<>() : result;\n return result.toArray(Arrays.copyOf(typeIndicator, result.size()));\n}"
},
{
"identifier": "convertObj",
"path": "src/main/java/berlin/yuna/typemap/logic/TypeConverter.java",
"snippet": "@SuppressWarnings({\"rawtypes\", \"unchecked\"})\npublic static <T> T convertObj(final Object value, final Class<T> targetType) {\n if (value == null) return null;\n if (targetType.isInstance(value)) {\n return targetType.cast(value);\n }\n\n // Handle non-empty arrays, collections, map\n final Object firstValue = getFirstItem(value);\n if (firstValue != null) {\n return convertObj(firstValue, targetType);\n }\n\n // Enums\n if (targetType.isEnum()) {\n return (T) enumOf(String.valueOf(value), (Class<Enum>) targetType);\n }\n\n final Class<?> sourceType = value.getClass();\n final Map<Class<?>, FunctionOrNull> conversions = TYPE_CONVERSIONS.getOrDefault(targetType, Collections.emptyMap());\n\n // First try to find exact match\n final FunctionOrNull exactMatch = conversions.get(sourceType);\n if (exactMatch != null) {\n return targetType.cast(exactMatch.apply(value));\n }\n\n // Fallback to more general converters\n for (final Map.Entry<Class<?>, FunctionOrNull> entry : conversions.entrySet()) {\n if (entry.getKey().isAssignableFrom(sourceType)) {\n return targetType.cast(entry.getValue().apply(value));\n }\n }\n\n // Fallback to string convert\n if (!String.class.equals(sourceType)) {\n return convertObj(String.valueOf(value), targetType);\n }\n return null;\n}"
}
] | import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.function.IntFunction;
import java.util.stream.Collectors;
import static berlin.yuna.typemap.logic.TypeConverter.arrayOf;
import static berlin.yuna.typemap.logic.TypeConverter.convertObj; | 1,715 | package berlin.yuna.typemap.logic;
public class JsonEncoder {
@SuppressWarnings({"java:S2386"})
public static final Map<Character, String> JSON_ESCAPE_SEQUENCES = new HashMap<>();
@SuppressWarnings({"java:S2386"})
public static final Map<String, String> JSON_UNESCAPE_SEQUENCES = new HashMap<>();
static {
JSON_ESCAPE_SEQUENCES.put('"', "\\\"");
JSON_ESCAPE_SEQUENCES.put('\\', "\\\\");
JSON_ESCAPE_SEQUENCES.put('\b', "\\b");
JSON_ESCAPE_SEQUENCES.put('\f', "\\f");
JSON_ESCAPE_SEQUENCES.put('\n', "\\n");
JSON_ESCAPE_SEQUENCES.put('\r', "\\r");
JSON_ESCAPE_SEQUENCES.put('\t', "\\t");
JSON_ESCAPE_SEQUENCES.forEach((key, value) -> JSON_UNESCAPE_SEQUENCES.put(value, key.toString()));
}
/**
* Converts any object to its JSON representation.
* This method dispatches the conversion task based on the type of the object.
* It handles Maps, Collections, Arrays (both primitive and object types),
* and other objects. If the object is null, it returns an empty JSON object ({}).
* Standalone objects are converted to JSON strings and wrapped in curly braces,
* making them single-property JSON objects.
*
* @param object The object to be converted to JSON.
* @return A JSON representation of the object as a String.
* If the object is null, returns "{}".
*/
public static String toJson(final Object object) {
if (object == null) {
return "{}";
} else if (object instanceof Map) {
return jsonOf((Map<?, ?>) object);
} else if (object instanceof Collection) {
return jsonOf((Collection<?>) object);
} else if (object.getClass().isArray()) {
return jsonOfArray(object, Object[]::new, Object.class);
} else {
return "{" + jsonify(object) + "}";
}
}
/**
* Escapes a String for JSON.
* This method replaces special characters in a String with their corresponding JSON escape sequences.
*
* @param str The string to be escaped for JSON.
* @return The escaped JSON string.
*/
public static String escapeJsonValue(final String str) {
return str == null ? null : str.chars()
.mapToObj(c -> escapeJson((char) c))
.collect(Collectors.joining());
}
/**
* Escapes a character for JSON.
* This method returns the JSON escape sequence for a given character, if necessary.
*
* @param c The character to be escaped for JSON.
* @return The escaped JSON character as a String.
*/
public static String escapeJson(final char c) {
return JSON_ESCAPE_SEQUENCES.getOrDefault(c, (c < 32 || c >= 127) ? String.format("\\u%04x", (int) c) : String.valueOf(c));
}
/**
* Unescapes a JSON string by replacing JSON escape sequences with their corresponding characters.
* <p>
* This method iterates through a predefined set of JSON escape sequences (like \" for double quotes,
* \\ for backslash, \n for newline, etc.) and replaces them in the input string with the actual characters
* they represent. The method is designed to process a JSON-encoded string and return a version with
* standard characters, making it suitable for further processing or display.
* <p>
* Note: This method assumes that the input string is a valid JSON string with correct escape sequences.
* It does not perform JSON validation.
*
* @param str The JSON string with escape sequences to be unescaped.
* @return The unescaped version of the JSON string.
*/
public static String unescapeJson(final String str) {
String result = str;
for (final Map.Entry<String, String> entry : JSON_UNESCAPE_SEQUENCES.entrySet()) {
result = result.replace(entry.getKey(), entry.getValue());
}
return result;
}
private static String jsonOf(final Map<?, ?> map) {
return map.entrySet().stream()
.map(entry -> jsonify(entry.getKey()) + ":" + jsonify(entry.getValue()))
.collect(Collectors.joining(",", "{", "}"));
}
private static String jsonOf(final Collection<?> collection) {
return collection.stream()
.map(JsonEncoder::jsonify)
.collect(Collectors.joining(",", "[", "]"));
}
@SuppressWarnings("SameParameterValue")
private static <E> String jsonOfArray(final Object object, final IntFunction<E[]> generator, final Class<E> componentType) {
return object.getClass().isArray() ? Arrays.stream(arrayOf(object, generator, componentType))
.map(JsonEncoder::jsonify)
.collect(Collectors.joining(",", "[", "]")) : "null";
}
private static String jsonify(final Object obj) {
if (obj == null) {
return "null";
} else if (obj instanceof String) {
return "\"" + escapeJsonValue((String) obj) + "\"";
} else if (obj instanceof Number || obj instanceof Boolean) {
return obj.toString();
} else if (obj instanceof Map) {
return jsonOf((Map<?, ?>) obj);
} else if (obj instanceof Collection) {
return jsonOf((Collection<?>) obj);
} else if (obj.getClass().isArray()) {
return jsonOfArray(obj, Object[]::new, Object.class);
} else { | package berlin.yuna.typemap.logic;
public class JsonEncoder {
@SuppressWarnings({"java:S2386"})
public static final Map<Character, String> JSON_ESCAPE_SEQUENCES = new HashMap<>();
@SuppressWarnings({"java:S2386"})
public static final Map<String, String> JSON_UNESCAPE_SEQUENCES = new HashMap<>();
static {
JSON_ESCAPE_SEQUENCES.put('"', "\\\"");
JSON_ESCAPE_SEQUENCES.put('\\', "\\\\");
JSON_ESCAPE_SEQUENCES.put('\b', "\\b");
JSON_ESCAPE_SEQUENCES.put('\f', "\\f");
JSON_ESCAPE_SEQUENCES.put('\n', "\\n");
JSON_ESCAPE_SEQUENCES.put('\r', "\\r");
JSON_ESCAPE_SEQUENCES.put('\t', "\\t");
JSON_ESCAPE_SEQUENCES.forEach((key, value) -> JSON_UNESCAPE_SEQUENCES.put(value, key.toString()));
}
/**
* Converts any object to its JSON representation.
* This method dispatches the conversion task based on the type of the object.
* It handles Maps, Collections, Arrays (both primitive and object types),
* and other objects. If the object is null, it returns an empty JSON object ({}).
* Standalone objects are converted to JSON strings and wrapped in curly braces,
* making them single-property JSON objects.
*
* @param object The object to be converted to JSON.
* @return A JSON representation of the object as a String.
* If the object is null, returns "{}".
*/
public static String toJson(final Object object) {
if (object == null) {
return "{}";
} else if (object instanceof Map) {
return jsonOf((Map<?, ?>) object);
} else if (object instanceof Collection) {
return jsonOf((Collection<?>) object);
} else if (object.getClass().isArray()) {
return jsonOfArray(object, Object[]::new, Object.class);
} else {
return "{" + jsonify(object) + "}";
}
}
/**
* Escapes a String for JSON.
* This method replaces special characters in a String with their corresponding JSON escape sequences.
*
* @param str The string to be escaped for JSON.
* @return The escaped JSON string.
*/
public static String escapeJsonValue(final String str) {
return str == null ? null : str.chars()
.mapToObj(c -> escapeJson((char) c))
.collect(Collectors.joining());
}
/**
* Escapes a character for JSON.
* This method returns the JSON escape sequence for a given character, if necessary.
*
* @param c The character to be escaped for JSON.
* @return The escaped JSON character as a String.
*/
public static String escapeJson(final char c) {
return JSON_ESCAPE_SEQUENCES.getOrDefault(c, (c < 32 || c >= 127) ? String.format("\\u%04x", (int) c) : String.valueOf(c));
}
/**
* Unescapes a JSON string by replacing JSON escape sequences with their corresponding characters.
* <p>
* This method iterates through a predefined set of JSON escape sequences (like \" for double quotes,
* \\ for backslash, \n for newline, etc.) and replaces them in the input string with the actual characters
* they represent. The method is designed to process a JSON-encoded string and return a version with
* standard characters, making it suitable for further processing or display.
* <p>
* Note: This method assumes that the input string is a valid JSON string with correct escape sequences.
* It does not perform JSON validation.
*
* @param str The JSON string with escape sequences to be unescaped.
* @return The unescaped version of the JSON string.
*/
public static String unescapeJson(final String str) {
String result = str;
for (final Map.Entry<String, String> entry : JSON_UNESCAPE_SEQUENCES.entrySet()) {
result = result.replace(entry.getKey(), entry.getValue());
}
return result;
}
private static String jsonOf(final Map<?, ?> map) {
return map.entrySet().stream()
.map(entry -> jsonify(entry.getKey()) + ":" + jsonify(entry.getValue()))
.collect(Collectors.joining(",", "{", "}"));
}
private static String jsonOf(final Collection<?> collection) {
return collection.stream()
.map(JsonEncoder::jsonify)
.collect(Collectors.joining(",", "[", "]"));
}
@SuppressWarnings("SameParameterValue")
private static <E> String jsonOfArray(final Object object, final IntFunction<E[]> generator, final Class<E> componentType) {
return object.getClass().isArray() ? Arrays.stream(arrayOf(object, generator, componentType))
.map(JsonEncoder::jsonify)
.collect(Collectors.joining(",", "[", "]")) : "null";
}
private static String jsonify(final Object obj) {
if (obj == null) {
return "null";
} else if (obj instanceof String) {
return "\"" + escapeJsonValue((String) obj) + "\"";
} else if (obj instanceof Number || obj instanceof Boolean) {
return obj.toString();
} else if (obj instanceof Map) {
return jsonOf((Map<?, ?>) obj);
} else if (obj instanceof Collection) {
return jsonOf((Collection<?>) obj);
} else if (obj.getClass().isArray()) {
return jsonOfArray(obj, Object[]::new, Object.class);
} else { | final String str = convertObj(obj, String.class); | 1 | 2023-11-09 14:40:13+00:00 | 4k |
estkme-group/InfiLPA | app/src/main/java/com/infineon/esim/lpa/euicc/usbreader/identive/IdentiveUSBReaderInterface.java | [
{
"identifier": "EuiccConnection",
"path": "app/src/main/java/com/infineon/esim/lpa/euicc/base/EuiccConnection.java",
"snippet": "@SuppressWarnings(\"unused\")\npublic interface EuiccConnection extends EuiccChannel {\n\n void updateEuiccConnectionSettings(EuiccConnectionSettings euiccConnectionSettings);\n\n String getEuiccName();\n\n boolean open() throws Exception;\n void close() throws Exception;\n boolean isOpen();\n\n boolean resetEuicc() throws Exception;\n}"
},
{
"identifier": "EuiccInterfaceStatusChangeHandler",
"path": "app/src/main/java/com/infineon/esim/lpa/euicc/base/EuiccInterfaceStatusChangeHandler.java",
"snippet": "@SuppressWarnings(\"unused\")\npublic interface EuiccInterfaceStatusChangeHandler {\n\n void onEuiccInterfaceConnected(String interfaceTag);\n void onEuiccInterfaceDisconnected(String interfaceTag);\n\n void onEuiccConnected(String euiccName, EuiccConnection euiccConnection);\n void onEuiccListRefreshed(List<String> euiccDescriptions);\n}"
},
{
"identifier": "USBReaderConnectionBroadcastReceiver",
"path": "app/src/main/java/com/infineon/esim/lpa/euicc/usbreader/USBReaderConnectionBroadcastReceiver.java",
"snippet": "public class USBReaderConnectionBroadcastReceiver extends BroadcastReceiver {\n private static final String TAG = USBReaderConnectionBroadcastReceiver.class.getName();\n\n private final Context context;\n private final OnDisconnectCallback onDisconnectCallback;\n private static USBReaderEuiccInterface usbif;\n private static boolean hasBeenFreshlyAttached = false;\n private static String lastReaderName;\n\n public USBReaderConnectionBroadcastReceiver(Context context, OnDisconnectCallback onDisconnectCallback,USBReaderEuiccInterface usbif) {\n this.context = context;\n this.onDisconnectCallback = onDisconnectCallback;\n this.usbif = usbif;\n }\n\n @Override\n @SuppressWarnings(\"deprecation\")\n public void onReceive(Context context, Intent intent) {\n Log.debug(TAG, \"Received a broadcast.\");\n Log.debug(TAG, \"Action: \" + intent.getAction());\n\n switch (intent.getAction()) {\n case UsbManager.ACTION_USB_DEVICE_ATTACHED:\n UsbDevice usbDevice;\n\n if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {\n usbDevice = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE, UsbDevice.class);\n } else {\n usbDevice = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);\n }\n\n lastReaderName = usbDevice.getProductName();\n\n Log.info(TAG,\"USB reader \\\"\" + lastReaderName + \"\\\" attached.\");\n hasBeenFreshlyAttached = true;\n\n /* Do not directly initialize because of user prompt. Only in onResume method in the\n activity (e.g. ProfileListActivity).\n */\n break;\n case UsbManager.ACTION_USB_DEVICE_DETACHED:\n onDisconnectCallback.onDisconnect();\n break;\n default:\n Log.error(TAG, \"Unknown action: \" + intent.getAction());\n }\n }\n\n public void registerReceiver() {\n IntentFilter filter = new IntentFilter();\n filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);\n filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);\n context.registerReceiver(this, filter);\n }\n\n public static Boolean hasBeenFreshlyAttached() throws Exception {\n if(hasBeenFreshlyAttached) {\n hasBeenFreshlyAttached = false;\n if(usbif.checkDevice(lastReaderName)) {\n return true;\n } else {\n throw new Exception(\"Reader \\\"\" + lastReaderName + \"\\\" not supported.\");\n }\n } else {\n return false;\n }\n }\n\n public static boolean isDeviceAttached() {\n UsbManager usbManager = Application.getUsbManager();\n\n HashMap<String, UsbDevice> deviceList = usbManager.getDeviceList();\n for (UsbDevice device : deviceList.values()) {\n Log.debug(TAG, \"USB device attached: \" + device.getProductName());\n\n return usbif.checkDevice(device.getProductName());\n }\n\n return false;\n }\n\n public interface OnDisconnectCallback {\n void onDisconnect();\n }\n}"
},
{
"identifier": "USBReaderInterface",
"path": "app/src/main/java/com/infineon/esim/lpa/euicc/usbreader/USBReaderInterface.java",
"snippet": "public interface USBReaderInterface {\n boolean checkDevice(String name);\n boolean isInterfaceConnected();\n boolean connectInterface() throws Exception;\n boolean disconnectInterface() throws Exception;\n\n List<String> refreshEuiccNames() throws Exception;\n List<String> getEuiccNames();\n\n EuiccConnection getEuiccConnection(String euiccName) throws Exception;\n}"
},
{
"identifier": "Log",
"path": "app/src/test/java/com/infineon/esim/util/Log.java",
"snippet": "final public class Log {\n\n // Ref:\n // https://stackoverflow.com/questions/8355632/how-do-you-usually-tag-log-entries-android\n public static String getFileLineNumber() {\n String info = \"\";\n final StackTraceElement[] ste = Thread.currentThread().getStackTrace();\n for (int i = 0; i < ste.length; i++) {\n if (ste[i].getMethodName().equals(\"getFileLineNumber\")) {\n info = \"(\"+ste[i + 1].getFileName() + \":\" + ste[i + 1].getLineNumber()+\")\";\n }\n }\n return info;\n }\n\n public static void verbose(final String tag, final String msg) {\n System.out.println(\"V - \" + tag + \": \" + msg);\n }\n\n public static void debug(final String tag, final String msg) {\n System.out.println(\"D - \" + tag + \": \" + msg);\n }\n\n public static void info(final String tag, final String msg) {\n System.out.println(\"I- \" + tag + \": \" + msg);\n }\n\n public static void error(final String msg) {\n System.out.println(\"E- \" + msg);\n }\n\n public static void error(final String tag, final String msg) {\n System.out.println(\"E- \" + tag + \": \" + msg);\n }\n\n public static void error(final String tag, final String msg, final Throwable error) {\n System.out.println(\"E- \" + tag + \": \" + msg);\n error.printStackTrace();\n }\n}"
}
] | import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import android.content.Context;
import com.infineon.esim.lpa.euicc.base.EuiccConnection;
import com.infineon.esim.lpa.euicc.base.EuiccInterfaceStatusChangeHandler;
import com.infineon.esim.lpa.euicc.usbreader.USBReaderConnectionBroadcastReceiver;
import com.infineon.esim.lpa.euicc.usbreader.USBReaderInterface;
import com.infineon.esim.util.Log; | 2,034 | /*
* THE SOURCE CODE AND ITS RELATED DOCUMENTATION IS PROVIDED "AS IS". INFINEON
* TECHNOLOGIES MAKES NO OTHER WARRANTY OF ANY KIND,WHETHER EXPRESS,IMPLIED OR,
* STATUTORY AND DISCLAIMS ANY AND ALL IMPLIED WARRANTIES OF MERCHANTABILITY,
* SATISFACTORY QUALITY, NON INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE.
*
* THE SOURCE CODE AND DOCUMENTATION MAY INCLUDE ERRORS. INFINEON TECHNOLOGIES
* RESERVES THE RIGHT TO INCORPORATE MODIFICATIONS TO THE SOURCE CODE IN LATER
* REVISIONS OF IT, AND TO MAKE IMPROVEMENTS OR CHANGES IN THE DOCUMENTATION OR
* THE PRODUCTS OR TECHNOLOGIES DESCRIBED THEREIN AT ANY TIME.
*
* INFINEON TECHNOLOGIES SHALL NOT BE LIABLE FOR ANY DIRECT, INDIRECT OR
* CONSEQUENTIAL DAMAGE OR LIABILITY ARISING FROM YOUR USE OF THE SOURCE CODE OR
* ANY DOCUMENTATION, INCLUDING BUT NOT LIMITED TO, LOST REVENUES, DATA OR
* PROFITS, DAMAGES OF ANY SPECIAL, INCIDENTAL OR CONSEQUENTIAL NATURE, PUNITIVE
* DAMAGES, LOSS OF PROPERTY OR LOSS OF PROFITS ARISING OUT OF OR IN CONNECTION
* WITH THIS AGREEMENT, OR BEING UNUSABLE, EVEN IF ADVISED OF THE POSSIBILITY OR
* PROBABILITY OF SUCH DAMAGES AND WHETHER A CLAIM FOR SUCH DAMAGE IS BASED UPON
* WARRANTY, CONTRACT, TORT, NEGLIGENCE OR OTHERWISE.
*
* (C)Copyright INFINEON TECHNOLOGIES All rights reserved
*/
package com.infineon.esim.lpa.euicc.usbreader.identive;
final public class IdentiveUSBReaderInterface implements USBReaderInterface {
private static final String TAG = IdentiveUSBReaderInterface.class.getName();
public static final List<String> READER_NAMES = new ArrayList<>(Arrays.asList(
"SCR3500 A Contact Reader",
"Identive CLOUD 4700 F Dual Interface Reader",
"Identiv uTrust 4701 F Dual Interface Reader",
"CLOUD 2700 R Smart Card Reader"
));
private final IdentiveService identiveService;
private final List<String> euiccNames;
| /*
* THE SOURCE CODE AND ITS RELATED DOCUMENTATION IS PROVIDED "AS IS". INFINEON
* TECHNOLOGIES MAKES NO OTHER WARRANTY OF ANY KIND,WHETHER EXPRESS,IMPLIED OR,
* STATUTORY AND DISCLAIMS ANY AND ALL IMPLIED WARRANTIES OF MERCHANTABILITY,
* SATISFACTORY QUALITY, NON INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE.
*
* THE SOURCE CODE AND DOCUMENTATION MAY INCLUDE ERRORS. INFINEON TECHNOLOGIES
* RESERVES THE RIGHT TO INCORPORATE MODIFICATIONS TO THE SOURCE CODE IN LATER
* REVISIONS OF IT, AND TO MAKE IMPROVEMENTS OR CHANGES IN THE DOCUMENTATION OR
* THE PRODUCTS OR TECHNOLOGIES DESCRIBED THEREIN AT ANY TIME.
*
* INFINEON TECHNOLOGIES SHALL NOT BE LIABLE FOR ANY DIRECT, INDIRECT OR
* CONSEQUENTIAL DAMAGE OR LIABILITY ARISING FROM YOUR USE OF THE SOURCE CODE OR
* ANY DOCUMENTATION, INCLUDING BUT NOT LIMITED TO, LOST REVENUES, DATA OR
* PROFITS, DAMAGES OF ANY SPECIAL, INCIDENTAL OR CONSEQUENTIAL NATURE, PUNITIVE
* DAMAGES, LOSS OF PROPERTY OR LOSS OF PROFITS ARISING OUT OF OR IN CONNECTION
* WITH THIS AGREEMENT, OR BEING UNUSABLE, EVEN IF ADVISED OF THE POSSIBILITY OR
* PROBABILITY OF SUCH DAMAGES AND WHETHER A CLAIM FOR SUCH DAMAGE IS BASED UPON
* WARRANTY, CONTRACT, TORT, NEGLIGENCE OR OTHERWISE.
*
* (C)Copyright INFINEON TECHNOLOGIES All rights reserved
*/
package com.infineon.esim.lpa.euicc.usbreader.identive;
final public class IdentiveUSBReaderInterface implements USBReaderInterface {
private static final String TAG = IdentiveUSBReaderInterface.class.getName();
public static final List<String> READER_NAMES = new ArrayList<>(Arrays.asList(
"SCR3500 A Contact Reader",
"Identive CLOUD 4700 F Dual Interface Reader",
"Identiv uTrust 4701 F Dual Interface Reader",
"CLOUD 2700 R Smart Card Reader"
));
private final IdentiveService identiveService;
private final List<String> euiccNames;
| private EuiccConnection euiccConnection; | 0 | 2023-11-06 02:41:13+00:00 | 4k |
Teleight/TeleightBots | demo/src/main/java/org/teleight/teleightbots/demo/MainDemo.java | [
{
"identifier": "TeleightBots",
"path": "src/main/java/org/teleight/teleightbots/TeleightBots.java",
"snippet": "public final class TeleightBots {\n\n private static TeleightBotsProcess teleightBotsProcess;\n\n public static @NotNull TeleightBots init() {\n updateProcess();\n return new TeleightBots();\n }\n\n @ApiStatus.Internal\n public static TeleightBotsProcess updateProcess() {\n TeleightBotsProcess process = new TeleightBotsProcessImpl();\n teleightBotsProcess = process;\n return process;\n }\n\n public static void stopCleanly() {\n teleightBotsProcess.close();\n }\n\n public static @NotNull Scheduler getScheduler() {\n return teleightBotsProcess.scheduler();\n }\n\n public static @NotNull BotManager getBotManager() {\n return teleightBotsProcess.botManager();\n }\n\n public static @NotNull ExceptionManager getExceptionManager() {\n return teleightBotsProcess.exceptionManager();\n }\n\n public void start() {\n teleightBotsProcess.start();\n }\n\n}"
},
{
"identifier": "ParseMode",
"path": "src/main/java/org/teleight/teleightbots/api/utils/ParseMode.java",
"snippet": "public enum ParseMode {\n\n MARKDOWN(\"Markdown\"),\n MARKDOWNV2(\"MarkdownV2\"),\n HTML(\"html\");\n\n private final String fieldValue;\n\n ParseMode(String fieldValue) {\n this.fieldValue = fieldValue;\n }\n\n public String getFieldValue() {\n return fieldValue;\n }\n\n}"
},
{
"identifier": "BotSettings",
"path": "src/main/java/org/teleight/teleightbots/bot/BotSettings.java",
"snippet": "public interface BotSettings {\n\n BotSettings DEFAULT = BotSettings.of(\"https://api.telegram.org/bot\");\n\n static @NotNull BotSettings of(@NotNull String endPointUrl) {\n return of(endPointUrl, 100);\n }\n\n static @NotNull BotSettings of(@NotNull String endPointUrl, int updatesLimit) {\n return of(endPointUrl, updatesLimit, 50);\n }\n\n static @NotNull BotSettings of(@NotNull String endPointUrl, int updatesLimit, int updatesTimeout) {\n return BotSettingsImpl.create(endPointUrl, updatesLimit, updatesTimeout);\n }\n\n static @NotNull Builder builder(@NotNull String endPointUrl) {\n return new BotSettingsImpl.Builder(endPointUrl);\n }\n\n\n String endpointUrl();\n\n int updatesLimit();\n\n int updatesTimeout();\n\n\n interface Builder {\n @NotNull Builder endpointUrl(@NotNull String url);\n\n @NotNull Builder updatesLimit(int limit);\n\n @NotNull Builder updatesTimeout(int timeout);\n\n @NotNull BotSettings build();\n }\n\n}"
},
{
"identifier": "Test2Command",
"path": "demo/src/main/java/org/teleight/teleightbots/demo/command/Test2Command.java",
"snippet": "public class Test2Command extends Command {\n public Test2Command() {\n super(\"test2\");\n\n setDefaultExecutor((sender, context) -> {\n String input = context.getInput();\n\n System.out.println(\"test2 command executed: from: \" + sender.username() + \", input: \" + input);\n\n if (context.bot().getConversationManager().isUserInConversation(sender, \"test\")) {\n System.out.println(\"User is already in conversation\");\n return;\n }\n\n context.bot().getConversationManager().joinConversation(sender, context.message().chat(), \"test\");\n });\n }\n}"
},
{
"identifier": "TestCommand",
"path": "demo/src/main/java/org/teleight/teleightbots/demo/command/TestCommand.java",
"snippet": "public class TestCommand extends Command {\n\n public TestCommand() {\n super(\"test\", \"test1\");\n\n\n setDefaultExecutor((sender, context) -> {\n String input = context.getInput();\n\n System.out.println(\"test command executed: from: \" + sender.username() + \", input: \" + input);\n });\n\n\n ArgumentInteger argumentInteger = new ArgumentInteger(\"int1\");\n ArgumentInteger argumentInteger2 = new ArgumentInteger(\"int2\");\n ArgumentString argumentString1 = new ArgumentString(\"string1\");\n\n addSyntax((sender, context) -> {\n int value = context.getArgument(argumentInteger);\n int value2 = context.getArgument(argumentInteger2);\n System.out.println(\"syntax 1: first: \" + value + \", second: \" + value2);\n }, argumentInteger, argumentInteger2);\n\n addSyntax((sender, context) -> {\n int value = context.getArgument(argumentInteger);\n String value2 = context.getArgument(argumentString1);\n System.out.println(\"syntax 2: first: \" + value + \", second: \" + value2);\n }, argumentInteger, argumentString1);\n\n\n addSyntax((sender, context) -> {\n int value = context.getArgument(argumentInteger);\n System.out.println(\"syntax 3: value: \" + value);\n }, argumentInteger);\n }\n\n}"
},
{
"identifier": "EventListener",
"path": "src/main/java/org/teleight/teleightbots/event/EventListener.java",
"snippet": "public sealed interface EventListener<T extends Event> permits EventListenerImpl {\n\n static <T extends Event> Builder<T> builder(@NotNull Class<T> eventType) {\n return new EventListenerImpl.BuilderImpl<>(eventType);\n }\n\n static <T extends Event> EventListener<T> of(@NotNull Class<T> eventType, @NotNull Consumer<T> listener) {\n return builder(eventType).handler(listener).build();\n }\n\n @NotNull Class<T> eventType();\n\n @NotNull Result run(@NotNull T event);\n\n enum Result {\n SUCCESS,\n CANCELLED,\n EXPIRED,\n EXCEPTION\n }\n\n sealed interface Builder<T extends Event> permits EventListenerImpl.BuilderImpl {\n @NotNull Builder<T> filter(@NotNull Predicate<T> filter);\n\n @NotNull Builder<T> ignoreCancelled(boolean ignoreCancelled);\n\n @NotNull Builder<T> handler(@NotNull Consumer<T> handler);\n\n @NotNull Builder<T> expireCount(int expireCount);\n\n @NotNull EventListener<T> build();\n }\n\n}"
},
{
"identifier": "Menu",
"path": "src/main/java/org/teleight/teleightbots/menu/Menu.java",
"snippet": "public interface Menu {\n\n int getMenuId();\n\n @Nullable String getMenuName();\n\n @Nullable String getText();\n\n @NotNull Menu setText(@NotNull String text);\n\n @NotNull Menu addRow(@NotNull MenuButton... buttons);\n\n @NotNull Menu addRow(@NotNull List<MenuButton> buttons);\n\n @NotNull InlineKeyboardMarkup getKeyboard();\n\n @FunctionalInterface\n interface Builder {\n void create(@NotNull MenuBuilder context, @NotNull Menu rootMenu);\n }\n\n}"
}
] | import org.teleight.teleightbots.TeleightBots;
import org.teleight.teleightbots.api.methods.SendMessage;
import org.teleight.teleightbots.api.utils.ParseMode;
import org.teleight.teleightbots.bot.BotSettings;
import org.teleight.teleightbots.demo.command.Test2Command;
import org.teleight.teleightbots.demo.command.TestCommand;
import org.teleight.teleightbots.event.EventListener;
import org.teleight.teleightbots.event.bot.UpdateReceivedEvent;
import org.teleight.teleightbots.menu.Menu;
import org.teleight.teleightbots.menu.MenuButton;
import java.util.concurrent.TimeUnit; | 2,283 | package org.teleight.teleightbots.demo;
public class MainDemo {
public static void main(String[] args) {
final TeleightBots teleightBots = TeleightBots.init();
teleightBots.start();
final String botToken = System.getenv("bot.token") != null ? System.getenv("bot.token") : "--INSERT-TOKEN-HERE--";
final String botUsername = System.getenv("bot.username") != null ? System.getenv("bot.username") : "--INSERT-USERNAME--HERE";
final String chatId = System.getenv("bot.default_chatid") != null ? System.getenv("bot.default_chatid") : "--INSERT-CHATID--HERE";
final EventListener<UpdateReceivedEvent> updateEvent = EventListener.builder(UpdateReceivedEvent.class)
.handler(event -> System.out.println("UpdateReceivedEvent: " + event.bot().getBotUsername() + " -> " + event))
.build();
TeleightBots.getBotManager().registerLongPolling(botToken, botUsername, BotSettings.DEFAULT, bot -> {
System.out.println("Bot registered: " + bot.getBotUsername());
//Listener
bot.getEventManager().addListener(updateEvent);
//Commands
bot.getCommandManager().registerCommand(new TestCommand());
Menu menu = bot.createMenu((context, rootMenu) -> {
Menu subMenu2 = context.createMenu("subMenu2");
Menu subMenu3 = context.createMenu("subMenu3");
rootMenu.setText("Root menu");
subMenu2.setText("SubMenu 2");
subMenu3.setText("SubMenu 3");
MenuButton button1_1 = MenuButton.builder().text("menu 1 - button 1").destinationMenu(subMenu2).build();
MenuButton button2_1 = MenuButton.builder().text("menu 2 - button 1").build();
MenuButton button2_2 = MenuButton.builder().text("menu 2 - button 2").destinationMenu(rootMenu).build();
MenuButton button2_3 = MenuButton.builder().text("menu 2 - button 3").destinationMenu(subMenu3).build();
MenuButton button3_1 = MenuButton.builder().text("menu 3 - button 4").destinationMenu(subMenu2).build();
rootMenu.addRow(button1_1);
subMenu2.addRow(button2_1, button2_2)
.addRow(button2_3);
subMenu3.addRow(button3_1);
});
SendMessage sendMessage = SendMessage.builder()
.text("<b>Test message</b>")
.chatId(chatId)
.replyMarkup(menu.getKeyboard()) | package org.teleight.teleightbots.demo;
public class MainDemo {
public static void main(String[] args) {
final TeleightBots teleightBots = TeleightBots.init();
teleightBots.start();
final String botToken = System.getenv("bot.token") != null ? System.getenv("bot.token") : "--INSERT-TOKEN-HERE--";
final String botUsername = System.getenv("bot.username") != null ? System.getenv("bot.username") : "--INSERT-USERNAME--HERE";
final String chatId = System.getenv("bot.default_chatid") != null ? System.getenv("bot.default_chatid") : "--INSERT-CHATID--HERE";
final EventListener<UpdateReceivedEvent> updateEvent = EventListener.builder(UpdateReceivedEvent.class)
.handler(event -> System.out.println("UpdateReceivedEvent: " + event.bot().getBotUsername() + " -> " + event))
.build();
TeleightBots.getBotManager().registerLongPolling(botToken, botUsername, BotSettings.DEFAULT, bot -> {
System.out.println("Bot registered: " + bot.getBotUsername());
//Listener
bot.getEventManager().addListener(updateEvent);
//Commands
bot.getCommandManager().registerCommand(new TestCommand());
Menu menu = bot.createMenu((context, rootMenu) -> {
Menu subMenu2 = context.createMenu("subMenu2");
Menu subMenu3 = context.createMenu("subMenu3");
rootMenu.setText("Root menu");
subMenu2.setText("SubMenu 2");
subMenu3.setText("SubMenu 3");
MenuButton button1_1 = MenuButton.builder().text("menu 1 - button 1").destinationMenu(subMenu2).build();
MenuButton button2_1 = MenuButton.builder().text("menu 2 - button 1").build();
MenuButton button2_2 = MenuButton.builder().text("menu 2 - button 2").destinationMenu(rootMenu).build();
MenuButton button2_3 = MenuButton.builder().text("menu 2 - button 3").destinationMenu(subMenu3).build();
MenuButton button3_1 = MenuButton.builder().text("menu 3 - button 4").destinationMenu(subMenu2).build();
rootMenu.addRow(button1_1);
subMenu2.addRow(button2_1, button2_2)
.addRow(button2_3);
subMenu3.addRow(button3_1);
});
SendMessage sendMessage = SendMessage.builder()
.text("<b>Test message</b>")
.chatId(chatId)
.replyMarkup(menu.getKeyboard()) | .parseMode(ParseMode.HTML) | 1 | 2023-11-04 16:55:27+00:00 | 4k |
DJ-Raven/swing-glasspane-popup | src/test/java/test/TestSampleMessage.java | [
{
"identifier": "Drawer",
"path": "src/main/java/raven/drawer/Drawer.java",
"snippet": "public class Drawer {\n\n private static Drawer instance;\n private DrawerPanel drawerPanel;\n private DrawerOption option;\n\n public static Drawer getInstance() {\n if (instance == null) {\n instance = new Drawer();\n }\n return instance;\n }\n\n public static Drawer newInstance() {\n return new Drawer();\n }\n\n private Drawer() {\n }\n\n public void setDrawerBuilder(DrawerBuilder drawerBuilder) {\n drawerPanel = new DrawerPanel(drawerBuilder);\n option = new DrawerOption(drawerBuilder.getDrawerWidth());\n drawerBuilder.build(drawerPanel);\n }\n\n public void showDrawer() {\n if (drawerPanel == null) {\n throw new NullPointerException(\"Drawer builder has not initialize\");\n }\n if (!isShowing()) {\n GlassPanePopup.showPopup(drawerPanel, option, \"drawer\");\n }\n }\n\n public void closeDrawer() {\n GlassPanePopup.closePopup(\"drawer\");\n }\n\n public boolean isShowing() {\n return GlassPanePopup.isShowing(drawerPanel);\n }\n\n public DrawerPanel getDrawerPanel() {\n return drawerPanel;\n }\n}"
},
{
"identifier": "GlassPanePopup",
"path": "src/main/java/raven/popup/GlassPanePopup.java",
"snippet": "public class GlassPanePopup {\n\n private static GlassPanePopup instance;\n private JFrame mainFrame;\n protected WindowSnapshots windowSnapshots;\n protected JLayeredPane layerPane;\n protected Container contentPane;\n protected Option defaultOption;\n\n private GlassPanePopup() {\n init();\n }\n\n private void init() {\n layerPane = new JLayeredPane();\n layerPane.setLayout(new CardLayout());\n }\n\n protected void addAndShowPopup(GlassPaneChild component, Option option, String name) {\n GlassPopup popup = new GlassPopup(this, component, option);\n instance.layerPane.applyComponentOrientation(instance.contentPane.getComponentOrientation());\n popup.applyComponentOrientation(instance.contentPane.getComponentOrientation());\n if (name != null) {\n popup.setName(name);\n }\n layerPane.setLayer(popup, JLayeredPane.DRAG_LAYER);\n layerPane.add(popup, 0);\n popup.setVisible(true);\n popup.setShowPopup(true);\n if (!layerPane.isVisible()) {\n layerPane.setVisible(true);\n }\n layerPane.grabFocus();\n }\n\n private void updateLayout() {\n for (Component com : layerPane.getComponents()) {\n com.revalidate();\n }\n }\n\n public static void install(JFrame frame) {\n instance = new GlassPanePopup();\n instance.mainFrame = frame;\n instance.windowSnapshots = new WindowSnapshots(frame);\n instance.contentPane = frame.getContentPane();\n frame.setGlassPane(instance.layerPane);\n frame.addWindowStateListener(new WindowAdapter() {\n @Override\n public void windowStateChanged(WindowEvent e) {\n SwingUtilities.invokeLater(() -> {\n instance.updateLayout();\n });\n }\n });\n }\n\n public static void setDefaultOption(Option option) {\n instance.defaultOption = option;\n }\n\n public static void showPopup(GlassPaneChild component, Option option, String name) {\n if (component.getMouseListeners().length == 0) {\n component.addMouseListener(new MouseAdapter() {\n });\n }\n instance.addAndShowPopup(component, option, name);\n }\n\n public static void showPopup(GlassPaneChild component, Option option) {\n showPopup(component, option, null);\n }\n\n public static void showPopup(GlassPaneChild component, String name) {\n Option option = instance.defaultOption == null ? new DefaultOption() : instance.defaultOption;\n showPopup(component, option, name);\n }\n\n public static void showPopup(GlassPaneChild component) {\n showPopup(component, new DefaultOption(), null);\n }\n\n public static void push(GlassPaneChild component, String name) {\n for (Component com : instance.layerPane.getComponents()) {\n if (com.getName() != null && com.getName().equals(name)) {\n if (com instanceof GlassPopup) {\n GlassPopup popup = (GlassPopup) com;\n popup.getComponentLayer().pushComponent(component);\n break;\n }\n }\n }\n }\n\n public static void pop(String name) {\n for (Component com : instance.layerPane.getComponents()) {\n if (com.getName() != null && com.getName().equals(name)) {\n if (com instanceof GlassPopup) {\n GlassPopup popup = (GlassPopup) com;\n popup.getComponentLayer().popComponent();\n break;\n }\n }\n }\n }\n\n public static void pop(Component component) {\n for (Component com : instance.layerPane.getComponents()) {\n if (com instanceof GlassPopup) {\n GlassPopup popup = (GlassPopup) com;\n if (popup.getComponent() == component) {\n popup.getComponentLayer().popComponent();\n }\n }\n }\n }\n\n public static void closePopup(int index) {\n index = instance.layerPane.getComponentCount() - 1 - index;\n if (index >= 0 && index < instance.layerPane.getComponentCount()) {\n if (instance.layerPane.getComponent(index) instanceof GlassPopup) {\n GlassPopup popup = (GlassPopup) instance.layerPane.getComponent(index);\n popup.setShowPopup(false);\n }\n }\n }\n\n public static void closePopup(String name) {\n for (Component com : instance.layerPane.getComponents()) {\n if (com.getName() != null && com.getName().equals(name)) {\n if (com instanceof GlassPopup) {\n GlassPopup popup = (GlassPopup) com;\n popup.setShowPopup(false);\n }\n }\n }\n }\n\n public static void closePopup(Component component) {\n for (Component com : instance.layerPane.getComponents()) {\n if (com instanceof GlassPopup) {\n GlassPopup popup = (GlassPopup) com;\n if (popup.getComponent() == component) {\n popup.setShowPopup(false);\n }\n }\n }\n }\n\n public static void closePopupLast() {\n closePopup(getPopupCount() - 1);\n }\n\n public static void closePopupAll() {\n for (Component com : instance.layerPane.getComponents()) {\n if (com instanceof GlassPopup) {\n GlassPopup popup = (GlassPopup) com;\n popup.setShowPopup(false);\n }\n }\n }\n\n public static boolean isShowing(String name) {\n boolean act = false;\n for (Component com : instance.layerPane.getComponents()) {\n if (com.getName() != null && com.getName().equals(name)) {\n act = true;\n break;\n }\n }\n return act;\n }\n\n public static boolean isShowing(Component component) {\n boolean act = false;\n for (Component com : instance.layerPane.getComponents()) {\n if (com instanceof GlassPopup) {\n GlassPopup popup = (GlassPopup) com;\n if (popup.getComponent() == component) {\n act = true;\n break;\n }\n }\n }\n return act;\n }\n\n public static int getPopupCount() {\n return instance.layerPane.getComponentCount();\n }\n\n public static JFrame getMainFrame() {\n return instance.mainFrame;\n }\n\n public static boolean isInit() {\n return !(instance == null || instance.mainFrame == null);\n }\n\n protected synchronized void removePopup(Component popup) {\n layerPane.remove(popup);\n if (layerPane.getComponentCount() == 0) {\n layerPane.setVisible(false);\n }\n }\n}"
},
{
"identifier": "SimplePopupBorder",
"path": "src/main/java/raven/popup/component/SimplePopupBorder.java",
"snippet": "public class SimplePopupBorder extends GlassPaneChild {\n\n private final Component component;\n private JPanel panelTitle;\n private final String title;\n private final String[] action;\n private SimplePopupBorderOption option;\n\n public SimplePopupBorder(Component component, String title, SimplePopupBorderOption option) {\n this(component, title, option, null, null);\n }\n\n public SimplePopupBorder(Component component, String title) {\n this(component, title, null, null);\n }\n\n public SimplePopupBorder(Component component, String title, String[] action, PopupCallbackAction callbackAction) {\n this(component, title, new SimplePopupBorderOption(), action, callbackAction);\n }\n\n public SimplePopupBorder(Component component, String title, SimplePopupBorderOption option, String[] action, PopupCallbackAction callbackAction) {\n this.component = component;\n this.title = title;\n this.option = option;\n this.action = action;\n this.callbackAction = callbackAction;\n if (component instanceof GlassPaneChild) {\n ((GlassPaneChild) component).callbackAction = callbackAction;\n }\n init();\n }\n\n private void init() {\n setLayout(new MigLayout(\"wrap,fillx,insets 15 0 15 0\", \"[fill,\" + option.width + \"]\"));\n panelTitle = new JPanel(new MigLayout(\"insets 2 25 2 25,fill\"));\n if (title != null) {\n panelTitle.add(createTitle(title), \"push\");\n }\n panelTitle.add(createCloseButton(), \"trailing\");\n add(panelTitle);\n if (option.useScroll) {\n JScrollPane scrollPane = new JScrollPane(component);\n scrollPane.setBorder(BorderFactory.createEmptyBorder());\n applyScrollStyle(scrollPane.getVerticalScrollBar());\n applyScrollStyle(scrollPane.getHorizontalScrollBar());\n add(scrollPane);\n } else {\n add(component);\n }\n if (action != null) {\n add(createActionButton(action, callbackAction));\n }\n }\n\n private void applyScrollStyle(JScrollBar scrollBar) {\n scrollBar.setUnitIncrement(10);\n scrollBar.putClientProperty(FlatClientProperties.STYLE, \"\" +\n \"width:10;\" +\n \"trackArc:999;\" +\n \"thumbInsets:0,3,0,3;\" +\n \"trackInsets:0,3,0,3;\");\n }\n\n protected Component createTitle(String title) {\n JLabel lbTitle = new JLabel(title);\n lbTitle.putClientProperty(FlatClientProperties.STYLE, \"\" +\n \"font:+4\");\n return lbTitle;\n }\n\n protected void addBackButton() {\n panelTitle.add(createBackButton(), 0);\n }\n\n protected Component createCloseButton() {\n JButton cmdClose = new JButton(new FlatSVGIcon(\"raven/popup/icon/close.svg\", 0.8f));\n cmdClose.putClientProperty(FlatClientProperties.STYLE, \"\" +\n \"arc:999;\" +\n \"borderWidth:0;\" +\n \"focusWidth:0;\" +\n \"innerFocusWidth:0;\" +\n \"background:null\");\n applyCloseButtonEvent(cmdClose);\n return cmdClose;\n }\n\n protected Component createBackButton() {\n JButton cmdBack = new JButton(new FlatSVGIcon(\"raven/popup/icon/back.svg\", 0.8f));\n cmdBack.putClientProperty(FlatClientProperties.STYLE, \"\" +\n \"arc:999;\" +\n \"borderWidth:0;\" +\n \"focusWidth:0;\" +\n \"innerFocusWidth:0;\" +\n \"background:null\");\n applyBackButtonEvent(cmdBack);\n return cmdBack;\n }\n\n protected void applyCloseButtonEvent(JButton button) {\n button.addActionListener(e -> {\n if (callbackAction == null) {\n GlassPanePopup.closePopup(this);\n return;\n }\n PopupController action = createController();\n callbackAction.action(action, PopupCallbackAction.CLOSE);\n if (!action.getConsume()) {\n GlassPanePopup.closePopup(this);\n }\n });\n }\n\n protected void applyBackButtonEvent(JButton button) {\n button.addActionListener(e -> {\n GlassPanePopup.pop(this);\n });\n }\n\n protected Component createActionButton(String[] action, PopupCallbackAction callbackAction) {\n JPanel panel = new JPanel(new MigLayout(\"insets 2 25 2 25,trailing\"));\n for (int i = 0; i < action.length; i++) {\n panel.add(getActionButton(action[i], i, callbackAction));\n }\n return panel;\n }\n\n private JButton getActionButton(String name, int index, PopupCallbackAction callbackAction) {\n JButton button = new JButton(name);\n button.setFocusable(false);\n button.addActionListener(e -> {\n callbackAction.action(createController(), index);\n });\n button.putClientProperty(FlatClientProperties.STYLE, \"\" +\n \"borderWidth:0;\" +\n \"focusWidth:0;\" +\n \"innerFocusWidth:0;\" +\n \"background:null;\" +\n \"font:+1\");\n return button;\n }\n\n @Override\n public void onPush() {\n addBackButton();\n }\n\n @Override\n public int getRoundBorder() {\n return option.roundBorder;\n }\n}"
},
{
"identifier": "SimplePopupBorderOption",
"path": "src/main/java/raven/popup/component/SimplePopupBorderOption.java",
"snippet": "public class SimplePopupBorderOption {\n\n protected boolean useScroll;\n protected int width = 400;\n\n protected int roundBorder = 20;\n\n public SimplePopupBorderOption useScroll() {\n useScroll = true;\n return this;\n }\n\n public SimplePopupBorderOption setWidth(int width) {\n this.width = width;\n return this;\n }\n\n public SimplePopupBorderOption setRoundBorder(int roundBorder) {\n this.roundBorder = roundBorder;\n return this;\n }\n}"
}
] | import com.formdev.flatlaf.FlatClientProperties;
import com.formdev.flatlaf.FlatLaf;
import com.formdev.flatlaf.fonts.roboto.FlatRobotoFont;
import com.formdev.flatlaf.themes.FlatMacDarkLaf;
import net.miginfocom.swing.MigLayout;
import raven.drawer.Drawer;
import raven.popup.GlassPanePopup;
import raven.popup.component.SimplePopupBorder;
import raven.popup.component.SimplePopupBorderOption;
import javax.swing.*;
import java.awt.*; | 3,416 | package test;
public class TestSampleMessage extends JFrame {
public TestSampleMessage() { | package test;
public class TestSampleMessage extends JFrame {
public TestSampleMessage() { | GlassPanePopup.install(this); | 1 | 2023-11-08 14:06:16+00:00 | 4k |
CxyJerry/pilipala | src/main/java/com/jerry/pilipala/domain/user/service/impl/FansServiceImpl.java | [
{
"identifier": "UserVO",
"path": "src/main/java/com/jerry/pilipala/application/vo/user/UserVO.java",
"snippet": "@Data\n@EqualsAndHashCode(callSuper = true)\n@Accessors(chain = true)\npublic class UserVO extends PreviewUserVO {\n private int fansCount = 0;\n private int followCount = 0;\n}"
},
{
"identifier": "UserEntity",
"path": "src/main/java/com/jerry/pilipala/domain/user/entity/neo4j/UserEntity.java",
"snippet": "@Data\n@Node(\"user\")\n@Accessors(chain = true)\npublic class UserEntity {\n @Id\n private String uid = \"\";\n private String tel = \"\";\n private String email = \"\";\n private Long ctime = System.currentTimeMillis();\n @Relationship(\"Followed\")\n private List<UserEntity> followUps = new ArrayList<>();\n}"
},
{
"identifier": "UserEntityRepository",
"path": "src/main/java/com/jerry/pilipala/domain/user/repository/UserEntityRepository.java",
"snippet": "public interface UserEntityRepository extends Neo4jRepository<UserEntity, String> {\n UserEntity findUserEntityByTel(String tel);\n\n /**\n * 获取粉丝数据\n *\n * @param uid 用户ID\n * @return list\n */\n @Query(\"MATCH (follower:`user`)-[:Followed]->(user:`user` {uid: $uid}) RETURN follower\")\n List<UserEntity> findFollowersByUserId(String uid);\n\n /**\n * 获取粉丝数据\n *\n * @param uid 用户ID\n * @return list\n */\n @Query(\"MATCH (follower:`user`)-[:Followed]->(user:`user` {uid: $uid}) RETURN follower SKIP $skip LIMIT $limit\")\n List<UserEntity> findFollowersByUserId(String uid, int skip, int limit);\n\n /**\n * 获取粉丝数量\n *\n * @param uid 用户ID\n * @return count\n */\n @Query(\"MATCH (follower:`user`)-[:Followed]->(user:`user` {uid: $uid}) RETURN COUNT(follower)\")\n int countFollowersByUserId(String uid);\n\n\n /**\n * 获取我关注的 up\n *\n * @param userId 用户ID\n * @return up\n */\n @Query(\"MATCH (user:`user` {uid: $userId})-[:Followed]->(followed:`user`) RETURN followed SKIP $skip LIMIT $limit\")\n List<UserEntity> getFollowedUsers(@Param(\"userId\") String userId, @Param((\"skip\")) int skip, @Param(\"limit\") int limit);\n\n /**\n * 获取我关注的 up 数量\n *\n * @param userId 用户ID\n * @return count\n */\n @Query(\"MATCH (user:`user` {uid: $userId})-[:Followed]->(followed:`user`) RETURN COUNT(followed)\")\n int getFollowedUsersCount(@Param(\"userId\") String userId);\n\n @Query(\"MATCH (u:`user` {uid: $userId})-[r:Followed]->(f:`user` {uid: $followedUserId}) DELETE r\")\n void removeFollowUpRelation(@Param(\"userId\") String userId, @Param(\"followedUserId\") String followedUserId);\n}"
},
{
"identifier": "FansService",
"path": "src/main/java/com/jerry/pilipala/domain/user/service/FansService.java",
"snippet": "public interface FansService {\n UserVO put(String upUid);\n\n List<UserVO> idles();\n\n}"
},
{
"identifier": "UserService",
"path": "src/main/java/com/jerry/pilipala/domain/user/service/UserService.java",
"snippet": "public interface UserService {\n UserVO login(LoginDTO loginDTO);\n\n void code(String tel);\n\n UserVO userVO(String uid, boolean forceQuery);\n\n List<UserVO> userVoList(Collection<String> uidSet);\n\n Page<UserVO> page(Integer pageNo, Integer pageSize);\n\n void emailCode(String email);\n\n UserVO emailLogin(EmailLoginDTO loginDTO);\n}"
},
{
"identifier": "BusinessException",
"path": "src/main/java/com/jerry/pilipala/infrastructure/common/errors/BusinessException.java",
"snippet": "@Data\n@EqualsAndHashCode(callSuper = true)\npublic class BusinessException extends RuntimeException implements IResponse {\n private final int code;\n private final String message;\n private final IResponse response;\n\n public BusinessException(IResponse response) {\n this(\"\", response, null);\n }\n\n public BusinessException(String message, IResponse response) {\n this(message, response, null);\n }\n\n public BusinessException(String message, IResponse response, Object[] args) {\n super(message == null ? response.getMessage() : message);\n this.code = response.getCode();\n this.response = response;\n this.message = MessageFormat.format(super.getMessage(), args);\n }\n\n\n @Override\n public int getCode() {\n return code;\n }\n\n @Override\n public String getMessage() {\n return message;\n }\n\n public static BusinessException businessError(String message) {\n return new BusinessException(message, StandardResponse.ERROR);\n }\n}"
},
{
"identifier": "StandardResponse",
"path": "src/main/java/com/jerry/pilipala/infrastructure/common/response/StandardResponse.java",
"snippet": "public enum StandardResponse implements IResponse {\n OK(200, \"success\"),\n BAD_REQUEST(400, \"Bad Request\"),\n FORBIDDEN(403, \"Access Denied\"),\n NOT_FOUND(404, \"Not Found\"),\n ERROR(500, \"Business Error\");\n private final int code;\n private final String message;\n\n StandardResponse(int code, String message) {\n this.code = code;\n this.message = message;\n }\n\n\n @Override\n public int getCode() {\n return code;\n }\n\n @Override\n public String getMessage() {\n return message;\n }\n}"
}
] | import cn.dev33.satoken.stp.StpUtil;
import com.jerry.pilipala.application.vo.user.UserVO;
import com.jerry.pilipala.domain.user.entity.neo4j.UserEntity;
import com.jerry.pilipala.domain.user.repository.UserEntityRepository;
import com.jerry.pilipala.domain.user.service.FansService;
import com.jerry.pilipala.domain.user.service.UserService;
import com.jerry.pilipala.infrastructure.common.errors.BusinessException;
import com.jerry.pilipala.infrastructure.common.response.StandardResponse;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors; | 1,630 | package com.jerry.pilipala.domain.user.service.impl;
@Service
public class FansServiceImpl implements FansService {
private final UserService userService;
private final UserEntityRepository userEntityRepository;
public FansServiceImpl(UserService userService,
UserEntityRepository userEntityRepository) {
this.userService = userService;
this.userEntityRepository = userEntityRepository;
}
@Override
public UserVO put(String upUid) {
String myUid = (String) StpUtil.getLoginId();
if (upUid.equals(myUid)) { | package com.jerry.pilipala.domain.user.service.impl;
@Service
public class FansServiceImpl implements FansService {
private final UserService userService;
private final UserEntityRepository userEntityRepository;
public FansServiceImpl(UserService userService,
UserEntityRepository userEntityRepository) {
this.userService = userService;
this.userEntityRepository = userEntityRepository;
}
@Override
public UserVO put(String upUid) {
String myUid = (String) StpUtil.getLoginId();
if (upUid.equals(myUid)) { | throw new BusinessException("无须关注自己", StandardResponse.ERROR); | 6 | 2023-11-03 10:05:02+00:00 | 4k |
viego1999/xuecheng-plus-project | xuecheng-plus-learning/xuecheng-plus-learning-service/src/main/java/com/xuecheng/learning/service/impl/LearningServiceImpl.java | [
{
"identifier": "XueChengPlusException",
"path": "xuecheng-plus-base/src/main/java/com/xuecheng/base/exception/XueChengPlusException.java",
"snippet": "public class XueChengPlusException extends RuntimeException {\n private static final long serialVersionUID = 5565760508056698922L;\n private String errMessage;\n\n public XueChengPlusException() {\n super();\n }\n\n public XueChengPlusException(String errMessage) {\n super(errMessage);\n this.errMessage = errMessage;\n }\n\n public String getErrMessage() {\n return errMessage;\n }\n\n public static void cast(CommonError commonError) {\n throw new XueChengPlusException(commonError.getErrMessage());\n }\n\n public static void cast(String errMessage) {\n throw new XueChengPlusException(errMessage);\n }\n}"
},
{
"identifier": "RestResponse",
"path": "xuecheng-plus-base/src/main/java/com/xuecheng/base/model/RestResponse.java",
"snippet": "@Data\n@ToString\npublic class RestResponse<T> {\n\n /**\n * 响应编码,0为正常,-1错误\n */\n private int code;\n\n /**\n * 响应提示信息\n */\n private String msg;\n\n /**\n * 响应内容\n */\n private T result;\n\n public RestResponse() {\n this(0, \"success\");\n }\n\n public RestResponse(int code, String msg) {\n this.code = code;\n this.msg = msg;\n }\n\n /**\n * 错误信息的封装\n *\n * @param msg 响应消息\n * @param <T> 响应结果类型\n * @return 响应结果\n */\n public static <T> RestResponse<T> validfail(String msg) {\n RestResponse<T> response = new RestResponse<T>();\n response.setCode(-1);\n response.setMsg(msg);\n return response;\n }\n\n public static <T> RestResponse<T> validfail(T result, String msg) {\n RestResponse<T> response = new RestResponse<T>();\n response.setCode(-1);\n response.setResult(result);\n response.setMsg(msg);\n return response;\n }\n\n /**\n * 添加正常响应数据(包含响应内容)\n *\n * @return RestResponse Rest服务封装相应数据\n */\n public static <T> RestResponse<T> success(T result) {\n RestResponse<T> response = new RestResponse<T>();\n response.setResult(result);\n return response;\n }\n\n public static <T> RestResponse<T> success(T result, String msg) {\n RestResponse<T> response = new RestResponse<T>();\n response.setResult(result);\n response.setMsg(msg);\n return response;\n }\n\n /**\n * 添加正常响应数据(不包含响应内容)\n *\n * @return RestResponse Rest服务封装相应数据\n */\n public static <T> RestResponse<T> success() {\n return new RestResponse<T>();\n }\n\n\n public Boolean isSuccessful() {\n return this.code == 0;\n }\n\n}"
},
{
"identifier": "TeachplanDto",
"path": "xuecheng-plus-content/xuecheng-plus-content-model/src/main/java/com/xuecheng/content/model/dto/TeachplanDto.java",
"snippet": "@EqualsAndHashCode(callSuper = true)\n@Slf4j\n@Data\npublic class TeachplanDto extends Teachplan {\n\n /**\n * 关联的媒资信息\n */\n TeachplanMedia teachplanMedia;\n\n /**\n * 子目录\n */\n List<TeachplanDto> teachPlanTreeNodes;\n\n}"
},
{
"identifier": "CoursePublish",
"path": "xuecheng-plus-content/xuecheng-plus-content-model/src/main/java/com/xuecheng/content/model/po/CoursePublish.java",
"snippet": "@Data\n@TableName(\"course_publish\")\npublic class CoursePublish implements Serializable {\n\n private static final long serialVersionUID = 1L;\n\n /**\n * 主键(课程id)\n */\n private Long id;\n\n /**\n * 机构ID\n */\n private Long companyId;\n\n /**\n * 公司名称\n */\n private String companyName;\n\n /**\n * 课程名称\n */\n private String name;\n\n /**\n * 适用人群\n */\n private String users;\n\n /**\n * 标签\n */\n private String tags;\n\n /**\n * 创建人\n */\n private String username;\n\n /**\n * 大分类\n */\n private String mt;\n\n /**\n * 大分类名称\n */\n private String mtName;\n\n /**\n * 小分类\n */\n private String st;\n\n /**\n * 小分类名称\n */\n private String stName;\n\n /**\n * 课程等级\n */\n private String grade;\n\n /**\n * 教育模式\n */\n private String teachmode;\n\n /**\n * 课程图片\n */\n private String pic;\n\n /**\n * 课程介绍\n */\n private String description;\n\n /**\n * 课程营销信息,json格式\n */\n private String market;\n\n /**\n * 所有课程计划,json格式\n */\n private String teachplan;\n\n /**\n * 教师信息,json格式\n */\n private String teachers;\n\n /**\n * 发布时间\n */\n @TableField(fill = FieldFill.INSERT)\n private LocalDateTime createDate;\n\n /**\n * 上架时间\n */\n private LocalDateTime onlineDate;\n\n /**\n * 下架时间\n */\n private LocalDateTime offlineDate;\n\n /**\n * 发布状态<p>\n * {\"203001\":\"未发布\"},{\"203002\":\"已发布\"},{\"203003\":\"下线\"}\n * </p>\n */\n private String status;\n\n /**\n * 备注\n */\n private String remark;\n\n /**\n * 收费规则,对应数据字典--203\n */\n private String charge;\n\n /**\n * 现价\n */\n private Float price;\n\n /**\n * 原价\n */\n private Float originalPrice;\n\n /**\n * 课程有效期天数\n */\n private Integer validDays;\n\n\n}"
},
{
"identifier": "ContentServiceClient",
"path": "xuecheng-plus-learning/xuecheng-plus-learning-service/src/main/java/com/xuecheng/learning/feignclient/ContentServiceClient.java",
"snippet": "@FeignClient(value = \"content-api\", fallbackFactory = ContentServiceClient.ContentServiceClientFallbackFactory.class)\npublic interface ContentServiceClient {\n\n @ResponseBody\n @GetMapping(\"/content/r/coursepublish/{courseId}\")\n CoursePublish getCoursePublish(@PathVariable(\"courseId\") Long courseId);\n\n /**\n * 内容管理服务远程接口降级类\n */\n @Slf4j\n class ContentServiceClientFallbackFactory implements FallbackFactory<ContentServiceClient> {\n\n @Override\n public ContentServiceClient create(Throwable cause) {\n log.error(\"调用内容管理服务接口熔断:{}\", cause.getMessage());\n return null;\n }\n }\n}"
},
{
"identifier": "MediaServiceClient",
"path": "xuecheng-plus-learning/xuecheng-plus-learning-service/src/main/java/com/xuecheng/learning/feignclient/MediaServiceClient.java",
"snippet": "@FeignClient(value = \"media-api\", fallbackFactory = MediaServiceClient.MediaServiceClientFallbackFactory.class)\n@RequestMapping(\"/media\")\npublic interface MediaServiceClient {\n\n @GetMapping(\"/open/preview/{mediaId}\")\n RestResponse<String> getPlayUrlByMediaId(@PathVariable(\"mediaId\") String mediaId);\n\n\n /**\n * MediaServiceClient 接口的降级类\n */\n @Slf4j\n class MediaServiceClientFallbackFactory implements FallbackFactory<MediaServiceClient> {\n\n @Override\n public MediaServiceClient create(Throwable cause) {\n log.error(\"远程调用媒资管理服务熔断异常: {}\", cause.getMessage());\n return null;\n }\n }\n}"
},
{
"identifier": "XcCourseTablesDto",
"path": "xuecheng-plus-learning/xuecheng-plus-learning-model/src/main/java/com/xuecheng/learning/model/dto/XcCourseTablesDto.java",
"snippet": "@EqualsAndHashCode(callSuper = true)\n@Data\n@ToString\npublic class XcCourseTablesDto extends XcCourseTables {\n\n /**\n * 学习资格,[{\"code\":\"702001\",\"desc\":\"正常学习\"},{\"code\":\"702002\",\"desc\":\"没有选课或选课后没有支付\"},{\"code\":\"702003\",\"desc\":\"已过期需要申请续期或重新支付\"}]\n */\n public String learnStatus;\n}"
},
{
"identifier": "LearningService",
"path": "xuecheng-plus-learning/xuecheng-plus-learning-service/src/main/java/com/xuecheng/learning/service/LearningService.java",
"snippet": "public interface LearningService {\n\n /**\n * 获取教学视频\n *\n * @param courseId 课程id\n * @param teachplanId 课程计划id\n * @param mediaId 视频文件id\n * @return {@link com.xuecheng.base.model.RestResponse}<{@link java.lang.String}>\n * @author Wuxy\n * @since 2022/10/5 9:08\n */\n RestResponse<String> getVideo(String userId, Long courseId, Long teachplanId, String mediaId);\n\n}"
},
{
"identifier": "MyCourseTablesService",
"path": "xuecheng-plus-learning/xuecheng-plus-learning-service/src/main/java/com/xuecheng/learning/service/MyCourseTablesService.java",
"snippet": "public interface MyCourseTablesService {\n\n /**\n * 添加选课\n *\n * @param userId 用户 id\n * @param courseId 课程 id\n * @return {@link com.xuecheng.learning.model.dto.XcChooseCourseDto}\n * @author Wuxy\n * @since 2022/10/24 17:33\n */\n XcChooseCourseDto addChooseCourse(String userId, Long courseId);\n\n /**\n * 添加免费课程\n *\n * @param userId 用户 id\n * @param coursePublish 课程发布信息\n * @return 选课信息\n */\n XcChooseCourse addFreeCourse(String userId, CoursePublish coursePublish);\n\n /**\n * 添加收费课程\n *\n * @param userId 用户 id\n * @param coursePublish 课程发布信息\n * @return 选课信息\n */\n XcChooseCourse addChargeCourse(String userId, CoursePublish coursePublish);\n\n /**\n * 添加到我的课程表\n *\n * @param chooseCourse 选课记录\n * @return {@link com.xuecheng.learning.model.po.XcCourseTables}\n * @author Wuxy\n * @since 2022/10/3 11:24\n */\n XcCourseTables addCourseTables(XcChooseCourse chooseCourse);\n\n /**\n * 根据课程和用户查询我的课程表中某一门课程\n *\n * @param userId 用户 id\n * @param courseId 课程 id\n * @return {@link com.xuecheng.learning.model.po.XcCourseTables}\n * @author Wuxy\n * @since 2022/10/2 17:07\n */\n XcCourseTables getXcCourseTables(String userId, Long courseId);\n\n /**\n * 判断学习资格\n * <pre>\n * 学习资格状态 [{\"code\":\"702001\",\"desc\":\"正常学习\"},\n * {\"code\":\"702002\",\"desc\":\"没有选课或选课后没有支付\"},\n * {\"code\":\"702003\",\"desc\":\"已过期需要申请续期或重新支付\"}]\n * </pre>\n *\n * @param userId 用户 id\n * @param courseId 课程 id\n * @return {@link XcCourseTablesDto}\n * @author Wuxy\n * @since 2022/10/3 7:37\n */\n XcCourseTablesDto getLearningStatus(String userId, Long courseId);\n\n boolean saveChooseCourseStatus(String chooseCourseId);\n\n PageResult<MyCourseTableItemDto> myCourseTables(MyCourseTableParams params);\n\n}"
}
] | import com.alibaba.fastjson.JSON;
import com.xuecheng.base.exception.XueChengPlusException;
import com.xuecheng.base.model.RestResponse;
import com.xuecheng.content.model.dto.TeachplanDto;
import com.xuecheng.content.model.po.CoursePublish;
import com.xuecheng.learning.feignclient.ContentServiceClient;
import com.xuecheng.learning.feignclient.MediaServiceClient;
import com.xuecheng.learning.model.dto.XcCourseTablesDto;
import com.xuecheng.learning.service.LearningService;
import com.xuecheng.learning.service.MyCourseTablesService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List; | 3,476 | package com.xuecheng.learning.service.impl;
/**
* 学习课程管理 service 接口实现类
*
* @author Wuxy
* @version 1.0
* @ClassName LearningServiceImpl
* @since 2023/2/3 12:32
*/
@Service
public class LearningServiceImpl implements LearningService {
@Autowired
private ContentServiceClient contentServiceClient;
@Autowired
private MediaServiceClient mediaServiceClient;
@Autowired
private MyCourseTablesService myCourseTablesService;
@Override
public RestResponse<String> getVideo(String userId, Long courseId, Long teachplanId, String mediaId) {
// 查询课程信息
CoursePublish coursePublish = contentServiceClient.getCoursePublish(courseId);
if (coursePublish == null) { | package com.xuecheng.learning.service.impl;
/**
* 学习课程管理 service 接口实现类
*
* @author Wuxy
* @version 1.0
* @ClassName LearningServiceImpl
* @since 2023/2/3 12:32
*/
@Service
public class LearningServiceImpl implements LearningService {
@Autowired
private ContentServiceClient contentServiceClient;
@Autowired
private MediaServiceClient mediaServiceClient;
@Autowired
private MyCourseTablesService myCourseTablesService;
@Override
public RestResponse<String> getVideo(String userId, Long courseId, Long teachplanId, String mediaId) {
// 查询课程信息
CoursePublish coursePublish = contentServiceClient.getCoursePublish(courseId);
if (coursePublish == null) { | XueChengPlusException.cast("课程信息不存在"); | 0 | 2023-11-04 07:15:26+00:00 | 4k |
snicoll/cds-log-parser | src/main/java/org/springframework/experiment/cds/Runner.java | [
{
"identifier": "CdsArchiveLogParser",
"path": "src/main/java/org/springframework/experiment/cds/parser/CdsArchiveLogParser.java",
"snippet": "public class CdsArchiveLogParser {\n\n\tprivate static final Log logger = LogFactory.getLog(CdsArchiveLogParser.class);\n\n\tpublic CdsArchiveReport parse(Resource resource) throws IOException {\n\t\tif (!resource.exists()) {\n\t\t\tthrow new IllegalAccessError(\"Resource \" + resource + \" does not exist\");\n\t\t}\n\t\tLogLineParser lineParser = new LogLineParser();\n\t\tprocess(resource, lineParser);\n\t\treturn lineParser.toReport();\n\t}\n\n\tprivate void process(Resource resource, Consumer<String> line) throws IOException {\n\t\ttry (Scanner scanner = new Scanner(resource.getInputStream(), StandardCharsets.UTF_8)) {\n\t\t\twhile (scanner.hasNextLine()) {\n\t\t\t\tString nextLine = scanner.nextLine();\n\t\t\t\tif (StringUtils.hasText(nextLine)) {\n\t\t\t\t\tline.accept(nextLine);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate class LogLineParser implements Consumer<String> {\n\n\t\tprivate static final String SKIPPING_TAG = \"Skipping\";\n\n\t\tprivate final MultiValueMap<String, String> skipped = new LinkedMultiValueMap<>();\n\n\t\t@Override\n\t\tpublic void accept(String content) {\n\t\t\tLogLine logLine = LogLine.parse(content);\n\t\t\tif (!logLine.containTags(\"cds\")) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tString message = logLine.message();\n\t\t\tif (!message.startsWith(SKIPPING_TAG)) {\n\t\t\t\tlogger.debug(\"Could not process \" + message);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tString classNameAndReason = message.substring(SKIPPING_TAG.length());\n\t\t\tint separator = classNameAndReason.indexOf(\":\");\n\t\t\tif (separator == -1) {\n\t\t\t\tlogger.warn(\"Separator not found \" + message);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tString className = classNameAndReason.substring(0, separator).trim().replace('/', '.');\n\t\t\tString reason = classNameAndReason.substring(separator + 1).trim();\n\t\t\tif (reason.contains(\"is excluded\") && reason.contains(\"interface \")) {\n\t\t\t\tskipped.add(CdsArchiveReport.INTERFACE_EXCLUDED, className);\n\t\t\t}\n\t\t\telse if (reason.contains(\"is excluded\") && reason.contains(\"super class \")) {\n\t\t\t\tskipped.add(CdsArchiveReport.SUPER_CLASS_EXCLUDED, className);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tskipped.add(reason, className);\n\t\t\t}\n\t\t}\n\n\t\tpublic CdsArchiveReport toReport() {\n\t\t\treturn new CdsArchiveReport(this.skipped);\n\t\t}\n\n\t}\n\n}"
},
{
"identifier": "CdsArchiveReport",
"path": "src/main/java/org/springframework/experiment/cds/parser/CdsArchiveReport.java",
"snippet": "public class CdsArchiveReport {\n\n\t/**\n\t * A curated reason to indicate a class was skipped because one of its interface is\n\t * excluded.\n\t */\n\tpublic static final String INTERFACE_EXCLUDED = \"interface is excluded\";\n\n\t/**\n\t * A curated reason to indicate a class was skipped because its super class is\n\t * excluded.\n\t */\n\tpublic static final String SUPER_CLASS_EXCLUDED = \"super class is excluded\";\n\n\tprivate final MultiValueMap<String, String> skipped;\n\n\tprivate final long total;\n\n\tCdsArchiveReport(MultiValueMap<String, String> skipped) {\n\t\tthis.skipped = CollectionUtils.unmodifiableMultiValueMap(new LinkedMultiValueMap<>(skipped));\n\t\tthis.total = this.skipped.values().stream().map(List::size).reduce(0, Integer::sum);\n\t}\n\n\t/**\n\t * Return the number of classes that were skipped from the archive.\n\t * @return the number of excluded classes\n\t */\n\tpublic long getSkippedCount() {\n\t\treturn this.total;\n\t}\n\n\t/**\n\t * Return the classes that were excluded, mapped by reasons.\n\t * @return a mapping of class names by reason for exclusion\n\t */\n\tpublic MultiValueMap<String, String> getSkipped() {\n\t\treturn this.skipped;\n\t}\n\n}"
},
{
"identifier": "ClassLoadingLogParser",
"path": "src/main/java/org/springframework/experiment/cds/parser/ClassLoadingLogParser.java",
"snippet": "public class ClassLoadingLogParser {\n\n\tprivate static final Log logger = LogFactory.getLog(ClassLoadingLogParser.class);\n\n\tprivate final Path workingDir;\n\n\tpublic ClassLoadingLogParser(Path workingDir) {\n\t\tthis.workingDir = workingDir;\n\t}\n\n\tpublic ClassLoadingReport parser(Resource resource) throws IOException {\n\t\tif (!resource.exists()) {\n\t\t\tthrow new IllegalAccessError(\"Resource \" + resource + \" does not exist\");\n\t\t}\n\t\tLogLineParser lineParser = new LogLineParser();\n\t\tprocess(resource, lineParser);\n\t\treturn lineParser.toReport();\n\t}\n\n\tprivate void process(Resource resource, Consumer<String> line) throws IOException {\n\t\ttry (Scanner scanner = new Scanner(resource.getInputStream(), StandardCharsets.UTF_8)) {\n\t\t\twhile (scanner.hasNextLine()) {\n\t\t\t\tString nextLine = scanner.nextLine();\n\t\t\t\tif (StringUtils.hasText(nextLine)) {\n\t\t\t\t\tline.accept(nextLine);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate class LogLineParser implements Consumer<String> {\n\n\t\tprivate static final String SOURCE_TAG = \"source: \";\n\n\t\tprivate static final String HIT_SOURCE = \"shared objects file\";\n\n\t\tprivate static final String FILE_URI_PREFIX = \"file:\";\n\n\t\tprivate final List<String> hits = new ArrayList<>();\n\n\t\tprivate final MultiValueMap<String, String> misses = new LinkedMultiValueMap<>();\n\n\t\t@Override\n\t\tpublic void accept(String content) {\n\t\t\tLogLine logLine = LogLine.parse(content);\n\t\t\tif (!logLine.containTags(\"class\", \"load\")) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tString message = logLine.message();\n\t\t\tint sourceIndex = message.indexOf(SOURCE_TAG);\n\t\t\tif (sourceIndex == -1) {\n\t\t\t\tlogger.debug(\"No source found in \" + message);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tString source = message.substring(sourceIndex + SOURCE_TAG.length()).trim();\n\t\t\tString className = message.substring(0, sourceIndex).trim();\n\t\t\tif (source.startsWith(HIT_SOURCE)) {\n\t\t\t\thits.add(className);\n\t\t\t}\n\t\t\telse if (source.startsWith(FILE_URI_PREFIX)) {\n\t\t\t\tPath path = Path.of(source.substring(FILE_URI_PREFIX.length()));\n\t\t\t\tPath pathToUse = path.startsWith(workingDir) ? workingDir.relativize(path) : path;\n\t\t\t\tmisses.add(pathToUse.toString(), className);\n\t\t\t}\n\t\t\telse if (source.startsWith(\"jar:nested:\")) {\n\t\t\t\tint start = source.indexOf(\"!\");\n\t\t\t\tint end = source.indexOf(\"!\", start + 1);\n\t\t\t\tif (start == -1 || end == -1) {\n\t\t\t\t\tthrow new IllegalArgumentException(\"Nested jar not found in \" + source);\n\t\t\t\t}\n\t\t\t\tmisses.add(source.substring(start + 1, end), className);\n\t\t\t}\n\t\t\telse if (source.equals(ClassLoadingReport.CLASS_DEFINER)\n\t\t\t\t\t|| source.equals(ClassLoadingReport.DYNAMIC_GENERATED_LAMBDA)\n\t\t\t\t\t|| source.equals(ClassLoadingReport.DYNAMIC_PROXY)) {\n\t\t\t\tmisses.add(source, className);\n\t\t\t}\n\t\t\telse if (className.startsWith(source)) { // Lambda\n\t\t\t\tmisses.add(source, className);\n\t\t\t}\n\t\t\telse if (source.startsWith(\"jrt:/\")) { // Java Runtime Image\n\t\t\t\tmisses.add(source, className);\n\t\t\t}\n\t\t\telse if (source.startsWith(\"instance of \")) {\n\t\t\t\tmisses.add(source.substring(\"instance of \".length()), className);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tlogger.warn(\"Fallback on default source for \" + logLine);\n\t\t\t\tmisses.add(source, className);\n\t\t\t}\n\t\t}\n\n\t\tpublic ClassLoadingReport toReport() {\n\t\t\treturn new ClassLoadingReport(this.hits, this.misses);\n\t\t}\n\n\t}\n\n}"
},
{
"identifier": "ClassLoadingReport",
"path": "src/main/java/org/springframework/experiment/cds/parser/ClassLoadingReport.java",
"snippet": "public class ClassLoadingReport {\n\n\t/**\n\t * The location for dynamic generated lambdas.\n\t */\n\tpublic static final String DYNAMIC_GENERATED_LAMBDA = \"__JVM_LookupDefineClass__\";\n\n\t/**\n\t * The location for dynamic proxies.\n\t */\n\tpublic static final String DYNAMIC_PROXY = \"__dynamic_proxy__\";\n\n\t/**\n\t * TODO.\n\t */\n\tpublic static final String CLASS_DEFINER = \"__ClassDefiner__\";\n\n\tprivate final List<String> hits;\n\n\tprivate final MultiValueMap<String, String> misses;\n\n\tprivate final long total;\n\n\tClassLoadingReport(List<String> hits, MultiValueMap<String, String> misses) {\n\t\tthis.hits = List.copyOf(hits);\n\t\tthis.misses = CollectionUtils.unmodifiableMultiValueMap(new LinkedMultiValueMap<>(misses));\n\t\tthis.total = hits.size() + misses.values().stream().map(List::size).reduce(0, Integer::sum);\n\t}\n\n\t/**\n\t * Return the class names that were loaded from the cache.\n\t * @return the hits\n\t */\n\tpublic List<String> getHits() {\n\t\treturn this.hits;\n\t}\n\n\t/**\n\t * Return the classes names that were not loaded from the cache, mapped by location.\n\t * @return a map from location to class names that were not loaded from the cache\n\t */\n\tpublic MultiValueMap<String, String> getMisses() {\n\t\treturn this.misses;\n\t}\n\n\t/**\n\t * Return the total number of classes that were loaded.\n\t * @return the classes loaded count\n\t */\n\tpublic long getLoadCount() {\n\t\treturn this.total;\n\t}\n\n\t/**\n\t * Returns the ratio of classes that were loaded from the cache.\n\t * @return the hit rate\n\t */\n\tpublic float getHitRate() {\n\t\treturn ((float) this.hits.size() / (float) this.total);\n\t}\n\n\t/**\n\t * Returns the ratio of classes that were loaded from the classpath.\n\t * @return the miss rate\n\t */\n\tpublic float getMissRate() {\n\t\treturn 1 - getHitRate();\n\t}\n\n}"
}
] | import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Locale;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.io.FileSystemResource;
import org.springframework.experiment.cds.parser.CdsArchiveLogParser;
import org.springframework.experiment.cds.parser.CdsArchiveReport;
import org.springframework.experiment.cds.parser.ClassLoadingLogParser;
import org.springframework.experiment.cds.parser.ClassLoadingReport;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils; | 3,149 | package org.springframework.experiment.cds;
/**
* {@link ApplicationRunner} implementation that parses and print a class loading report.
*
* @author Stephane Nicoll
*/
@Component
class Runner implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) throws Exception {
String target = getValue(args, "target", System.getProperty("user.dir"));
Path workingDirectory = Paths.get(target);
Mode mode = Mode.from(args);
switch (mode) {
case PARSE -> parseJvmLogs(args, workingDirectory);
case CREATE -> createCdsArchive(args, workingDirectory);
}
}
private void createCdsArchive(ApplicationArguments args, Path workingDirectory) throws Exception {
List<String> applicationArguments = detectApplication(args, workingDirectory);
if (applicationArguments == null) {
throw new IllegalStateException("No application detected in " + workingDirectory);
}
AppRunner appRunner = new AppRunner();
System.out.println("Creating the CDS archive ...");
System.out.println();
System.out.println("Using java version:");
System.out.println(appRunner.getJavaVersion());
System.out.println("Starting application using command: java " + String.join(" ", applicationArguments));
Path cdsArchive = appRunner.createCdsArchive(workingDirectory, applicationArguments);
CdsArchiveReport report = new CdsArchiveLogParser().parse(new FileSystemResource(cdsArchive));
new CdsArchiveReportPrinter().print(report, System.out);
System.out.println(
"To use the archive and collect class loading logs for this application, add the following flags:");
System.out.println();
System.out.println("\t-XX:SharedArchiveFile=application.jsa -Xlog:class+load:file=cds.log");
}
private List<String> detectApplication(ApplicationArguments args, Path workingDirectory) {
String jarFile = getValue(args, "jar", null);
if (jarFile != null) {
if (!Files.exists(workingDirectory.resolve(jarFile))) {
throw new IllegalArgumentException(
"Specified jar file does not exist: " + workingDirectory.resolve(jarFile));
}
return List.of("-jar", jarFile);
}
else if (Files.exists(workingDirectory.resolve("BOOT-INF"))) {
return List.of("org.springframework.boot.loader.launch.JarLauncher");
}
else if (Files.exists(workingDirectory.resolve("run-app.jar"))) {
return List.of("-jar", "run-app.jar");
}
return null;
}
private void parseJvmLogs(ApplicationArguments args, Path workingDirectory) throws IOException {
String fileName = getValue(args, "logFile", "cds.log");
Path logFile = workingDirectory.resolve(fileName);
if (!Files.exists(logFile)) {
throw new IllegalArgumentException(
"JVM log file does not exist: '" + logFile.toAbsolutePath() + "' Set --target or --logFile");
}
ClassLoadingLogParser parser = new ClassLoadingLogParser(workingDirectory); | package org.springframework.experiment.cds;
/**
* {@link ApplicationRunner} implementation that parses and print a class loading report.
*
* @author Stephane Nicoll
*/
@Component
class Runner implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) throws Exception {
String target = getValue(args, "target", System.getProperty("user.dir"));
Path workingDirectory = Paths.get(target);
Mode mode = Mode.from(args);
switch (mode) {
case PARSE -> parseJvmLogs(args, workingDirectory);
case CREATE -> createCdsArchive(args, workingDirectory);
}
}
private void createCdsArchive(ApplicationArguments args, Path workingDirectory) throws Exception {
List<String> applicationArguments = detectApplication(args, workingDirectory);
if (applicationArguments == null) {
throw new IllegalStateException("No application detected in " + workingDirectory);
}
AppRunner appRunner = new AppRunner();
System.out.println("Creating the CDS archive ...");
System.out.println();
System.out.println("Using java version:");
System.out.println(appRunner.getJavaVersion());
System.out.println("Starting application using command: java " + String.join(" ", applicationArguments));
Path cdsArchive = appRunner.createCdsArchive(workingDirectory, applicationArguments);
CdsArchiveReport report = new CdsArchiveLogParser().parse(new FileSystemResource(cdsArchive));
new CdsArchiveReportPrinter().print(report, System.out);
System.out.println(
"To use the archive and collect class loading logs for this application, add the following flags:");
System.out.println();
System.out.println("\t-XX:SharedArchiveFile=application.jsa -Xlog:class+load:file=cds.log");
}
private List<String> detectApplication(ApplicationArguments args, Path workingDirectory) {
String jarFile = getValue(args, "jar", null);
if (jarFile != null) {
if (!Files.exists(workingDirectory.resolve(jarFile))) {
throw new IllegalArgumentException(
"Specified jar file does not exist: " + workingDirectory.resolve(jarFile));
}
return List.of("-jar", jarFile);
}
else if (Files.exists(workingDirectory.resolve("BOOT-INF"))) {
return List.of("org.springframework.boot.loader.launch.JarLauncher");
}
else if (Files.exists(workingDirectory.resolve("run-app.jar"))) {
return List.of("-jar", "run-app.jar");
}
return null;
}
private void parseJvmLogs(ApplicationArguments args, Path workingDirectory) throws IOException {
String fileName = getValue(args, "logFile", "cds.log");
Path logFile = workingDirectory.resolve(fileName);
if (!Files.exists(logFile)) {
throw new IllegalArgumentException(
"JVM log file does not exist: '" + logFile.toAbsolutePath() + "' Set --target or --logFile");
}
ClassLoadingLogParser parser = new ClassLoadingLogParser(workingDirectory); | ClassLoadingReport report = parser.parser(new FileSystemResource(logFile)); | 3 | 2023-11-06 08:24:32+00:00 | 4k |
SAHONGPAK/JWT-Example | jwt-springboot/src/main/java/com/example/jwt/controller/UserController.java | [
{
"identifier": "AuthDto",
"path": "jwt-springboot/src/main/java/com/example/jwt/model/dto/AuthDto.java",
"snippet": "public class AuthDto {\n\tprivate String userId;\n\tprivate String refreshToken;\n\t\n\tpublic AuthDto(String userId, String refreshToken) {\n\t\tthis.userId = userId;\n\t\tthis.refreshToken = refreshToken;\n\t}\n\t\n\tpublic String getUserId() {\n\t\treturn userId;\n\t}\n\tpublic void setUserId(String userId) {\n\t\tthis.userId = userId;\n\t}\n\tpublic String getRefreshToken() {\n\t\treturn refreshToken;\n\t}\n\tpublic void setRefreshToken(String refreshToken) {\n\t\tthis.refreshToken = refreshToken;\n\t}\n\t\n\t@Override\n\tpublic String toString() {\n\t\treturn \"AuthDto [userId=\" + userId + \", refreshToken=\" + refreshToken + \"]\";\n\t}\n}"
},
{
"identifier": "UserDto",
"path": "jwt-springboot/src/main/java/com/example/jwt/model/dto/UserDto.java",
"snippet": "public class UserDto {\n\tprivate String id;\n\tprivate String password;\n\tprivate String name;\n\tprivate int permission;\n\t\n\tpublic String getId() {\n\t\treturn id;\n\t}\n\tpublic void setId(String id) {\n\t\tthis.id = id;\n\t}\n\tpublic String getPassword() {\n\t\treturn password;\n\t}\n\tpublic void setPassword(String password) {\n\t\tthis.password = password;\n\t}\n\tpublic String getName() {\n\t\treturn name;\n\t}\n\tpublic void setName(String name) {\n\t\tthis.name = name;\n\t}\n\tpublic void setPermission(int permission) {\n\t\tthis.permission = permission;\n\t}\n\tpublic int getPermission() {\n\t\treturn permission;\n\t}\n\t\n\t@Override\n\tpublic String toString() {\n\t\treturn \"UserDto [id=\" + id + \", password=\" + password + \", name=\" + name + \", permission=\" + permission + \"]\";\n\t}\n}"
},
{
"identifier": "AuthService",
"path": "jwt-springboot/src/main/java/com/example/jwt/model/service/AuthService.java",
"snippet": "public interface AuthService {\n\tint setRefreshToken(AuthDto authDto);\n\tAuthDto getRefreshToken(String userId);\n\tint updateRefreshToken(AuthDto authDto);\n\t\n}"
},
{
"identifier": "UserService",
"path": "jwt-springboot/src/main/java/com/example/jwt/model/service/UserService.java",
"snippet": "public interface UserService {\n\tUserDto login(UserDto userDto);\n\tUserDto myPage(String id);\n\tint signUp(UserDto userDto);\n\tboolean modify(Map<String, String> map);\n\tint withdrawal(String string);\n}"
},
{
"identifier": "JWTUtil",
"path": "jwt-springboot/src/main/java/com/example/jwt/util/JWTUtil.java",
"snippet": "@Component\npublic class JWTUtil {\n\t\n\t@Value(\"jwt.key\")\n\tprivate String jwtKey;\n\t\n\t@Value(\"${jwt.accesstoken.expiretime}\")\n\tprivate Long accessTokenExpireTime;\n\t\n\t@Value(\"${jwt.refreshtoken.expiretime}\")\n\tprivate Long refreshTokenExpireTime;\n\t\n\tpublic String createAccessToken(String userId) throws UnsupportedEncodingException {\n\t\n\t\t// 현재 시간을 저장한다.\n\t\tlong currentTimeMillis = System.currentTimeMillis();\n\t\t\n\t\t// accessToken을 생성한다.\n\t\tJwtBuilder jwtAccessTokenBuilder = Jwts.builder();\n\t\tjwtAccessTokenBuilder.claim(\"userId\", userId);\n\t\tjwtAccessTokenBuilder.setIssuedAt(new Date(currentTimeMillis));\n\t\tjwtAccessTokenBuilder.setExpiration(new Date(currentTimeMillis + accessTokenExpireTime*1000));\n\t\tjwtAccessTokenBuilder.signWith(SignatureAlgorithm.HS256, jwtKey.getBytes(\"UTF-8\"));\n\t\n\t\treturn jwtAccessTokenBuilder.compact();\n\t}\n\t\n\t\n\tpublic String createRefreshToken(String userId) throws UnsupportedEncodingException {\n\t\t\n\t\t// 현재 시간을 저장한다.\n\t\tlong currentTimeMillis = System.currentTimeMillis();\n\t\t\n\t\t\n\t\t// refreshToken을 생성한다.\n\t\tJwtBuilder jwtRefreshTokenBuilder = Jwts.builder();\n\t\tjwtRefreshTokenBuilder.claim(\"userId\", userId);\n\t\tjwtRefreshTokenBuilder.setIssuedAt(new Date(currentTimeMillis));\n\t\tjwtRefreshTokenBuilder.setExpiration(new Date(currentTimeMillis + refreshTokenExpireTime*1000));\n\t\tjwtRefreshTokenBuilder.signWith(SignatureAlgorithm.HS256, jwtKey.getBytes(\"UTF-8\"));\n\t\n\t\treturn jwtRefreshTokenBuilder.compact();\n\t}\n\t\n\tpublic String getUserId(String authorization) throws ParseException {\n\t\t// accessToken을 파싱한다.\n\t\tString[] chunks = authorization.split(\"\\\\.\");\n\t\tBase64.Decoder decoder = Base64.getUrlDecoder();\n\t\t\n\t\t// payload에 저장된 userId를 획득한다.\n\t\tString payload = new String(decoder.decode(chunks[1]));\n\t\tJSONParser parser = new JSONParser();\n\t\tJSONObject obj = (JSONObject) parser.parse(payload);\n\t\t\n\t\tString userId = (String) obj.get(\"userId\");\n\t\t\n\t\treturn userId;\n\t}\n\t\n\tpublic boolean vaildCheck(String token) {\n\t\t\n\t\t// 해당 토큰을 확인하면서 예외가 발생하는 경우\n\t\t// 만료가 되었거나, 잘못된 토큰이다.\n\t\ttry {\n\t\t\tJwts.parser().setSigningKey(jwtKey.getBytes(\"UTF-8\")).parseClaimsJws(token);\n\t\t}\n\t\tcatch (Exception e) {\n\t\t\t// 예외가 발생한 경우 유효한 토큰이 아니다.\n\t\t\treturn false;\n\t\t}\n\t\n\t\t// 예외가 발생하지 않았다면 유효한 토큰이다.\n\t\treturn true;\n\t}\n}"
}
] | import java.io.UnsupportedEncodingException;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
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.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.example.jwt.annotation.AuthRequired;
import com.example.jwt.model.dto.AuthDto;
import com.example.jwt.model.dto.UserDto;
import com.example.jwt.model.service.AuthService;
import com.example.jwt.model.service.UserService;
import com.example.jwt.util.JWTUtil;
import io.swagger.annotations.ApiOperation;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses; | 1,601 | package com.example.jwt.controller;
@RestController
@RequestMapping("/api/v1/user")
public class UserController {
@Value("${jwt.refreshtoken.expiretime}")
private Integer refreshTokenExpireTime;
private final UserService userService; | package com.example.jwt.controller;
@RestController
@RequestMapping("/api/v1/user")
public class UserController {
@Value("${jwt.refreshtoken.expiretime}")
private Integer refreshTokenExpireTime;
private final UserService userService; | private final JWTUtil jwtUtil; | 4 | 2023-11-09 13:14:13+00:00 | 4k |
Verusins/CMS-Android-Simulation | app/src/main/java/example/com/cmsandroidsimulation/EventStudentFragment.java | [
{
"identifier": "EventComment",
"path": "app/src/main/java/example/com/cmsandroidsimulation/datastructures/EventComment.java",
"snippet": "public class EventComment extends UserPost {\n private final int rating;\n private final Date date;\n public EventComment(String author, String details, int rating, Date date) {\n super(author, null, details);\n this.rating = rating;\n this.date = date;\n }\n\n public int getRating() {\n return rating;\n }\n\n public Date getDate() {\n return date;\n }\n\n}"
},
{
"identifier": "EventInfo",
"path": "app/src/main/java/example/com/cmsandroidsimulation/datastructures/EventInfo.java",
"snippet": "public class EventInfo extends UserPost{\n\n // Might change to builder pattern later.\n\n private final ArrayList<EventComment> comments;\n private final Date eventStartDateTime;\n private final Date eventEndDateTime;\n private final String eventid;\n\n private final int maxppl;\n\n private final String location;\n\n private final ArrayList<String> attendees;\n\n public EventInfo(String eventid, String author, String title, String details,\n Date eventStartDateTime, Date eventEndDateTime,\n ArrayList<EventComment> comments, int maxppl, ArrayList<String> attendees, String location)\n {\n super(author, title, details);\n this.comments = comments;\n this.eventStartDateTime = eventStartDateTime;\n this.eventEndDateTime = eventEndDateTime;\n this.eventid = eventid;\n this.maxppl = maxppl;\n this.attendees = attendees;\n this.location = location;\n }\n\n public String getLocation() {return location;}\n public ArrayList<String> getAttendees(){return attendees;}\n\n public String getEventid(){\n return eventid;\n }\n\n public ArrayList<EventComment> getComments() {\n return comments;\n }\n\n public Date getEventEndDateTime() {\n return eventEndDateTime;\n }\n\n public int getMaxppl() {return maxppl;}\n\n public Date getEventStartDateTime() {\n return eventStartDateTime;\n }\n}"
},
{
"identifier": "Student",
"path": "app/src/main/java/example/com/cmsandroidsimulation/apiwrapper/Student.java",
"snippet": "public class Student extends User {\n public void Logout(){\n\n FirebaseAuth.getInstance().signOut();\n instance = null;\n }\n\n\n public static Task<AuthResult> Register(String username, String email, String password) throws FailedLoginException\n {\n // Simulate an asynchronous API call\n Task<AuthResult> authResult = mAuth.createUserWithEmailAndPassword(email, password);\n authResult.addOnCompleteListener(new OnCompleteListener<AuthResult>() {\n @Override\n public void onComplete(@NonNull Task<AuthResult> task) {\n if (task.isSuccessful()) {\n // Sign in success, update UI with the signed-in user's information\n instance = new Student();\n instance.email = email;\n user = mAuth.getCurrentUser();\n Map<String, Object> user = new HashMap<>();\n ArrayList<String> events = new ArrayList<>();\n user.put(\"name\", username);\n user.put(\"email\", email);\n user.put(\"isAdmin\", false);\n user.put(\"events\", events);\n FirebaseFirestore db = FirebaseFirestore.getInstance();\n db.collection(\"users\")\n .add(user)\n .addOnSuccessListener(new OnSuccessListener<DocumentReference>() {\n @Override\n public void onSuccess(DocumentReference documentReference) {\n Log.d(\"MASTER APP\", \"DocumentSnapshot added with ID: \" + documentReference.getId());\n }\n });\n } else {\n // If sign in fails, display a message to the user.\n Log.e(\"MASTER APP\", \"Login failed\");\n }\n }\n });\n return authResult;\n }\n public static Student getInstance()\n {\n return (Student) instance;\n }\n public Task<DocumentSnapshot> postEventComment(EventInfo eventInfo, String content, int rating)\n {\n String eventid = eventInfo.getEventid();\n FirebaseFirestore db = FirebaseFirestore.getInstance();\n Task<DocumentSnapshot> task = db.collection(\"events\").document(eventid).get()\n .addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {\n @Override\n public void onComplete(@NonNull Task<DocumentSnapshot> task) {\n if (task.isSuccessful()) {\n DocumentSnapshot document = task.getResult();\n if (document.exists()) {\n getName(email).thenAccept((String username) -> {\n ArrayList<EventComment> temp = (ArrayList<EventComment>) document.get(\"comments\");\n EventComment eventComment = new EventComment(username, content, rating, new Date());\n temp.add(eventComment);\n DocumentReference eventref = db.collection(\"events\").document(eventid);\n eventref.update(\"comments\", temp);\n });\n } else {\n Log.e(\"MASTER APP\", \"No such document\");\n }\n } else {\n Log.e(\"MASTER APP\", \"Error getting document: \", task.getException());\n }\n }\n });\n return task;\n }\n // TODO: implement api calls\n public CompletableFuture<Boolean> getEventHasRated(EventInfo eventInfo)\n {\n return CompletableFuture.supplyAsync(() -> {\n // Simulate an asynchronous API call\n try {\n Thread.sleep(2000); // Simulating a delay\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n return false;\n });\n }\n public CompletableFuture<Void> setEventHasRSVPd(EventInfo eventInfo, boolean setTrue)\n {\n FirebaseFirestore db = FirebaseFirestore.getInstance();\n Task<QuerySnapshot> task = db.collection(\"users\").whereEqualTo(\"email\", email).get();\n task.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {\n @Override\n public void onComplete(@NonNull Task<QuerySnapshot> task) {\n if (task.isSuccessful()) {\n for (QueryDocumentSnapshot document : task.getResult()) {\n ArrayList<String> events = (ArrayList<String>) document.get(\"events\");\n if (!setTrue && events.indexOf(eventInfo.getEventid()) != -1){\n events.remove(eventInfo.getEventid());\n }\n else if (setTrue && events.indexOf(eventInfo.getEventid()) == -1){\n events.add(eventInfo.getEventid());\n }\n DocumentReference eventref = db.collection(\"users\").document(document.getId());\n eventref.update(\"events\", events);\n }\n// Log.e(\"MASTER APP\", \"No such document USER\");\n } else {\n Log.e(\"MASTER APP\", \"Error getting document: \", task.getException());\n }\n }\n });\n Task<QuerySnapshot> eventtask = db.collection(\"events\").get();\n eventtask.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {\n @Override\n public void onComplete(@NonNull Task<QuerySnapshot> eventtask) {\n if (eventtask.isSuccessful()) {\n for (QueryDocumentSnapshot document : eventtask.getResult()) {\n Log.i(\"MASTERP APP\", document.getId() + \" \" + eventInfo.getEventid());\n if (document.getId().equals(eventInfo.getEventid())){\n ArrayList<String> attendees = (ArrayList<String>) document.get(\"attendees\");\n if (!setTrue && attendees.indexOf(email) != -1){\n attendees.remove(email);\n }\n else if (setTrue && attendees.indexOf(email) == -1){\n attendees.add(email);\n }\n DocumentReference eventref = db.collection(\"events\").document(eventInfo.getEventid());\n eventref.update(\"attendees\", attendees);\n }\n }\n// Log.e(\"MASTER APP\", \"No such document EVENTS\");\n } else {\n Log.e(\"MASTER APP\", \"Error getting document: \", eventtask.getException());\n }\n }\n });\n return CompletableFuture.completedFuture(null);\n }\n\n// TODO: implement api calls\n public Task<DocumentReference> postComplaint(String author, String content)\n {\n Log.i(\"MASTER APP\", \"prepare post complaint\");\n Log.i(\"MASTER APP\", author);\n Log.i(\"MASTER APP\", content);\n Map<String, Object> complaint = new HashMap<>();\n complaint.put(\"username\", author);\n complaint.put(\"description\", content);\n FirebaseFirestore db = FirebaseFirestore.getInstance();\n Task<DocumentReference> task =db.collection(\"complaint\").add(complaint);\n task.addOnSuccessListener(new OnSuccessListener<DocumentReference>() {\n @Override\n public void onSuccess(DocumentReference documentReference) {\n Log.d(\"SUCCESS\", \"DocumentSnapshot for complaint added with ID: \" + documentReference.getId());\n }\n });\n return task;\n }\n// return CompletableFuture.supplyAsync(() -> {\n// // Simulate an asynchronous API call\n// try {\n// Thread.sleep(2000); // Simulating a delay\n// } catch (InterruptedException e) {\n// e.printStackTrace();\n// }\n// return null;\n// });\n}"
}
] | import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.navigation.fragment.NavHostFragment;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.firestore.DocumentSnapshot;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Locale;
import example.com.cmsandroidsimulation.databinding.FragmentEventStudentBinding;
import example.com.cmsandroidsimulation.datastructures.EventComment;
import example.com.cmsandroidsimulation.datastructures.EventInfo;
import example.com.cmsandroidsimulation.apiwrapper.Student; | 2,351 | package example.com.cmsandroidsimulation;
public class EventStudentFragment extends Fragment {
FragmentEventStudentBinding binding;
@Override
public View onCreateView(
LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState
) {
binding = FragmentEventStudentBinding.inflate(inflater, container, false);
return binding.getRoot();
}
@SuppressLint("MissingInflatedId")
@Override
public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
// Load Content from db
int eventIndex = getArguments().getInt("selectedEventIndex");
| package example.com.cmsandroidsimulation;
public class EventStudentFragment extends Fragment {
FragmentEventStudentBinding binding;
@Override
public View onCreateView(
LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState
) {
binding = FragmentEventStudentBinding.inflate(inflater, container, false);
return binding.getRoot();
}
@SuppressLint("MissingInflatedId")
@Override
public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
// Load Content from db
int eventIndex = getArguments().getInt("selectedEventIndex");
| Student.getInstance().getEvents().thenAccept((ArrayList<EventInfo> events) -> { | 2 | 2023-11-07 16:52:01+00:00 | 4k |
ProjectBIGWHALE/bigwhale-api | src/test/java/com/whale/web/documents/DocumentsTest.java | [
{
"identifier": "CertificateTypeEnum",
"path": "src/main/java/com/whale/web/documents/certificategenerator/model/enums/CertificateTypeEnum.java",
"snippet": "@Getter\n@ToString\npublic enum CertificateTypeEnum {\n PARTICIPATION(\"Participante\"), SPEAKER(\"Palestrante\"), COURCE(\"Curso\");\n\n private final String type;\n\n CertificateTypeEnum(String type) {\n this.type = type;\n }\n}"
},
{
"identifier": "CompactConverterService",
"path": "src/main/java/com/whale/web/documents/compressedfileconverter/CompactConverterService.java",
"snippet": "@Service\npublic class CompactConverterService {\n\n private final ConvertToZipService convertToZip;\n\n private final ConvertToTarService convertToTar;\n\n private final ConvertTo7zService converterTo7z;\n\n private final ConvertToTarGzService convertToTarGz;\n\n\n public CompactConverterService(ConvertToZipService convertToZip, ConvertToTarService convertToTar,\n ConvertTo7zService converterTo7z, ConvertToTarGzService convertToTarGz) {\n this.convertToZip = convertToZip;\n this.convertToTar = convertToTar;\n this.converterTo7z = converterTo7z;\n this.convertToTarGz = convertToTarGz;\n }\n\n public List<byte[]> converterFile(List<MultipartFile> files, String outputFormat) throws IOException {\n\n if (files == null || files.isEmpty() || !areAllFilesZip(files)) {\n throw new IllegalArgumentException(\"The input is not a valid zip file\");\n } else {\n return switch (outputFormat.toLowerCase()) {\n case \"zip\" -> convertToZip.convertToZip(files);\n case \"tar.gz\" -> convertToTarGz.convertToTarGz(files);\n case \"7z\" -> converterTo7z.convertTo7z(files);\n case \"tar\" -> convertToTar.convertToTar(files);\n default -> throw new IllegalArgumentException(\"Invalid compression format\");\n };\n }\n }\n\n public static boolean areAllFilesZip(List<MultipartFile> files) {\n for (MultipartFile file : files) {\n if (!isZipFileByFilename(file)) {\n return false;\n }\n }\n return true;\n }\n\n public static boolean isZipFileByFilename(MultipartFile file) {\n String originalFilename = file.getOriginalFilename();\n if (originalFilename != null) {\n\n return originalFilename.toLowerCase().endsWith(\".zip\");\n }\n return false;\n }\n}"
},
{
"identifier": "ZipFileCompressorService",
"path": "src/main/java/com/whale/web/documents/zipfilegenerator/ZipFileCompressorService.java",
"snippet": "@Service\npublic class ZipFileCompressorService {\n\n public byte[] compressFiles(List<MultipartFile> multipartFiles) throws IOException {\n if (multipartFiles == null || multipartFiles.isEmpty()) {\n throw new IllegalArgumentException(\"The input file list is null or empty.\");\n }\n\n try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();\n ZipOutputStream zipOut = new ZipOutputStream(byteArrayOutputStream)) {\n\n zipOut.setLevel(Deflater.BEST_COMPRESSION);\n\n for (MultipartFile multipartFile : multipartFiles) {\n ZipEntry zipEntry = new ZipEntry(Objects.requireNonNull(multipartFile.getOriginalFilename()));\n zipOut.putNextEntry(zipEntry);\n\n byte[] buffer = new byte[1024];\n int length;\n InputStream fileInputStream = multipartFile.getInputStream();\n\n while ((length = fileInputStream.read(buffer)) > 0) {\n zipOut.write(buffer, 0, length);\n }\n\n zipOut.closeEntry();\n fileInputStream.close();\n }\n\n zipOut.finish();\n return byteArrayOutputStream.toByteArray();\n }\n }\n}"
},
{
"identifier": "TextExtractService",
"path": "src/main/java/com/whale/web/documents/textextract/TextExtractService.java",
"snippet": "@Service\npublic class TextExtractService {\n\n private static final String PATCH = \"../bigwhale/src/main/resources/static/tessdata\";\n\n public String extractTextFromImage(MultipartFile multipartFile) {\n\n Tesseract tesseract = new Tesseract();\n tesseract.setDatapath(PATCH);\n tesseract.setLanguage(\"por\");\n\n try {\n return tesseract.doOCR(convertMutlpartFileToBufferedImage(multipartFile));\n } catch (TesseractException e) {\n throw new RuntimeException(e.getCause());\n }\n }\n\n private BufferedImage convertMutlpartFileToBufferedImage(MultipartFile multipartFile) {\n try {\n ByteArrayInputStream inputStream = new ByteArrayInputStream(multipartFile.getBytes());\n return ImageIO.read(inputStream);\n } catch (IOException e) {\n throw new RuntimeException(e.getCause());\n }\n }\n}"
}
] | import com.fasterxml.jackson.databind.ObjectMapper;
import com.whale.web.documents.certificategenerator.dto.CertificateRecordDto;
import com.whale.web.documents.certificategenerator.model.enums.CertificateTypeEnum;
import com.whale.web.documents.compressedfileconverter.CompactConverterService;
import com.whale.web.documents.zipfilegenerator.ZipFileCompressorService;
import com.whale.web.documents.qrcodegenerator.dto.QRCodeEmailRecordDto;
import com.whale.web.documents.qrcodegenerator.dto.QRCodeLinkRecordDto;
import com.whale.web.documents.qrcodegenerator.dto.QRCodeWhatsappRecordDto;
import com.whale.web.documents.textextract.TextExtractService;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; | 2,867 | "test-image." + inputFormat,
"image/" + inputFormat,
baos.toByteArray()
);
}
MockMultipartFile createTestImageWhithName(String inputFormat, String name) throws IOException {
BufferedImage bufferedImage = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB);
Graphics2D graphics = bufferedImage.createGraphics();
graphics.setColor(Color.WHITE);
graphics.fillRect(0, 0, 100, 100);
graphics.dispose();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(bufferedImage, inputFormat, baos);
baos.toByteArray();
return new MockMultipartFile(
name,
"test-image." + inputFormat,
"image/" + inputFormat,
baos.toByteArray()
);
}
@Test
void testCompactConverterForOneArchive() throws Exception {
MockMultipartFile file = createTestZipFile();
String outputFormat = "tar";
mockMvc.perform(MockMvcRequestBuilders.multipart("/api/v1/documents/compactconverter")
.file(file)
.param("outputFormat", outputFormat))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.header().string("Content-Disposition", "attachment; filename=zip-test." + outputFormat))
.andExpect(MockMvcResultMatchers.header().string("Content-Type", "application/octet-stream"))
.andReturn();
}
@Test
void testCompactConverterForTwoArchives() throws Exception {
MockMultipartFile file1 = createTestZipFile();
MockMultipartFile file2 = createTestZipFile();
String outputFormat = "7z";
mockMvc.perform(MockMvcRequestBuilders.multipart("/api/v1/documents/compactconverter")
.file(file1)
.file(file2)
.param("outputFormat", outputFormat))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.header().string("Content-Disposition", "attachment; filename=zip-test." + outputFormat))
.andExpect(MockMvcResultMatchers.header().string("Content-Type", "application/octet-stream"))
.andReturn();
}
@Test
void compressFileShouldReturnTheFileZip() throws Exception {
MockMultipartFile multipartFile = new MockMultipartFile(
"file",
"test-file.txt",
"text/plain",
"Test file content".getBytes()
);
var multipartFile2 = createTestImage("jpeg", "file");
when(compressorService.compressFiles(any())).thenReturn(multipartFile.getBytes());
mockMvc.perform(MockMvcRequestBuilders.multipart("/api/v1/documents/filecompressor")
.file(multipartFile)
.file(multipartFile2))
.andExpect(status().isOk())
.andExpect(MockMvcResultMatchers.content().contentType("application/octet-stream"))
.andExpect(MockMvcResultMatchers.header().string("Content-Disposition", "attachment; filename=compressedFile.zip"));
verify(compressorService, times(1)).compressFiles(any());
}
/* @Test
void shouldReturnTheCertificatesStatusCode200() throws Exception {
String csvContent = "col1,col2,col3\nvalue1,value2,value3";
MockMultipartFile csvFileDto = new MockMultipartFile(
"csvFileDto",
"worksheet.csv",
MediaType.TEXT_PLAIN_VALUE,
csvContent.getBytes());
var certificateRecordDto = new CertificateRecordDto(
CertificateTypeEnum.COURCE,
"ABC dos DEVS",
"Ronnyscley",
"CTO",
"20",
"2023-09-12",
"São Paulo",
1L
);
mockMvc.perform(MockMvcRequestBuilders.multipart("/api/v1/documents/certificategenerator")
.file(csvFileDto)
.flashAttr("certificateRecordDto", certificateRecordDto)
.contentType(MediaType.MULTIPART_FORM_DATA))
.andExpect(status().isOk())
.andExpect(MockMvcResultMatchers.content().contentType(MediaType.APPLICATION_OCTET_STREAM_VALUE))
.andExpect(MockMvcResultMatchers.header().string("Content-Disposition", Matchers.containsString("attachment")));
}*/
@Test
void shouldReturnARedirectionStatusCode500() throws Exception {
String csvContent = "col1,col2,col3\nvalue1,value2,value3";
MockMultipartFile csvFileDto = new MockMultipartFile(
"csvFileDto",
"worksheet.csv",
MediaType.TEXT_PLAIN_VALUE,
csvContent.getBytes());
var certificateDto = new CertificateRecordDto( | package com.whale.web.documents;
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
@AutoConfigureMockMvc
@SpringBootTest
class DocumentsTest {
@Autowired
private MockMvc mockMvc;
@Autowired
private ObjectMapper objectMapper;
@MockBean
private TextExtractService textExtractService;
@MockBean
private ZipFileCompressorService compressorService;
@MockBean
private CompactConverterService compactConverterService;
MockMultipartFile createTestZipFile() throws IOException {
try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
ZipOutputStream zipOut = new ZipOutputStream(baos)) {
ZipEntry entry = new ZipEntry("test.txt");
zipOut.putNextEntry(entry);
byte[] fileContent = "This is a test file content.".getBytes();
zipOut.write(fileContent, 0, fileContent.length);
zipOut.closeEntry();
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
return new MockMultipartFile("files", "zip-test.zip", "application/zip", bais);
}
}
MockMultipartFile createTestTarFile() throws IOException {
try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
TarArchiveOutputStream tarOut = new TarArchiveOutputStream(baos)) {
TarArchiveEntry entry = new TarArchiveEntry("test.txt");
tarOut.putArchiveEntry(entry);
byte[] fileContent = "This is a test file content.".getBytes();
tarOut.write(fileContent, 0, fileContent.length);
tarOut.closeArchiveEntry();
tarOut.finish();
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
return new MockMultipartFile("files", "tar-test.tar", "application/tar", bais);
}
}
MockMultipartFile createTestImage(String inputFormat, String name) throws IOException {
BufferedImage bufferedImage = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB);
Graphics2D graphics = bufferedImage.createGraphics();
graphics.setColor(Color.WHITE);
graphics.fillRect(0, 0, 100, 100);
graphics.dispose();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(bufferedImage, inputFormat, baos);
baos.toByteArray();
return new MockMultipartFile(
name,
"test-image." + inputFormat,
"image/" + inputFormat,
baos.toByteArray()
);
}
MockMultipartFile createTestImageWhithName(String inputFormat, String name) throws IOException {
BufferedImage bufferedImage = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB);
Graphics2D graphics = bufferedImage.createGraphics();
graphics.setColor(Color.WHITE);
graphics.fillRect(0, 0, 100, 100);
graphics.dispose();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(bufferedImage, inputFormat, baos);
baos.toByteArray();
return new MockMultipartFile(
name,
"test-image." + inputFormat,
"image/" + inputFormat,
baos.toByteArray()
);
}
@Test
void testCompactConverterForOneArchive() throws Exception {
MockMultipartFile file = createTestZipFile();
String outputFormat = "tar";
mockMvc.perform(MockMvcRequestBuilders.multipart("/api/v1/documents/compactconverter")
.file(file)
.param("outputFormat", outputFormat))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.header().string("Content-Disposition", "attachment; filename=zip-test." + outputFormat))
.andExpect(MockMvcResultMatchers.header().string("Content-Type", "application/octet-stream"))
.andReturn();
}
@Test
void testCompactConverterForTwoArchives() throws Exception {
MockMultipartFile file1 = createTestZipFile();
MockMultipartFile file2 = createTestZipFile();
String outputFormat = "7z";
mockMvc.perform(MockMvcRequestBuilders.multipart("/api/v1/documents/compactconverter")
.file(file1)
.file(file2)
.param("outputFormat", outputFormat))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.header().string("Content-Disposition", "attachment; filename=zip-test." + outputFormat))
.andExpect(MockMvcResultMatchers.header().string("Content-Type", "application/octet-stream"))
.andReturn();
}
@Test
void compressFileShouldReturnTheFileZip() throws Exception {
MockMultipartFile multipartFile = new MockMultipartFile(
"file",
"test-file.txt",
"text/plain",
"Test file content".getBytes()
);
var multipartFile2 = createTestImage("jpeg", "file");
when(compressorService.compressFiles(any())).thenReturn(multipartFile.getBytes());
mockMvc.perform(MockMvcRequestBuilders.multipart("/api/v1/documents/filecompressor")
.file(multipartFile)
.file(multipartFile2))
.andExpect(status().isOk())
.andExpect(MockMvcResultMatchers.content().contentType("application/octet-stream"))
.andExpect(MockMvcResultMatchers.header().string("Content-Disposition", "attachment; filename=compressedFile.zip"));
verify(compressorService, times(1)).compressFiles(any());
}
/* @Test
void shouldReturnTheCertificatesStatusCode200() throws Exception {
String csvContent = "col1,col2,col3\nvalue1,value2,value3";
MockMultipartFile csvFileDto = new MockMultipartFile(
"csvFileDto",
"worksheet.csv",
MediaType.TEXT_PLAIN_VALUE,
csvContent.getBytes());
var certificateRecordDto = new CertificateRecordDto(
CertificateTypeEnum.COURCE,
"ABC dos DEVS",
"Ronnyscley",
"CTO",
"20",
"2023-09-12",
"São Paulo",
1L
);
mockMvc.perform(MockMvcRequestBuilders.multipart("/api/v1/documents/certificategenerator")
.file(csvFileDto)
.flashAttr("certificateRecordDto", certificateRecordDto)
.contentType(MediaType.MULTIPART_FORM_DATA))
.andExpect(status().isOk())
.andExpect(MockMvcResultMatchers.content().contentType(MediaType.APPLICATION_OCTET_STREAM_VALUE))
.andExpect(MockMvcResultMatchers.header().string("Content-Disposition", Matchers.containsString("attachment")));
}*/
@Test
void shouldReturnARedirectionStatusCode500() throws Exception {
String csvContent = "col1,col2,col3\nvalue1,value2,value3";
MockMultipartFile csvFileDto = new MockMultipartFile(
"csvFileDto",
"worksheet.csv",
MediaType.TEXT_PLAIN_VALUE,
csvContent.getBytes());
var certificateDto = new CertificateRecordDto( | CertificateTypeEnum.COURCE, | 0 | 2023-11-08 22:41:22+00:00 | 4k |
ballerina-platform/module-ballerina-data-xmldata | native/src/main/java/io/ballerina/stdlib/data/xmldata/FromString.java | [
{
"identifier": "DiagnosticErrorCode",
"path": "native/src/main/java/io/ballerina/stdlib/data/xmldata/utils/DiagnosticErrorCode.java",
"snippet": "public enum DiagnosticErrorCode {\n\n INVALID_TYPE(\"BDE_0001\", \"invalid.type\"),\n XML_ROOT_MISSING(\"BDE_0002\", \"xml.root.missing\"),\n INVALID_REST_TYPE(\"BDE_0003\", \"invalid.rest.type\"),\n ARRAY_SIZE_MISMATCH(\"BDE_0004\", \"array.size.mismatch\"),\n REQUIRED_FIELD_NOT_PRESENT(\"BDE_0005\", \"required.field.not.present\"),\n REQUIRED_ATTRIBUTE_NOT_PRESENT(\"BDE_0006\", \"required.attribute.not.present\"),\n DUPLICATE_FIELD(\"BDE_0007\", \"duplicate.field\"),\n FOUND_ARRAY_FOR_NON_ARRAY_TYPE(\"BDE_0008\", \"found.array.for.non.array.type\"),\n EXPECTED_ANYDATA_OR_JSON(\"BDE_0009\", \"expected.anydata.or.json\"),\n NAMESPACE_MISMATCH(\"BDE_0010\", \"namespace.mismatch\"),\n TYPE_NAME_MISMATCH_WITH_XML_ELEMENT(\"BDE_0011\", \"type.name.mismatch.with.xml.element\"),\n CAN_NOT_READ_STREAM(\"BDE_0012\", \"error.cannot.read.stream\"),\n CANNOT_CONVERT_TO_EXPECTED_TYPE(\"BDE_0013\", \"cannot.convert.to.expected.type\"),\n UNSUPPORTED_TYPE(\"BDE_0014\", \"unsupported.type\"),\n STREAM_BROKEN(\"BDE_0015\", \"stream.broken\"),\n XML_PARSE_ERROR(\"BDE_0016\", \"xml.parse.error\");\n\n String diagnosticId;\n String messageKey;\n\n DiagnosticErrorCode(String diagnosticId, String messageKey) {\n this.diagnosticId = diagnosticId;\n this.messageKey = messageKey;\n }\n\n public String messageKey() {\n return messageKey;\n }\n}"
},
{
"identifier": "DiagnosticLog",
"path": "native/src/main/java/io/ballerina/stdlib/data/xmldata/utils/DiagnosticLog.java",
"snippet": "public class DiagnosticLog {\n private static final String ERROR_PREFIX = \"error\";\n private static final String ERROR = \"Error\";\n private static final ResourceBundle MESSAGES = ResourceBundle.getBundle(\"error\", Locale.getDefault());\n\n public static BError error(DiagnosticErrorCode code, Object... args) {\n String msg = formatMessage(code, args);\n return getXmlError(msg);\n }\n\n private static String formatMessage(DiagnosticErrorCode code, Object[] args) {\n String msgKey = MESSAGES.getString(ERROR_PREFIX + \".\" + code.messageKey());\n return MessageFormat.format(msgKey, args);\n }\n\n public static BError getXmlError(String message) {\n return ErrorCreator.createError(ModuleUtils.getModule(), ERROR, StringUtils.fromString(message),\n null, null);\n }\n}"
}
] | import java.util.Comparator;
import java.util.List;
import io.ballerina.runtime.api.PredefinedTypes;
import io.ballerina.runtime.api.TypeTags;
import io.ballerina.runtime.api.creators.ValueCreator;
import io.ballerina.runtime.api.types.ReferenceType;
import io.ballerina.runtime.api.types.Type;
import io.ballerina.runtime.api.types.UnionType;
import io.ballerina.runtime.api.values.BDecimal;
import io.ballerina.runtime.api.values.BError;
import io.ballerina.runtime.api.values.BString;
import io.ballerina.runtime.api.values.BTypedesc;
import io.ballerina.stdlib.data.xmldata.utils.DiagnosticErrorCode;
import io.ballerina.stdlib.data.xmldata.utils.DiagnosticLog; | 1,760 | /*
* Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com).
*
* WSO2 LLC. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package io.ballerina.stdlib.data.xmldata;
/**
* Native implementation of data:fromStringWithType(string).
*
* @since 0.1.0
*/
public class FromString {
public static Object fromStringWithType(BString string, BTypedesc typed) {
Type expType = typed.getDescribingType();
try {
return fromStringWithType(string, expType);
} catch (NumberFormatException e) {
return returnError(string.getValue(), expType.toString());
}
}
public static Object fromStringWithTypeInternal(BString string, Type expType) {
return fromStringWithType(string, expType);
}
private static Object fromStringWithType(BString string, Type expType) {
String value = string.getValue();
try {
switch (expType.getTag()) {
case TypeTags.INT_TAG:
return stringToInt(value);
case TypeTags.FLOAT_TAG:
return stringToFloat(value);
case TypeTags.DECIMAL_TAG:
return stringToDecimal(value);
case TypeTags.STRING_TAG:
return string;
case TypeTags.BOOLEAN_TAG:
return stringToBoolean(value);
case TypeTags.NULL_TAG:
return stringToNull(value);
case TypeTags.UNION_TAG:
return stringToUnion(string, (UnionType) expType);
case TypeTags.TYPE_REFERENCED_TYPE_TAG:
return fromStringWithType(string, ((ReferenceType) expType).getReferredType());
default:
return returnError(value, expType.toString());
}
} catch (NumberFormatException e) {
return returnError(value, expType.toString());
}
}
private static Long stringToInt(String value) throws NumberFormatException {
return Long.parseLong(value);
}
private static Double stringToFloat(String value) throws NumberFormatException {
if (hasFloatOrDecimalLiteralSuffix(value)) {
throw new NumberFormatException();
}
return Double.parseDouble(value);
}
private static BDecimal stringToDecimal(String value) throws NumberFormatException {
return ValueCreator.createDecimalValue(value);
}
private static Object stringToBoolean(String value) throws NumberFormatException {
if ("true".equalsIgnoreCase(value) || "1".equalsIgnoreCase(value)) {
return true;
}
if ("false".equalsIgnoreCase(value) || "0".equalsIgnoreCase(value)) {
return false;
}
return returnError(value, "boolean");
}
private static Object stringToNull(String value) throws NumberFormatException {
if ("null".equalsIgnoreCase(value) || "()".equalsIgnoreCase(value)) {
return null;
}
return returnError(value, "()");
}
private static Object stringToUnion(BString string, UnionType expType) throws NumberFormatException {
List<Type> memberTypes = expType.getMemberTypes();
memberTypes.sort(Comparator.comparingInt(t -> t.getTag()));
boolean isStringExpType = false;
for (Type memberType : memberTypes) {
try {
Object result = fromStringWithType(string, memberType);
if (result instanceof BString) {
isStringExpType = true;
continue;
} else if (result instanceof BError) {
continue;
}
return result;
} catch (Exception e) {
// Skip
}
}
if (isStringExpType) {
return string;
}
return returnError(string.getValue(), expType.toString());
}
private static boolean hasFloatOrDecimalLiteralSuffix(String value) {
int length = value.length();
if (length == 0) {
return false;
}
switch (value.charAt(length - 1)) {
case 'F':
case 'f':
case 'D':
case 'd':
return true;
default:
return false;
}
}
private static BError returnError(String string, String expType) { | /*
* Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com).
*
* WSO2 LLC. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package io.ballerina.stdlib.data.xmldata;
/**
* Native implementation of data:fromStringWithType(string).
*
* @since 0.1.0
*/
public class FromString {
public static Object fromStringWithType(BString string, BTypedesc typed) {
Type expType = typed.getDescribingType();
try {
return fromStringWithType(string, expType);
} catch (NumberFormatException e) {
return returnError(string.getValue(), expType.toString());
}
}
public static Object fromStringWithTypeInternal(BString string, Type expType) {
return fromStringWithType(string, expType);
}
private static Object fromStringWithType(BString string, Type expType) {
String value = string.getValue();
try {
switch (expType.getTag()) {
case TypeTags.INT_TAG:
return stringToInt(value);
case TypeTags.FLOAT_TAG:
return stringToFloat(value);
case TypeTags.DECIMAL_TAG:
return stringToDecimal(value);
case TypeTags.STRING_TAG:
return string;
case TypeTags.BOOLEAN_TAG:
return stringToBoolean(value);
case TypeTags.NULL_TAG:
return stringToNull(value);
case TypeTags.UNION_TAG:
return stringToUnion(string, (UnionType) expType);
case TypeTags.TYPE_REFERENCED_TYPE_TAG:
return fromStringWithType(string, ((ReferenceType) expType).getReferredType());
default:
return returnError(value, expType.toString());
}
} catch (NumberFormatException e) {
return returnError(value, expType.toString());
}
}
private static Long stringToInt(String value) throws NumberFormatException {
return Long.parseLong(value);
}
private static Double stringToFloat(String value) throws NumberFormatException {
if (hasFloatOrDecimalLiteralSuffix(value)) {
throw new NumberFormatException();
}
return Double.parseDouble(value);
}
private static BDecimal stringToDecimal(String value) throws NumberFormatException {
return ValueCreator.createDecimalValue(value);
}
private static Object stringToBoolean(String value) throws NumberFormatException {
if ("true".equalsIgnoreCase(value) || "1".equalsIgnoreCase(value)) {
return true;
}
if ("false".equalsIgnoreCase(value) || "0".equalsIgnoreCase(value)) {
return false;
}
return returnError(value, "boolean");
}
private static Object stringToNull(String value) throws NumberFormatException {
if ("null".equalsIgnoreCase(value) || "()".equalsIgnoreCase(value)) {
return null;
}
return returnError(value, "()");
}
private static Object stringToUnion(BString string, UnionType expType) throws NumberFormatException {
List<Type> memberTypes = expType.getMemberTypes();
memberTypes.sort(Comparator.comparingInt(t -> t.getTag()));
boolean isStringExpType = false;
for (Type memberType : memberTypes) {
try {
Object result = fromStringWithType(string, memberType);
if (result instanceof BString) {
isStringExpType = true;
continue;
} else if (result instanceof BError) {
continue;
}
return result;
} catch (Exception e) {
// Skip
}
}
if (isStringExpType) {
return string;
}
return returnError(string.getValue(), expType.toString());
}
private static boolean hasFloatOrDecimalLiteralSuffix(String value) {
int length = value.length();
if (length == 0) {
return false;
}
switch (value.charAt(length - 1)) {
case 'F':
case 'f':
case 'D':
case 'd':
return true;
default:
return false;
}
}
private static BError returnError(String string, String expType) { | return DiagnosticLog.error(DiagnosticErrorCode.CANNOT_CONVERT_TO_EXPECTED_TYPE, | 1 | 2023-11-08 04:13:52+00:00 | 4k |
Mau38/SparePartsFTC | TeamCode/src/main/java/org/firstinspires/ftc/teamcode/ParkFarBlue.java | [
{
"identifier": "SampleMecanumDrive",
"path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/roadRunner/drive/SampleMecanumDrive.java",
"snippet": "@Config\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 = 1;\n\n public static double VX_WEIGHT = 1;\n public static double VY_WEIGHT = 1;\n public static double OMEGA_WEIGHT = 1;\n\n private TrajectorySequenceRunner trajectorySequenceRunner;\n\n private static final TrajectoryVelocityConstraint VEL_CONSTRAINT = getVelocityConstraint(MAX_VEL, MAX_ANG_VEL, TRACK_WIDTH);\n private static final TrajectoryAccelerationConstraint ACCEL_CONSTRAINT = getAccelerationConstraint(MAX_ACCEL);\n\n private TrajectoryFollower follower;\n\n private DcMotorEx leftFront, leftRear, rightRear, rightFront;\n private List<DcMotorEx> motors;\n\n private 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 // 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 RevHubOrientationOnRobot.LogoFacingDirection.UP, RevHubOrientationOnRobot.UsbFacingDirection.RIGHT));\n imu.initialize(parameters);\n\n leftFront = hardwareMap.get(DcMotorEx.class, \"frontLeft\");\n leftRear = hardwareMap.get(DcMotorEx.class, \"backLeft\");\n rightRear = hardwareMap.get(DcMotorEx.class, \"backRight\");\n rightFront = hardwareMap.get(DcMotorEx.class, \"frontRight\");\n\n leftRear.setDirection(DcMotorSimple.Direction.REVERSE);\n leftFront.setDirection(DcMotorSimple.Direction.REVERSE);\n\n motors = Arrays.asList(leftFront, leftRear, rightRear, rightFront);\n\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\n trajectorySequenceRunner = new TrajectorySequenceRunner(\n follower, HEADING_PID, batteryVoltageSensor,\n lastEncPositions, lastEncVels, lastTrackingEncPositions, lastTrackingEncVels\n );\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 imu.getRobotYawPitchRollAngles().getYaw(AngleUnit.RADIANS);\n }\n\n @Override\n public Double getExternalHeadingVelocity() {\n return (double) imu.getRobotAngularVelocity(AngleUnit.RADIANS).zRotationRate;\n }\n\n public static TrajectoryVelocityConstraint getVelocityConstraint(double maxVel, double maxAngularVel, double trackWidth) {\n return new MinVelocityConstraint(Arrays.asList(\n new AngularVelocityConstraint(maxAngularVel),\n new MecanumVelocityConstraint(maxVel, trackWidth)\n ));\n }\n\n public static TrajectoryAccelerationConstraint getAccelerationConstraint(double maxAccel) {\n return new ProfileAccelerationConstraint(maxAccel);\n }\n}"
},
{
"identifier": "TrajectorySequence",
"path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/roadRunner/trajectorysequence/TrajectorySequence.java",
"snippet": "public class TrajectorySequence {\n private final List<SequenceSegment> sequenceList;\n\n public TrajectorySequence(List<SequenceSegment> sequenceList) {\n if (sequenceList.size() == 0) throw new EmptySequenceException();\n\n this.sequenceList = Collections.unmodifiableList(sequenceList);\n }\n\n public Pose2d start() {\n return sequenceList.get(0).getStartPose();\n }\n\n public Pose2d end() {\n return sequenceList.get(sequenceList.size() - 1).getEndPose();\n }\n\n public double duration() {\n double total = 0.0;\n\n for (SequenceSegment segment : sequenceList) {\n total += segment.getDuration();\n }\n\n return total;\n }\n\n public SequenceSegment get(int i) {\n return sequenceList.get(i);\n }\n\n public int size() {\n return sequenceList.size();\n }\n}"
}
] | import com.acmerobotics.roadrunner.geometry.Pose2d;
import com.qualcomm.robotcore.eventloop.opmode.Autonomous;
import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;
import org.firstinspires.ftc.teamcode.roadRunner.drive.SampleMecanumDrive;
import org.firstinspires.ftc.teamcode.roadRunner.trajectorysequence.TrajectorySequence; | 2,865 | package org.firstinspires.ftc.teamcode;
@Autonomous(name = "ParkFarBlue", group = "CompAutos")
public class ParkFarBlue extends LinearOpMode {
public static double STRAFE_DIST = 30;
public static double FORWARD_DIST = 160;
@Override
public void runOpMode() throws InterruptedException { | package org.firstinspires.ftc.teamcode;
@Autonomous(name = "ParkFarBlue", group = "CompAutos")
public class ParkFarBlue extends LinearOpMode {
public static double STRAFE_DIST = 30;
public static double FORWARD_DIST = 160;
@Override
public void runOpMode() throws InterruptedException { | SampleMecanumDrive drive = new SampleMecanumDrive(hardwareMap); | 0 | 2023-11-06 21:25:54+00:00 | 4k |
RoshanAdi/GPTonDemand-Api | src/main/java/com/gpt/gptplus1/Controller/UserController.java | [
{
"identifier": "ResponseMessage",
"path": "src/main/java/com/gpt/gptplus1/Entity/ResponseMessage.java",
"snippet": "public class ResponseMessage {\n private String message;\n\n public ResponseMessage(String message) {\n this.message = message;\n }\n\n public String getMessage() {\n return message;\n }\n\n public void setMessage(String message) {\n this.message = message;\n }\n\n}"
},
{
"identifier": "User",
"path": "src/main/java/com/gpt/gptplus1/Entity/User.java",
"snippet": "@Entity\npublic class User {\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n @NotNull\n private int userId;\n\n private String firstName;\n private String lastName;\n private String email;\n private String phone;\n private String password;\n\n private String verificationCode;\n\n private boolean enabled;\n private String role;\n\n public int getUserId() {\n return userId;\n }\n\n public void setUserId(int userId) {\n this.userId = userId;\n }\n\n public String getFirstName() {\n return firstName;\n }\n\n public void setFirstName(String firstName) {\n this.firstName = firstName;\n }\n\n public String getLastName() {\n return lastName;\n }\n\n public void setLastName(String lastName) {\n this.lastName = lastName;\n }\n\n public String getEmail() {\n return email;\n }\n\n public void setEmail(String email) {\n this.email = email;\n }\n\n public String getPhone() {\n return phone;\n }\n\n public void setPhone(String phone) {\n this.phone = phone;\n }\n\n public String getPassword() {\n return password;\n }\n\n public void setPassword(String password) {\n this.password = password;\n }\n\n public String getVerificationCode() {\n return verificationCode;\n }\n\n public void setVerificationCode(String verificationCode) {\n this.verificationCode = verificationCode;\n }\n\n public boolean isEnabled() {\n return enabled;\n }\n\n public void setEnabled(boolean enabled) {\n this.enabled = enabled;\n }\n\n public String getRole() {\n return role;\n }\n\n public void setRole(String role) {\n this.role = role;\n }\n}"
},
{
"identifier": "SendEmail",
"path": "src/main/java/com/gpt/gptplus1/Service/Email/SendEmail.java",
"snippet": "@Service\npublic class SendEmail {\n\n @Autowired\n private JavaMailSender mailSender;\n @Autowired\n UserRepo userRepo;\n public void sendVerificationEmail(User user, String siteURL) throws UnsupportedEncodingException, MessagingException {\n String toAddress = user.getEmail();\n String fromAddress = \"[email protected]\";\n String senderName = \"GPTPlus\";\n String subject = \"Please Verify Your Email Address\";\n String content = \"Dear [[name]],<br>\"\n + \"Please click the link below to verify your Email address:<br>\"\n + \"<h3><a href=\\\"[[URL]]\\\" target=\\\"_self\\\">VERIFY</a></h3>\"\n + \"Thank you,<br>\"\n + \"Roshan.\";\n\n MimeMessage message = mailSender.createMimeMessage();\n MimeMessageHelper helper = new MimeMessageHelper(message);\n\n helper.setFrom(fromAddress, senderName);\n helper.setTo(toAddress);\n helper.setSubject(subject);\n\n content = content.replace(\"[[name]]\", user.getFirstName());\n String verifyURL = siteURL + \"/api1/verify-account?code=\" + user.getVerificationCode();\n content = content.replace(\"[[URL]]\", verifyURL);\n\n helper.setText(content, true);\n\n mailSender.send(message);\n }\n public void sendCodes(User user, String siteURL) throws UnsupportedEncodingException, MessagingException {\n String toAddress = user.getEmail();\n String fromAddress = \"[email protected]\";\n String senderName = \"GPTPlus\";\n String subject = \"Your verification code\";\n String content = \"Dear [[name]],<br>\"\n + \"your one-time verification code is <span style=\\\"background-color: yellow; font-weight: bold;\\\">[[code]]</span>:<br>\"\n + \"Thank you,<br>\"\n + \"GPTPlus.\";\n\n MimeMessage message = mailSender.createMimeMessage();\n MimeMessageHelper helper = new MimeMessageHelper(message);\n\n helper.setFrom(fromAddress, senderName);\n helper.setTo(toAddress);\n helper.setSubject(subject);\n content = content.replace(\"[[name]]\", user.getFirstName());\n String randomNumber = generateRandomNumericString();\n user.setVerificationCode(randomNumber);\n userRepo.save(user);\n content = content.replace(\"[[code]]\", randomNumber);\n\n helper.setText(content, true);\n\n mailSender.send(message);\n }\n private static String generateRandomNumericString() {\n Random random = new Random();\n StringBuilder numericString = new StringBuilder(6);\n\n for (int i = 0; i < 6; i++) {\n int digit = random.nextInt(10);\n numericString.append(digit);\n }\n\n return numericString.toString();\n }\n public boolean verify(String verificationCode) {\n User user = userRepo.findByVerificationCode(verificationCode);\n if (user == null || user.isEnabled()) {\n return false;\n }\n else {\n user.setEnabled(true);\n userRepo.save(user);\n return true;\n }\n\n }\n}"
},
{
"identifier": "AuthToken",
"path": "src/main/java/com/gpt/gptplus1/Service/WebSecurity/AuthToken.java",
"snippet": "public class AuthToken {\n\n private String token;\n\n public AuthToken(){\n\n }\n\n public AuthToken(String token){\n this.token = token;\n }\n\n public String getToken() {\n return token;\n }\n\n public void setToken(String token) {\n this.token = token;\n }\n\n}"
},
{
"identifier": "TokenProvider",
"path": "src/main/java/com/gpt/gptplus1/Service/WebSecurity/TokenProvider.java",
"snippet": "@Component\npublic class TokenProvider implements Serializable {\n\n @Value(\"${jwt.token.validity}\")\n public long TOKEN_VALIDITY;\n\n @Value(\"${jwt.signing.key}\")\n public String SIGNING_KEY;\n\n @Value(\"${jwt.authorities.key}\")\n public String AUTHORITIES_KEY;\n\n public String getUsernameFromToken(String token) {\n return getClaimFromToken(token, Claims::getSubject);\n }\n\n public Date getExpirationDateFromToken(String token) {\n return getClaimFromToken(token, Claims::getExpiration);\n }\n\n public <T> T getClaimFromToken(String token, Function<Claims, T> claimsResolver) {\n final Claims claims = getAllClaimsFromToken(token);\n return claimsResolver.apply(claims);\n }\n\n private Claims getAllClaimsFromToken(String token) {\n return Jwts.parser()\n .setSigningKey(SIGNING_KEY)\n .parseClaimsJws(token)\n .getBody();\n }\n\n private Boolean isTokenExpired(String token) {\n final Date expiration = getExpirationDateFromToken(token);\n return expiration.before(new Date());\n }\n\n public String generateToken(Authentication authentication) {\n System.out.println(\"generating token...\");\n String authorities = authentication.getAuthorities().stream()\n .map(GrantedAuthority::getAuthority)\n .collect(Collectors.joining(\",\"));\n\n return Jwts.builder()\n .setSubject(authentication.getName())\n .claim(AUTHORITIES_KEY, authorities)\n .setIssuedAt(new Date(System.currentTimeMillis()))\n .setExpiration(new Date(System.currentTimeMillis() + TOKEN_VALIDITY*1000))\n .signWith(SignatureAlgorithm.HS256, SIGNING_KEY)\n .compact();\n }\n public Boolean validateToken(String token, UserDetails userDetails) {\n final String username = getUsernameFromToken(token);\n System.out.println(\"token username \"+username);\n return (username.equals(userDetails.getUsername()) && !isTokenExpired(token));\n }\n\n UsernamePasswordAuthenticationToken getAuthenticationToken(final String token, final Authentication existingAuth, final UserDetails userDetails) {\n System.out.println(\"Getting authkey\"+token);\n final JwtParser jwtParser = Jwts.parser().setSigningKey(SIGNING_KEY);\n\n final Jws<Claims> claimsJws = jwtParser.parseClaimsJws(token);\n\n final Claims claims = claimsJws.getBody();\n\n final Collection<? extends GrantedAuthority> authorities =\n Arrays.stream(claims.get(AUTHORITIES_KEY).toString().split(\",\"))\n .map(SimpleGrantedAuthority::new)\n .collect(Collectors.toList());\n System.out.println(\"userdetail authorites \"+userDetails.getAuthorities());\n return new UsernamePasswordAuthenticationToken(userDetails, \"\", authorities);\n }\n\n}"
},
{
"identifier": "UserDetailsServiceImpl",
"path": "src/main/java/com/gpt/gptplus1/Service/WebSecurity/UserDetailsServiceImpl.java",
"snippet": "@Service\n@Component\npublic class UserDetailsServiceImpl implements UserDetailsService {\n @Autowired\n UserRepo userRepo;\n public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {\n try {\n User user = userRepo.findByEmail(email);\n return new org.springframework.security.core.userdetails.User(user.getEmail(), user.getPassword(), getAuthority(user));\n\n }catch (UsernameNotFoundException e){return null;}\n\n }\n public boolean isUserEnabled(String email){\n User user = userRepo.findByEmail(email);\n return user != null && user.isEnabled();\n }\n private Set<SimpleGrantedAuthority> getAuthority(User user) {\n Set<SimpleGrantedAuthority> authorities = new HashSet<>();\n authorities.add(new SimpleGrantedAuthority(\"ROLE_\"+user.getRole()));\n return authorities;\n }\n\n public User loadUser4Reset(String email){\n return userRepo.findByEmail(email);\n }\n\n}"
},
{
"identifier": "UserService",
"path": "src/main/java/com/gpt/gptplus1/Service/WebSecurity/UserService.java",
"snippet": "@Service\npublic class UserService {\n @Autowired\n UserRepo userRepo;\n @Autowired\n PasswordEncoder passwordEncoder;\n @Autowired\n SendEmail sendEmail;\n\n\npublic User getUserByEmail(String email){\n\n return userRepo.findByEmail(email);\n}\n public void saveUser(User user,String siteURL){\n try {\n user.setPassword(passwordEncoder.encode(user.getPassword()));\n user.setRole(\"user\");\n user.setEnabled(false);\n String randomCode = RandomString.make(64);\n user.setVerificationCode(randomCode);\n sendEmail.sendVerificationEmail(user, siteURL);\n userRepo.save(user);\n }\n catch (Exception e){\n e.toString();\n }\n }\n public void saveNewPW(User user){\n User userExsisting = userRepo.findByEmail(user.getEmail());\n userExsisting.setPassword(passwordEncoder.encode(user.getPassword()));\n userExsisting.setVerificationCode(null);\n userRepo.save(userExsisting);\n }\n\n}"
}
] | import com.gpt.gptplus1.Entity.ResponseMessage;
import com.gpt.gptplus1.Entity.User;
import com.gpt.gptplus1.Service.Email.SendEmail;
import com.gpt.gptplus1.Service.WebSecurity.AuthToken;
import com.gpt.gptplus1.Service.WebSecurity.TokenProvider;
import com.gpt.gptplus1.Service.WebSecurity.UserDetailsServiceImpl;
import com.gpt.gptplus1.Service.WebSecurity.UserService;
import jakarta.mail.MessagingException;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.repository.query.Param;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.view.RedirectView;
import java.io.UnsupportedEncodingException;
import java.util.Objects; | 3,153 | package com.gpt.gptplus1.Controller;
@RestController
@RequestMapping("/")
public class UserController {
@Value("${frontEnd.URL}")
private String clientURL;
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
private TokenProvider jwtTokenUtil;
@Autowired
private UserService userService;
@Autowired
private SendEmail sendEmail;
@Autowired
private UserDetailsServiceImpl userDetailsService;
@PostMapping(value="/api1/register" )
public ResponseMessage saveUser(@RequestBody User user, HttpServletRequest request) {
String message="";
if (userService.getUserByEmail(user.getEmail())!=null) {
message = user.getEmail()+" is already registered!. May be you haven't verify your email address. if so, please check your mailbox ";
return new ResponseMessage(message);
} else {
String siteURL = request.getRequestURL().toString();
userService.saveUser(user,siteURL.replace(request.getServletPath(),""));
message = "Please confirm your email address. We have sent an confirmation link to "+user.getEmail();
return new ResponseMessage(message);
}
}
@PostMapping(value = "/api1/login")
public ResponseEntity<?> generateToken(@RequestBody User loginUser) throws AuthenticationException {
try {
final Authentication authentication = authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(
loginUser.getEmail(),
loginUser.getPassword()
)
);
if (!userDetailsService.isUserEnabled(loginUser.getEmail())) {
return ResponseEntity.status(399)
.body("User is not enabled. Please verify your email.");
}
SecurityContextHolder.getContext().setAuthentication(authentication);
final String token = jwtTokenUtil.generateToken(authentication);
| package com.gpt.gptplus1.Controller;
@RestController
@RequestMapping("/")
public class UserController {
@Value("${frontEnd.URL}")
private String clientURL;
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
private TokenProvider jwtTokenUtil;
@Autowired
private UserService userService;
@Autowired
private SendEmail sendEmail;
@Autowired
private UserDetailsServiceImpl userDetailsService;
@PostMapping(value="/api1/register" )
public ResponseMessage saveUser(@RequestBody User user, HttpServletRequest request) {
String message="";
if (userService.getUserByEmail(user.getEmail())!=null) {
message = user.getEmail()+" is already registered!. May be you haven't verify your email address. if so, please check your mailbox ";
return new ResponseMessage(message);
} else {
String siteURL = request.getRequestURL().toString();
userService.saveUser(user,siteURL.replace(request.getServletPath(),""));
message = "Please confirm your email address. We have sent an confirmation link to "+user.getEmail();
return new ResponseMessage(message);
}
}
@PostMapping(value = "/api1/login")
public ResponseEntity<?> generateToken(@RequestBody User loginUser) throws AuthenticationException {
try {
final Authentication authentication = authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(
loginUser.getEmail(),
loginUser.getPassword()
)
);
if (!userDetailsService.isUserEnabled(loginUser.getEmail())) {
return ResponseEntity.status(399)
.body("User is not enabled. Please verify your email.");
}
SecurityContextHolder.getContext().setAuthentication(authentication);
final String token = jwtTokenUtil.generateToken(authentication);
| return ResponseEntity.ok(new AuthToken(token)); | 3 | 2023-11-07 11:52:13+00:00 | 4k |
project-BarryBarry/coffeeport | src/main/java/com/barrybarry/coffeeport/router/VeraportRouter.java | [
{
"identifier": "VeraDataConverter",
"path": "src/main/java/com/barrybarry/coffeeport/converter/VeraDataConverter.java",
"snippet": "public class VeraDataConverter implements ResponseConverterFunction {\n // 正直、この方法は良くないと思う\n private static final String callbackFormat = \"try {%s(%s);} catch(e){}\";\n private final String[] allowedCallbackPrefix = {\"vp20handler_callback\", \"jQuery\"};\n\n @Override\n public @NotNull HttpResponse convertResponse(@NotNull ServiceRequestContext ctx, @NotNull ResponseHeaders headers, @Nullable Object res, @NotNull HttpHeaders trailers) {\n HttpResponse response;\n VeraData result = (VeraData) res;\n if (result == null) {\n response = HttpResponse.of(headers, HttpData.ofUtf8(String.format(callbackFormat, \"alert\", \"\\\"error!\\\"\")), trailers);\n } else {\n // Migration: callback xss vulnerability\n Pattern pattern = Pattern.compile(\"[A-Za-z0-9_]+\");\n if (!pattern.matcher(result.getCallback()).matches() || Arrays.stream(allowedCallbackPrefix).noneMatch(result.getCallback()::startsWith)) {\n // do nothing\n response = HttpResponse.of(headers, HttpData.ofUtf8(String.format(callbackFormat, \"void\", \"0\")));\n } else {\n String json = new Gson().toJson(result.getResponseData());\n response = HttpResponse.of(headers, HttpData.ofUtf8(String.format(callbackFormat, result.getCallback(), json)), trailers);\n }\n }\n return response;\n }\n}"
},
{
"identifier": "TaskData",
"path": "src/main/java/com/barrybarry/coffeeport/data/task/TaskData.java",
"snippet": "@SuppressWarnings({\"FieldCanBeLocal\", \"unused\"})\n@Setter\n@Getter\npublic class TaskData {\n private String callback;\n\n private String sid;\n private VeraTaskData data;\n\n private Object callbackData;\n\n private String origin;\n\n public void setData(String json) {\n this.data = new Gson().fromJson(json, VeraTaskData.class);\n }\n\n @SuppressWarnings({\"LombokSetterMayBeUsed\", \"RedundantSuppression\"})\n public void setData(VeraTaskData data) {\n this.data = data;\n }\n}"
},
{
"identifier": "VeraData",
"path": "src/main/java/com/barrybarry/coffeeport/data/task/VeraData.java",
"snippet": "@Getter\n@Setter\npublic class VeraData {\n private ResponseData responseData;\n private String callback;\n}"
},
{
"identifier": "Data",
"path": "src/main/java/com/barrybarry/coffeeport/data/xml/Data.java",
"snippet": "@Getter\n@Setter\n@SuppressWarnings({\"FieldCanBeLocal\", \"unused\"})\npublic class Data {\n private CommandType cmd;\n\n private InstallationConfigureData configure;\n}"
},
{
"identifier": "VeraTaskData",
"path": "src/main/java/com/barrybarry/coffeeport/data/xml/VeraTaskData.java",
"snippet": "@SuppressWarnings({\"FieldCanBeLocal\", \"unused\"})\n@Getter\n@Setter\npublic class VeraTaskData {\n private CommandType cmd;\n private Object data;\n\n private String sid;\n\n public Data getData() {\n if (data == null) return null;\n if(data instanceof Data dat){\n return dat;\n }\n if (data instanceof String str) {\n return new Gson().fromJson(str, Data.class);\n }\n return null;\n }\n}"
},
{
"identifier": "CommandHandler",
"path": "src/main/java/com/barrybarry/coffeeport/handler/CommandHandler.java",
"snippet": "public class CommandHandler {\n private static final Logger logger = LoggerFactory.getLogger(CommandHandler.class);\n public static void handleCommand(ResponseData res, TaskData task){\n res.setRes(0);\n if(task.getData().getCmd() != null) {\n res.setData(switch (task.getData().getCmd()) {\n case VERSION -> getVersion();\n case OS_INFO -> getOsInfo();\n case RESULT -> getResult(task.getSid());\n case AX_INFO -> getInstallationInfo(task);\n case SHOW -> startInstallation(task);\n case IS_RUNNING -> isRunning();\n case UPDATE_UI -> updateUI();\n });\n }\n if(res.getData() == null) res.setRes(1);\n }\n\n private static Object updateUI() {\n logger.debug(\"updateUI\");\n List<String> Ui = new ArrayList<>(TaskListManager.getInstance().getUiUpdate());\n TaskListManager.getInstance().getUiUpdate().clear();\n return Ui;\n }\n\n private static Object isRunning() {\n return TaskListManager.getInstance().isInstallationRunning()?1:0;\n }\n\n private static Object getVersion(){\n return Config.veraVersion;\n }\n private static Object getInstallationInfo(TaskData task){\n PluginInstallInfoData info = SystemUtil.getInstallationInfo(task);\n if(info == null) return null;\n String origin = task.getOrigin();\n ArrayList<InstallationData> installationDataList = new ArrayList<>();\n for (PluginInstallInfoData.PluginInfo pluginInfo : info.getPlugins()) {\n InstallationData installationData = new InstallationData();\n installationData.setObjectName(pluginInfo.getObjectName());\n installationData.setObjectVersion(pluginInfo.getObjectVersion());\n if(!pluginInfo.getBackupUrl().startsWith(\"https://\")) {\n installationData.setBackupUrl(origin + \"/\" + pluginInfo.getBackupUrl());\n }\n else{\n installationData.setBackupUrl(pluginInfo.getBackupUrl());\n }\n if(!pluginInfo.getDownloadUrl().startsWith(\"https://\")) {\n installationData.setDownloadUrl(origin + \"/\" + pluginInfo.getDownloadUrl());\n }\n else{\n installationData.setDownloadUrl(pluginInfo.getDownloadUrl());\n }\n installationData.setDisplayName(pluginInfo.getDisplayName());\n installationData.setObjectVersion(pluginInfo.getObjectVersion());\n installationData.setUpdateState(false);\n// installationData.setInstallState(true);\n installationData.setInstallState(SystemUtil.isInstalled(pluginInfo.getObjectMIMEType()));\n installationDataList.add(installationData);\n }\n return installationDataList;\n }\n private static Object getOsInfo(){\n if(SystemUtil.getOs() == OsType.Linux) return SystemUtil.getLinuxDistroName();\n return SystemUtil.getOsName(); // It seems checks when os is linux, so we don't need to consider windows, macos, etc.\n }\n\n private static Object startInstallation(TaskData task){\n return installActiveX(task);\n }\n\n private static Object installActiveX(TaskData task) {\n String[] installationList = task.getData().getData().getConfigure().getSelectObject().split(\",\");\n PluginInstallInfoData activexInfo = SystemUtil.getInstallationInfo(task);\n assert activexInfo != null;\n TaskListManager.getInstance().setInstallationRunning(true);\n for (String installation:installationList) {\n for (PluginInstallInfoData.PluginInfo info:activexInfo.getPlugins()) {\n if(info.getObjectName().equals(installation)){\n logger.debug(\"installActiveX: {}\", info.getObjectName());\n SystemUtil.installActiveX(info,task);\n }\n }\n }\n\n // install done, send complete message\n UiUpdateData uiUpdateData = new UiUpdateData();\n uiUpdateData.setFunc(\"VP_complete\");\n TaskListManager.getInstance().setUiUpdate(new ArrayList<>() {{add(new Gson().toJson(uiUpdateData));}});\n TaskListManager.getInstance().setInstallationRunning(false);\n return new Object();\n }\n\n private static Object getResult(String sid){\n TaskData task = TaskListManager.getInstance().getTask(sid);\n TaskListManager.getInstance().removeTask(sid);\n if(task == null || task.getCallbackData() == null){\n return \"\";\n }\n if(task.getCallbackData() instanceof ResponseData result) {\n return result.getData();\n }\n if (task.getCallbackData() instanceof String str) {\n return str;\n }\n throw new IllegalStateException(\"Unexpected value: \" + task.getCallbackData());\n }\n}"
},
{
"identifier": "TaskListManager",
"path": "src/main/java/com/barrybarry/coffeeport/sigleton/TaskListManager.java",
"snippet": "@Getter\n@Setter\npublic class TaskListManager {\n private TaskListManager(){\n }\n private final ConcurrentHashMap<String, TaskData> tasks = new ConcurrentHashMap<>();\n\n private volatile boolean isInstallationRunning = false;\n\n private List<String> uiUpdate = Collections.synchronizedList(new ArrayList<>());\n public final TaskData getTask(String sid){\n return tasks.get(sid);\n }\n\n public final void setTask(String sid, TaskData task){\n tasks.put(sid, task);\n }\n\n public final void removeTask(String sid){\n tasks.remove(sid);\n }\n\n public final String[] getTaskList(){\n return tasks.keySet().toArray(new String[0]);\n }\n private static class Lazy{\n private static final TaskListManager instance = new TaskListManager();\n }\n public static TaskListManager getInstance() {\n return Lazy.instance;\n }\n}"
}
] | import com.barrybarry.coffeeport.converter.VeraDataConverter;
import com.barrybarry.coffeeport.data.*;
import com.barrybarry.coffeeport.data.task.TaskData;
import com.barrybarry.coffeeport.data.task.VeraData;
import com.barrybarry.coffeeport.data.xml.Data;
import com.barrybarry.coffeeport.data.xml.VeraTaskData;
import com.barrybarry.coffeeport.handler.CommandHandler;
import com.barrybarry.coffeeport.sigleton.TaskListManager;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.linecorp.armeria.common.HttpRequest;
import com.linecorp.armeria.server.ServiceRequestContext;
import com.linecorp.armeria.server.annotation.Get;
import com.linecorp.armeria.server.annotation.Param;
import com.linecorp.armeria.server.annotation.Post;
import com.linecorp.armeria.server.annotation.ResponseConverter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | 2,299 | package com.barrybarry.coffeeport.router;
public class VeraportRouter {
private static final Logger logger = LoggerFactory.getLogger(VeraportRouter.class);
| package com.barrybarry.coffeeport.router;
public class VeraportRouter {
private static final Logger logger = LoggerFactory.getLogger(VeraportRouter.class);
| @ResponseConverter(VeraDataConverter.class) | 0 | 2023-11-08 01:22:24+00:00 | 4k |
celedev97/asa-server-manager | src/main/java/dev/cele/asa_sm/services/UpdateService.java | [
{
"identifier": "Const",
"path": "src/main/java/dev/cele/asa_sm/Const.java",
"snippet": "public final class Const {\n public final static String ASA_STEAM_GAME_NUMBER = \"2430930\";\n\n public final static Path DATA_DIR = Path.of(\"data\");\n public final static Path PROFILES_DIR = DATA_DIR.resolve(\"profiles\");\n public final static Path SERVERS_DIR = Path.of(\"servers\");\n\n\n public final static Path THEME_DIR = DATA_DIR.resolve(\"themes\");\n public final static Path MOD_CACHE_DIR = DATA_DIR.resolve(\"mod_cache\");\n\n public final static Path SETTINGS_FILE = DATA_DIR.resolve(\"settings.json\");\n\n public final static Path TEMP_DIR = SystemUtils.getJavaIoTmpDir().toPath().resolve(\"asa_sm\");\n}"
},
{
"identifier": "Release",
"path": "src/main/java/dev/cele/asa_sm/dto/github/Release.java",
"snippet": "@Data\npublic class Release {\n private String id;\n private String html_url;\n private String tag_name;\n private String name;\n private Date published_at;\n private Asset[] assets;\n private String body;\n}"
},
{
"identifier": "GithubClient",
"path": "src/main/java/dev/cele/asa_sm/feign/GithubClient.java",
"snippet": "@FeignClient(name = \"github\", url = \"https://api.github.com\")\npublic interface GithubClient {\n\n @GetMapping(\"/repos/{owner}/{repo}/releases/latest\")\n Release getLatestRelease(@PathVariable String owner, @PathVariable String repo);\n\n}"
},
{
"identifier": "ProgressFrame",
"path": "src/main/java/dev/cele/asa_sm/ui/frames/ProgressFrame.java",
"snippet": "public class ProgressFrame extends JDialog {\n\n private final JLabel label = new JLabel();\n\n @Getter\n private final JProgressBar progressBar = new JProgressBar();\n\n public ProgressFrame(Frame owner, String title, String message, boolean indeterminate) {\n super(owner, title, true);\n setLocationRelativeTo(owner);\n\n label.setText(message == null ? \"\" : message);\n\n setLayout(new BorderLayout());\n\n add(label, BorderLayout.CENTER);\n add(progressBar, BorderLayout.SOUTH);\n\n if(!indeterminate) progressBar.setStringPainted(true);\n progressBar.setIndeterminate(indeterminate);\n\n pack();\n setSize(new Dimension(getWidth()+ 50, getHeight() + 20));\n setResizable(false);\n }\n\n public void setProgress(int progress, String message) {\n SwingUtilities.invokeLater(() -> {\n setProgress(progress);\n label.setText(message);\n });\n }\n\n public void setProgress(int progress) {\n SwingUtilities.invokeLater(() -> {\n progressBar.setValue(progress);\n });\n }\n\n public void setMessage(String message) {\n label.setText(message);\n }\n\n public void launch(Consumer<ProgressFrame> action) {\n new Thread(() -> {\n action.accept(this);\n setVisible(false);\n }).start();\n setVisible(true);\n }\n}"
}
] | import dev.cele.asa_sm.Const;
import dev.cele.asa_sm.dto.github.Release;
import dev.cele.asa_sm.feign.GithubClient;
import dev.cele.asa_sm.ui.frames.ProgressFrame;
import jakarta.annotation.PostConstruct;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.SystemUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Service;
import org.springframework.util.StreamUtils;
import org.springframework.web.client.RestTemplate;
import javax.swing.*;
import java.awt.*;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.Arrays;
import java.util.regex.Pattern; | 1,760 | package dev.cele.asa_sm.services;
@Service
@RequiredArgsConstructor
@Slf4j
public class UpdateService {
private final GithubClient githubClient;
@Getter
@Value("${application.version}")
private String currentVersion;
private String ignoredVersion = "";
{
try {
var ignoredVersionFile = Const.DATA_DIR.resolve("ignoredVersion.txt");
if(ignoredVersionFile.toFile().exists() && ignoredVersionFile.toFile().isFile()){
ignoredVersion = new String(Files.readAllBytes(ignoredVersionFile));
}
}catch (IOException e){
JOptionPane.showMessageDialog(null, "Error while reading ignoredVersion.txt: " + e.getMessage());
log.error("Error while reading ignoredVersion.txt: ", e);
}
}
public void checkForUpdates() {
Release latestRelease = null;
if(currentVersion.contains("-SNAPSHOT")){
//don't check update if this is a snapshot
log.info("This is a snapshot version, skipping update check");
return;
}
log.info("Checking for updates...");
try {
latestRelease = githubClient.getLatestRelease("celedev97", "asa-server-manager");
}catch (Exception e){
JOptionPane.showMessageDialog(null, "Error while checking for updates: " + e.getMessage());
log.error("Error while checking for updates: ", e);
}
assert latestRelease != null;
var newVersion = latestRelease.getTag_name();
if(ignoredVersion.equals(newVersion)){
return;
}
//regex for version number with optional starting v and with optional snapshot version, one capturing group for major, one for minor, one for patch
var versionRegex = Pattern.compile("v?(\\d+)\\.(\\d+)\\.(\\d+)");
var currentVersionMatcher = versionRegex.matcher(currentVersion);
var newVersionMatcher = versionRegex.matcher(newVersion);
//extract version numbers from version strings
currentVersionMatcher.find();
newVersionMatcher.find();
var currentMajor = Integer.parseInt(currentVersionMatcher.group(1));
var currentMinor = Integer.parseInt(currentVersionMatcher.group(2));
var currentPatch = Integer.parseInt(currentVersionMatcher.group(3));
var newMajor = Integer.parseInt(newVersionMatcher.group(1));
var newMinor = Integer.parseInt(newVersionMatcher.group(2));
var newPatch = Integer.parseInt(newVersionMatcher.group(3));
//check if new version is newer than current version
if(newMajor > currentMajor || newMinor > currentMinor || newPatch > currentPatch){
String[] options = new String[] {"Yes", "Ask me Later", "Ignore this version"};
int response = JOptionPane.showOptionDialog(
null,
"A new version of ASA Server Manager is available: " + newVersion + "\nDo you want to download it?",
"New Version Available",
JOptionPane.DEFAULT_OPTION,
JOptionPane.INFORMATION_MESSAGE,
null,
options,
options[0]
);
if(response == 0){
try {
downloadUpdate(latestRelease);
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Error while opening download link: " + e.getMessage());
log.error("Error while opening download link: ", e);
}
System.exit(0);
}else if(response == 2){
try {
Files.writeString(Const.DATA_DIR.resolve("ignoredVersion.txt"), newVersion);
} catch (IOException e) {
JOptionPane.showMessageDialog(null, "Error while writing ignoredVersion.txt: " + e.getMessage());
log.error("Error while writing ignoredVersion.txt: ", e);
}
}
}
}
@SneakyThrows
private void downloadUpdate(Release latestRelease) {
if(SystemUtils.IS_OS_WINDOWS){
var asset = Arrays.stream(latestRelease.getAssets())
.filter(a -> a.getName().endsWith(".exe"))
.findFirst()
.orElseThrow(() -> new RuntimeException("No exe asset found"));
log.info("Downloading update...");
InputStream input = new URL(asset.getBrowser_download_url()).openStream();
var tempFile = File.createTempFile("asa_sm_update", ".exe");
//file copy from input to tempFile with progress bar
FileOutputStream output = new FileOutputStream(tempFile);
| package dev.cele.asa_sm.services;
@Service
@RequiredArgsConstructor
@Slf4j
public class UpdateService {
private final GithubClient githubClient;
@Getter
@Value("${application.version}")
private String currentVersion;
private String ignoredVersion = "";
{
try {
var ignoredVersionFile = Const.DATA_DIR.resolve("ignoredVersion.txt");
if(ignoredVersionFile.toFile().exists() && ignoredVersionFile.toFile().isFile()){
ignoredVersion = new String(Files.readAllBytes(ignoredVersionFile));
}
}catch (IOException e){
JOptionPane.showMessageDialog(null, "Error while reading ignoredVersion.txt: " + e.getMessage());
log.error("Error while reading ignoredVersion.txt: ", e);
}
}
public void checkForUpdates() {
Release latestRelease = null;
if(currentVersion.contains("-SNAPSHOT")){
//don't check update if this is a snapshot
log.info("This is a snapshot version, skipping update check");
return;
}
log.info("Checking for updates...");
try {
latestRelease = githubClient.getLatestRelease("celedev97", "asa-server-manager");
}catch (Exception e){
JOptionPane.showMessageDialog(null, "Error while checking for updates: " + e.getMessage());
log.error("Error while checking for updates: ", e);
}
assert latestRelease != null;
var newVersion = latestRelease.getTag_name();
if(ignoredVersion.equals(newVersion)){
return;
}
//regex for version number with optional starting v and with optional snapshot version, one capturing group for major, one for minor, one for patch
var versionRegex = Pattern.compile("v?(\\d+)\\.(\\d+)\\.(\\d+)");
var currentVersionMatcher = versionRegex.matcher(currentVersion);
var newVersionMatcher = versionRegex.matcher(newVersion);
//extract version numbers from version strings
currentVersionMatcher.find();
newVersionMatcher.find();
var currentMajor = Integer.parseInt(currentVersionMatcher.group(1));
var currentMinor = Integer.parseInt(currentVersionMatcher.group(2));
var currentPatch = Integer.parseInt(currentVersionMatcher.group(3));
var newMajor = Integer.parseInt(newVersionMatcher.group(1));
var newMinor = Integer.parseInt(newVersionMatcher.group(2));
var newPatch = Integer.parseInt(newVersionMatcher.group(3));
//check if new version is newer than current version
if(newMajor > currentMajor || newMinor > currentMinor || newPatch > currentPatch){
String[] options = new String[] {"Yes", "Ask me Later", "Ignore this version"};
int response = JOptionPane.showOptionDialog(
null,
"A new version of ASA Server Manager is available: " + newVersion + "\nDo you want to download it?",
"New Version Available",
JOptionPane.DEFAULT_OPTION,
JOptionPane.INFORMATION_MESSAGE,
null,
options,
options[0]
);
if(response == 0){
try {
downloadUpdate(latestRelease);
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Error while opening download link: " + e.getMessage());
log.error("Error while opening download link: ", e);
}
System.exit(0);
}else if(response == 2){
try {
Files.writeString(Const.DATA_DIR.resolve("ignoredVersion.txt"), newVersion);
} catch (IOException e) {
JOptionPane.showMessageDialog(null, "Error while writing ignoredVersion.txt: " + e.getMessage());
log.error("Error while writing ignoredVersion.txt: ", e);
}
}
}
}
@SneakyThrows
private void downloadUpdate(Release latestRelease) {
if(SystemUtils.IS_OS_WINDOWS){
var asset = Arrays.stream(latestRelease.getAssets())
.filter(a -> a.getName().endsWith(".exe"))
.findFirst()
.orElseThrow(() -> new RuntimeException("No exe asset found"));
log.info("Downloading update...");
InputStream input = new URL(asset.getBrowser_download_url()).openStream();
var tempFile = File.createTempFile("asa_sm_update", ".exe");
//file copy from input to tempFile with progress bar
FileOutputStream output = new FileOutputStream(tempFile);
| var progressFrame = new ProgressFrame(null, "Downloading Update", "Downloading update...", false); | 3 | 2023-11-07 19:36:49+00:00 | 4k |
fredpena/barcamp2023 | src/main/java/dev/fredpena/barcamp/views/person/FormView.java | [
{
"identifier": "ConfirmationDialog",
"path": "src/main/java/dev/fredpena/barcamp/componect/ConfirmationDialog.java",
"snippet": "public class ConfirmationDialog extends Dialog {\n\n private H2 title;\n private Paragraph question;\n private final transient Consumer<Dialog> listener;\n\n public ConfirmationDialog(Consumer<Dialog> listener) {\n super();\n super.setModal(true);\n this.listener = listener;\n setTitle(\"Confirm:\");\n setQuestion(\"Are you sure you want to execute this action?\");\n\n final VerticalLayout dialogLayout = createDialogLayout();\n super.add(dialogLayout);\n }\n\n public ConfirmationDialog(String title, String content, Consumer<Dialog> listener) {\n super();\n super.setModal(true);\n this.listener = listener;\n setTitle(title);\n setQuestion(content);\n\n final VerticalLayout dialogLayout = createDialogLayout();\n super.add(dialogLayout);\n }\n\n public void setTitle(String title) {\n this.title = new H2(title);\n this.title.getStyle().set(\"margin\", \"var(--lumo-space-m) 0\")\n .set(\"font-size\", \"1.5em\").set(\"font-weight\", \"bold\");\n }\n\n public void setQuestion(String question) {\n this.question = new Paragraph(question);\n }\n\n public void show(HtmlContainer parent) {\n super.open();\n parent.add(this);\n }\n\n private VerticalLayout createDialogLayout() {\n final Button abort = new Button(\"Cancel\");\n abort.addClickListener(e -> super.close());\n\n final Button confirm = new Button(\"Confirm\", event -> listener.accept(this));\n confirm.addThemeVariants(ButtonVariant.LUMO_PRIMARY);\n\n final HorizontalLayout buttonLayout = new HorizontalLayout(abort, confirm);\n buttonLayout.setJustifyContentMode(FlexComponent.JustifyContentMode.END);\n\n final VerticalLayout dialogLayout = new VerticalLayout(title, question, buttonLayout);\n dialogLayout.setPadding(false);\n dialogLayout.setAlignItems(FlexComponent.Alignment.STRETCH);\n dialogLayout.getStyle().set(\"width\", \"300px\").set(\"max-width\", \"100%\");\n\n return dialogLayout;\n }\n\n}"
},
{
"identifier": "CustomNotification",
"path": "src/main/java/dev/fredpena/barcamp/componect/CustomNotification.java",
"snippet": "public class CustomNotification {\n\n private void notification(Notification notification, String msg) {\n notification.setDuration(3000);\n notification.setPosition(com.vaadin.flow.component.notification.Notification.Position.TOP_END);\n\n final Div text = new Div(new Text(msg));\n\n final Button closeButton = new Button(new Icon(\"lumo\", \"cross\"));\n closeButton.addThemeVariants(ButtonVariant.LUMO_TERTIARY_INLINE);\n closeButton.getElement().setAttribute(\"aria-label\", \"Close\");\n closeButton.addClickListener(event -> notification.close());\n\n final HorizontalLayout layout = new HorizontalLayout(text, closeButton);\n layout.setAlignItems(FlexComponent.Alignment.CENTER);\n\n notification.add(layout);\n notification.open();\n }\n\n public void notificationError() {\n notificationError(\"There was an error in the transaction.\");\n }\n\n public void notificationError(String msg) {\n final com.vaadin.flow.component.notification.Notification notification = new com.vaadin.flow.component.notification.Notification();\n notification.addThemeVariants(NotificationVariant.LUMO_ERROR);\n\n notification(notification, msg);\n }\n\n public void notificationError(ValidationException validationException) {\n notificationError(null, validationException);\n }\n\n public void notificationError(String msg, ValidationException validationException) {\n final com.vaadin.flow.component.notification.Notification notification = new com.vaadin.flow.component.notification.Notification();\n notification.addThemeVariants(NotificationVariant.LUMO_ERROR);\n\n if (msg != null) {\n notification(notification, msg);\n }\n\n validationException.getFieldValidationErrors().forEach(err ->\n err.getMessage().ifPresent(msg2 -> {\n String label = ((HasLabel) err.getBinding().getField()).getLabel();\n\n notificationError(label + \" -> \" + msg2);\n })\n );\n\n }\n\n public void notificationSuccess() {\n notificationSuccess(\"The transaction was successful.\");\n }\n\n public void notificationSuccess(String msg) {\n final com.vaadin.flow.component.notification.Notification notification = new com.vaadin.flow.component.notification.Notification();\n notification.addThemeVariants(NotificationVariant.LUMO_SUCCESS);\n\n notification(notification, msg);\n }\n\n public void notificationWarning(String msg) {\n final com.vaadin.flow.component.notification.Notification notification = new com.vaadin.flow.component.notification.Notification();\n notification.addThemeVariants(NotificationVariant.LUMO_PRIMARY);\n\n notification(notification, msg);\n }\n}"
},
{
"identifier": "Person",
"path": "src/main/java/dev/fredpena/barcamp/data/tenant/entity/Person.java",
"snippet": "@ToString\n@Getter\n@Setter\n@Entity\n@Audited(withModifiedFlag = true)\n@EqualsAndHashCode(of = \"code\", callSuper = false)\n@Table(name = \"person\", indexes = {@Index(columnList = \"firstName\"), @Index(columnList = \"lastName\"), @Index(columnList = \"email\")})\npublic class Person extends Auditable implements Serializable {\n\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private Long code;\n @NotNull\n @Column(length = 50)\n @Length(message = \"This field can not be blank.\", min = 1, max = 50)\n private String firstName;\n @NotNull\n @Column(length = 50)\n @Length(message = \"This field can not be blank.\", min = 1, max = 50)\n private String lastName;\n @Email\n @NotNull\n @Column(length = 100)\n @Length(message = \"This field can not be blank.\", min = 1, max = 50)\n private String email;\n @NotNull\n @Column(length = 50)\n @Length(message = \"This field can not be blank.\", min = 1, max = 50)\n private String phone;\n @NotNull(message = \"This field can not be blank.\")\n private LocalDate dateOfBirth;\n @NotNull\n @Column(length = 100)\n @Length(message = \"This field can not be blank.\", min = 1, max = 50)\n private String occupation;\n @NotNull\n @Column(length = 50)\n @Length(message = \"This field can not be blank.\", min = 1, max = 50)\n private String role;\n\n private boolean important;\n\n\n}"
},
{
"identifier": "PersonService",
"path": "src/main/java/dev/fredpena/barcamp/data/tenant/service/PersonService.java",
"snippet": "@Service\npublic class PersonService {\n\n private final PersonRepository repository;\n\n public PersonService(PersonRepository repository) {\n this.repository = repository;\n }\n\n public Optional<Person> get(Long id) {\n if (id == null) return Optional.empty();\n\n return repository.findById(id);\n }\n\n public Person update(Person entity) {\n return repository.save(entity);\n }\n\n public void delete(Long id) {\n repository.deleteById(id);\n }\n\n public Page<Person> list(Pageable pageable) {\n return repository.findAll(pageable);\n }\n\n public Page<Person> list(Pageable pageable, Specification<Person> filter) {\n return repository.findAll(filter, pageable);\n }\n\n public List<Person> findAll() {\n return repository.findAll();\n }\n\n public int count() {\n return (int) repository.count();\n }\n\n}"
}
] | import com.vaadin.flow.component.ClickEvent;
import com.vaadin.flow.component.Component;
import com.vaadin.flow.component.HtmlContainer;
import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.button.ButtonVariant;
import com.vaadin.flow.component.checkbox.Checkbox;
import com.vaadin.flow.component.combobox.ComboBox;
import com.vaadin.flow.component.datepicker.DatePicker;
import com.vaadin.flow.component.dialog.Dialog;
import com.vaadin.flow.component.formlayout.FormLayout;
import com.vaadin.flow.component.html.Div;
import com.vaadin.flow.component.html.Hr;
import com.vaadin.flow.component.orderedlayout.FlexComponent;
import com.vaadin.flow.component.orderedlayout.HorizontalLayout;
import com.vaadin.flow.component.textfield.EmailField;
import com.vaadin.flow.component.textfield.TextField;
import com.vaadin.flow.data.binder.BeanValidationBinder;
import com.vaadin.flow.data.binder.Binder;
import com.vaadin.flow.data.binder.ValidationException;
import com.vaadin.flow.theme.lumo.LumoUtility;
import dev.fredpena.barcamp.componect.ConfirmationDialog;
import dev.fredpena.barcamp.componect.CustomNotification;
import dev.fredpena.barcamp.data.tenant.entity.Person;
import dev.fredpena.barcamp.data.tenant.service.PersonService;
import jakarta.persistence.Column;
import jakarta.validation.constraints.NotNull;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional; | 2,227 | package dev.fredpena.barcamp.views.person;
public class FormView {
private final TextField firstName = new TextField("First Name");
private final TextField lastName = new TextField("Last Name");
private final EmailField email = new EmailField("Email");
private final TextField phone = new TextField("Phone Number");
private final DatePicker dateOfBirth = new DatePicker("Birthday");
private final TextField occupation = new TextField("Occupation");
private final ComboBox<String> fieldRole = new ComboBox<>("Role");
private final Checkbox important = new Checkbox("Is important?");
private final Button delete = new Button("Delete");
private final Button cancel = new Button("Cancel");
private final Button save = new Button("Save");
private final HtmlContainer parent;
private final PersonService personService;
private final CustomNotification notification; | package dev.fredpena.barcamp.views.person;
public class FormView {
private final TextField firstName = new TextField("First Name");
private final TextField lastName = new TextField("Last Name");
private final EmailField email = new EmailField("Email");
private final TextField phone = new TextField("Phone Number");
private final DatePicker dateOfBirth = new DatePicker("Birthday");
private final TextField occupation = new TextField("Occupation");
private final ComboBox<String> fieldRole = new ComboBox<>("Role");
private final Checkbox important = new Checkbox("Is important?");
private final Button delete = new Button("Delete");
private final Button cancel = new Button("Cancel");
private final Button save = new Button("Save");
private final HtmlContainer parent;
private final PersonService personService;
private final CustomNotification notification; | private Person element; | 2 | 2023-11-08 18:12:12+00:00 | 4k |
HexHive/Crystallizer | src/dynamic/SeriFuzz.java | [
{
"identifier": "GadgetVertexSerializable",
"path": "src/static/src/main/java/analysis/GadgetVertexSerializable.java",
"snippet": "public class GadgetVertexSerializable implements Serializable {\n final GadgetMethodSerializable node;\n\n public GadgetVertexSerializable(GadgetMethodSerializable node) {\n this.node = node;\n }\n\n public String toString() {\n return node.keyString();\n }\n\n public String getType() {\n return node.getType();\n }\n\n public String getClsName() {\n return node.getClsName();\n }\n\n public String getMethodSignature() {\n return node.getMethodSignature();\n }\n\n public String getQualifiedName() {\n return node.getQualifiedName();\n }\n\n\n public int hashCode() {\n return toString().hashCode();\n }\n \n public boolean equals(Object o) {\n return (o instanceof GadgetVertexSerializable) && (toString().equals(o.toString()));\n }\n}"
},
{
"identifier": "GadgetMethodSerializable",
"path": "src/static/src/main/java/analysis/GadgetMethodSerializable.java",
"snippet": "public class GadgetMethodSerializable implements Serializable {\n\n final String clsName; \n final String methodSignature; \n\tfinal String qualifiedName; // The method name constructed to allow for comparison against what is output by method method in java \n final String type; // Type of gadget [Source/Sink/Chain]\n\n // We setup the unique key as <clsName: methodName(methodParameters)>\n public String keyString() {\n return this.methodSignature;\n }\n\n GadgetMethodSerializable(String clsName, String methodSignature, String type, String qualifiedName) {\n this.clsName = clsName;\n this.methodSignature = methodSignature;\n this.qualifiedName = qualifiedName;\n this.type = type;\n }\n\n String getMethodSignature() {\n return this.methodSignature;\n }\n\n String getClsName() {\n return this.clsName;\n }\n\n String getType() {\n return this.type;\n }\n\n String getQualifiedName() {\n return this.qualifiedName;\n }\n\n}"
}
] | import com.code_intelligence.jazzer.api.FuzzedDataProvider;
import com.code_intelligence.jazzer.autofuzz.*;
import analysis.GadgetVertexSerializable;
import analysis.GadgetMethodSerializable;
import org.jgrapht.*;
import org.jgrapht.graph.*;
import org.jgrapht.traverse.*;
import org.jgrapht.alg.shortestpath.*;
import java.io.*;
import java.lang.reflect.Constructor;
import java.util.*;
import java.util.concurrent.ThreadLocalRandom;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator; | 1,908 | package com.example;
// import clojure.*;
// import org.apache.logging.log4j.Logger;
public class SeriFuzz {
// private static final FluentLogger logger = FluentLogger.forEnclosingClass();
private static final Logger LOGGER = Logger.getLogger(SeriFuzz.class);
private static String logProperties = "/root/SeriFuzz/src/dynamic/log4j.properties";
// This sinkID is used to identify is sink gadget is triggered
public static List<String> sinkIDs = new ArrayList<String>();
// This flag identifies if we are running the fuzzer in the dynamic sink identification mode
public static boolean isSinkIDMode = false;
// This flag identifiers if we are running the fuzzer in the crash triage mode
public static boolean isCrashTriageMode = false;
// This flag identifies if we are running the fuzzer to find DoS bugs
public static boolean isDosMode = false;
// This flag identifies if we are running the fuzzer to enumerate all candidate paths
public static boolean isPathEnumerationMode = false;
// This flag identifies if we are running the fuzzer without the aid of the gadget graph
public static boolean isNoGGMode = false;
// Specify the threshold time we put in to get new cov before we deem that the campaign has stalled
public static long thresholdTime = 3600;
// Specifies the maximum length of the chains that are to be found
public static int maxPathLength = 5;
public static boolean sinkTriggered;
// In case CrashTriage mode is enabled, we use this variable to keep track
// of which path is being triaged
public static int triagePathID;
public static void readMode() {
// This control string identifies which mode the dynamic analysis component should be run in.
// Available modes: SinkID, CrashTriage, Dos, PathEnumeration, NoGG, Fuzz
// This string is read from a file named `_crystallizer_mode` created in the
// directory pointed by TrackStatistics.storeDir
String crystallizerMode = null;
try {
BufferedReader br = new BufferedReader(new FileReader(TrackStatistics.storeDir + "_crystallizer_mode"));
crystallizerMode = br.readLine();
if (crystallizerMode.equals("SinkID")) {
LOGGER.info("Turning on sink ID mode");
// Read in the library being analyzed
BufferedReader br1 = new BufferedReader(new FileReader(TrackStatistics.storeDir + "_libname"));
DynamicSinkID.targetLibrary = br1.readLine();
isSinkIDMode = true;
} else if (crystallizerMode.equals("CrashTriage")) {
LOGGER.info("Turning on crash triage mode");
Scanner scanner = new Scanner(new File(TrackStatistics.storeDir + "_pathID"));
GadgetDB.currentPathID = scanner.nextInt();
LOGGER.info("Path ID to be triaged:" + GadgetDB.currentPathID);
// Read in the path ID that is to be triaged
isCrashTriageMode = true;
} else if (crystallizerMode.equals("Dos")) {
LOGGER.info("Turning on DOS mode");
isDosMode = true;
} else if (crystallizerMode.equals("PathEnumeration")) {
LOGGER.info("Turning on path enumeration mode");
isPathEnumerationMode = true;
} else if (crystallizerMode.equals("NoGG")) {
LOGGER.info("Turning on nogg mode");
isNoGGMode = true;
} else if (crystallizerMode.equals("Fuzz")) {
LOGGER.info("No specialized modes turned on, performing regular fuzzing");
} else {
LOGGER.info(String.format("Unknown mode found %s...exiting", crystallizerMode));
System.exit(1);
}
} catch (IOException e) {
LOGGER.info("Could not read crystallizer mode initiailizer..exiting");
System.exit(1);
}
}
public static void fuzzerInitialize(String[] args) {
PropertyConfigurator.configure(logProperties);
// Read in the mode in which Crystallizer is to be run
SeriFuzz.readMode();
LogCrash.makeCrashDir();
LogCrash.initJDKCrashedPaths();
TrackStatistics.logInitTimeStamp();
// ObjectFactory.populateClassCache();
if (isSinkIDMode) {
Meta.isSinkIDMode = true;
LOGGER.debug("Reinitializing vulnerable sinks found");
LogCrash.reinitVulnerableSinks();
// We do this to force init the class so that reachable classes are
// computed before the fuzz timeout is enforced
LOGGER.debug(String.format("Number of unique classes:%d", DynamicSinkID.uniqueClasses.length));
return;
}
if (isCrashTriageMode) {
LOGGER.debug("Running the fuzzer in crash triage mode");
Meta.isCrashTriageMode = true;
}
LogCrash.initCrashID();
GadgetDB.tagSourcesAndSinks();
// GadgetDB.findAllPaths();
if (! isSinkIDMode) {
GadgetDB.findAllPaths();
}
if (! isDosMode) {
TrackStatistics.initProgressCounters();
}
}
public static void fuzzerTestOneInput(FuzzedDataProvider data) {
if (Meta.isCrashTriageMode) {
Meta.constructionSteps.clear();
}
if (isPathEnumerationMode) {
// GadgetDB.showVertices();
GadgetDB.printAllPaths();
System.exit(1);
}
// Operating in the dynamic sink ID mode
if (isSinkIDMode) {
boolean didTest = DynamicSinkID.testPotentialSinks(data);
return;
}
// Operating in DoS bug discovery mode
if (isDosMode) {
DosChain.runAnalysis(data);
return;
}
// makeHookActive = false;
sinkTriggered = false;
Meta.localCache.clear(); | package com.example;
// import clojure.*;
// import org.apache.logging.log4j.Logger;
public class SeriFuzz {
// private static final FluentLogger logger = FluentLogger.forEnclosingClass();
private static final Logger LOGGER = Logger.getLogger(SeriFuzz.class);
private static String logProperties = "/root/SeriFuzz/src/dynamic/log4j.properties";
// This sinkID is used to identify is sink gadget is triggered
public static List<String> sinkIDs = new ArrayList<String>();
// This flag identifies if we are running the fuzzer in the dynamic sink identification mode
public static boolean isSinkIDMode = false;
// This flag identifiers if we are running the fuzzer in the crash triage mode
public static boolean isCrashTriageMode = false;
// This flag identifies if we are running the fuzzer to find DoS bugs
public static boolean isDosMode = false;
// This flag identifies if we are running the fuzzer to enumerate all candidate paths
public static boolean isPathEnumerationMode = false;
// This flag identifies if we are running the fuzzer without the aid of the gadget graph
public static boolean isNoGGMode = false;
// Specify the threshold time we put in to get new cov before we deem that the campaign has stalled
public static long thresholdTime = 3600;
// Specifies the maximum length of the chains that are to be found
public static int maxPathLength = 5;
public static boolean sinkTriggered;
// In case CrashTriage mode is enabled, we use this variable to keep track
// of which path is being triaged
public static int triagePathID;
public static void readMode() {
// This control string identifies which mode the dynamic analysis component should be run in.
// Available modes: SinkID, CrashTriage, Dos, PathEnumeration, NoGG, Fuzz
// This string is read from a file named `_crystallizer_mode` created in the
// directory pointed by TrackStatistics.storeDir
String crystallizerMode = null;
try {
BufferedReader br = new BufferedReader(new FileReader(TrackStatistics.storeDir + "_crystallizer_mode"));
crystallizerMode = br.readLine();
if (crystallizerMode.equals("SinkID")) {
LOGGER.info("Turning on sink ID mode");
// Read in the library being analyzed
BufferedReader br1 = new BufferedReader(new FileReader(TrackStatistics.storeDir + "_libname"));
DynamicSinkID.targetLibrary = br1.readLine();
isSinkIDMode = true;
} else if (crystallizerMode.equals("CrashTriage")) {
LOGGER.info("Turning on crash triage mode");
Scanner scanner = new Scanner(new File(TrackStatistics.storeDir + "_pathID"));
GadgetDB.currentPathID = scanner.nextInt();
LOGGER.info("Path ID to be triaged:" + GadgetDB.currentPathID);
// Read in the path ID that is to be triaged
isCrashTriageMode = true;
} else if (crystallizerMode.equals("Dos")) {
LOGGER.info("Turning on DOS mode");
isDosMode = true;
} else if (crystallizerMode.equals("PathEnumeration")) {
LOGGER.info("Turning on path enumeration mode");
isPathEnumerationMode = true;
} else if (crystallizerMode.equals("NoGG")) {
LOGGER.info("Turning on nogg mode");
isNoGGMode = true;
} else if (crystallizerMode.equals("Fuzz")) {
LOGGER.info("No specialized modes turned on, performing regular fuzzing");
} else {
LOGGER.info(String.format("Unknown mode found %s...exiting", crystallizerMode));
System.exit(1);
}
} catch (IOException e) {
LOGGER.info("Could not read crystallizer mode initiailizer..exiting");
System.exit(1);
}
}
public static void fuzzerInitialize(String[] args) {
PropertyConfigurator.configure(logProperties);
// Read in the mode in which Crystallizer is to be run
SeriFuzz.readMode();
LogCrash.makeCrashDir();
LogCrash.initJDKCrashedPaths();
TrackStatistics.logInitTimeStamp();
// ObjectFactory.populateClassCache();
if (isSinkIDMode) {
Meta.isSinkIDMode = true;
LOGGER.debug("Reinitializing vulnerable sinks found");
LogCrash.reinitVulnerableSinks();
// We do this to force init the class so that reachable classes are
// computed before the fuzz timeout is enforced
LOGGER.debug(String.format("Number of unique classes:%d", DynamicSinkID.uniqueClasses.length));
return;
}
if (isCrashTriageMode) {
LOGGER.debug("Running the fuzzer in crash triage mode");
Meta.isCrashTriageMode = true;
}
LogCrash.initCrashID();
GadgetDB.tagSourcesAndSinks();
// GadgetDB.findAllPaths();
if (! isSinkIDMode) {
GadgetDB.findAllPaths();
}
if (! isDosMode) {
TrackStatistics.initProgressCounters();
}
}
public static void fuzzerTestOneInput(FuzzedDataProvider data) {
if (Meta.isCrashTriageMode) {
Meta.constructionSteps.clear();
}
if (isPathEnumerationMode) {
// GadgetDB.showVertices();
GadgetDB.printAllPaths();
System.exit(1);
}
// Operating in the dynamic sink ID mode
if (isSinkIDMode) {
boolean didTest = DynamicSinkID.testPotentialSinks(data);
return;
}
// Operating in DoS bug discovery mode
if (isDosMode) {
DosChain.runAnalysis(data);
return;
}
// makeHookActive = false;
sinkTriggered = false;
Meta.localCache.clear(); | GraphPath<GadgetVertexSerializable, DefaultEdge> candidate = null; | 0 | 2023-11-07 22:03:19+00:00 | 4k |
wuyu-wy/mgzm_volunteer | volunteer/src/main/java/com/blbd/volunteer/service/impl/ChatFriendListServiceImpl.java | [
{
"identifier": "ChatFriendListEntity",
"path": "volunteer/src/main/java/com/blbd/volunteer/dao/entity/ChatFriendListEntity.java",
"snippet": "@Data\npublic class ChatFriendListEntity implements Serializable {\n /**\n * 聊天列表主键\n */\n private Integer listId;\n\n /**\n * 聊天主表id\n */\n private String linkId;\n\n /**\n * 发送者\n */\n private String senderId;\n\n /**\n * 接收者\n */\n private String receiverId;\n\n /**\n * 接收者头像\n */\n private String receiverPicture;\n\n /**\n * 发送方是否在窗口\n */\n private Integer senderIsOnline;\n\n /**\n * 接收方是否在窗口\n */\n private Integer receiverIsOnline;\n\n /**\n * 未读数\n */\n private Integer unread;\n\n /**\n * 是否删除\n */\n private Integer status;\n\n private static final long serialVersionUID = 1L;\n\n @Override\n public boolean equals(Object that) {\n if (this == that) {\n return true;\n }\n if (that == null) {\n return false;\n }\n if (getClass() != that.getClass()) {\n return false;\n }\n ChatFriendListEntity other = (ChatFriendListEntity) that;\n return (this.getListId() == null ? other.getListId() == null : this.getListId().equals(other.getListId()))\n && (this.getLinkId() == null ? other.getLinkId() == null : this.getLinkId().equals(other.getLinkId()))\n && (this.getSenderId() == null ? other.getSenderId() == null : this.getSenderId().equals(other.getSenderId()))\n && (this.getReceiverId() == null ? other.getReceiverId() == null : this.getReceiverId().equals(other.getReceiverId()))\n && (this.getReceiverPicture() == null ? other.getReceiverPicture() == null : this.getReceiverPicture().equals(other.getReceiverPicture()))\n && (this.getSenderIsOnline() == null ? other.getSenderIsOnline() == null : this.getSenderIsOnline().equals(other.getSenderIsOnline()))\n && (this.getReceiverIsOnline() == null ? other.getReceiverIsOnline() == null : this.getReceiverIsOnline().equals(other.getReceiverIsOnline()))\n && (this.getUnread() == null ? other.getUnread() == null : this.getUnread().equals(other.getUnread()))\n && (this.getStatus() == null ? other.getStatus() == null : this.getStatus().equals(other.getStatus()));\n }\n\n @Override\n public int hashCode() {\n final int prime = 31;\n int result = 1;\n result = prime * result + ((getListId() == null) ? 0 : getListId().hashCode());\n result = prime * result + ((getLinkId() == null) ? 0 : getLinkId().hashCode());\n result = prime * result + ((getSenderId() == null) ? 0 : getSenderId().hashCode());\n result = prime * result + ((getReceiverId() == null) ? 0 : getReceiverId().hashCode());\n result = prime * result + ((getReceiverPicture() == null) ? 0 : getReceiverPicture().hashCode());\n result = prime * result + ((getSenderIsOnline() == null) ? 0 : getSenderIsOnline().hashCode());\n result = prime * result + ((getReceiverIsOnline() == null) ? 0 : getReceiverIsOnline().hashCode());\n result = prime * result + ((getUnread() == null) ? 0 : getUnread().hashCode());\n result = prime * result + ((getStatus() == null) ? 0 : getStatus().hashCode());\n return result;\n }\n\n @Override\n public String toString() {\n StringBuilder sb = new StringBuilder();\n sb.append(getClass().getSimpleName());\n sb.append(\" [\");\n sb.append(\"Hash = \").append(hashCode());\n sb.append(\", listId=\").append(listId);\n sb.append(\", linkId=\").append(linkId);\n sb.append(\", senderId=\").append(senderId);\n sb.append(\", receiverId=\").append(receiverId);\n sb.append(\", receiverPicture=\").append(receiverPicture);\n sb.append(\", senderIsOnline=\").append(senderIsOnline);\n sb.append(\", receiverIsOnline=\").append(receiverIsOnline);\n sb.append(\", unread=\").append(unread);\n sb.append(\", status=\").append(status);\n sb.append(\", serialVersionUID=\").append(serialVersionUID);\n sb.append(\"]\");\n return sb.toString();\n }\n}"
},
{
"identifier": "ChatFriendListService",
"path": "volunteer/src/main/java/com/blbd/volunteer/service/ChatFriendListService.java",
"snippet": "public interface ChatFriendListService {\n\n // 添加至好友列表(双向添加)\n int addFriendList(ChatFriendListEntity chatFriendListEntity);\n\n //根据linkId删除好友列表(双向删除)\n int deleteByLinkId(ChatFriendListEntity chatFriendListEntity);\n\n //修改好友列表信息\n int modify(ChatFriendListEntity chatFriendListEntity);\n\n //通过用户id查询好友列表\n List<ChatFriendListEntity> selectMyListBySenderId(ChatFriendListEntity chatFriendListEntity);\n\n //通过linkId查询双向好友列表\n List<ChatFriendListEntity> selectTwoListByLinkId(ChatFriendListEntity chatFriendListEntity);\n\n //用户上线,修改所有receiver为用户id的在线信息\n boolean modifyOnline(ChatFriendListEntity chatFriendListEntity);\n\n boolean modifyOffline(ChatFriendListEntity chatFriendListEntity);\n\n}"
},
{
"identifier": "ChatFriendListEntityMapper",
"path": "volunteer/src/main/java/com/blbd/volunteer/dao/ChatFriendListEntityMapper.java",
"snippet": "@Mapper\n@Repository\npublic interface ChatFriendListEntityMapper {\n int insert(ChatFriendListEntity chatFriendListEntity);\n int deleteByLinkId(ChatFriendListEntity chatFriendListEntity);\n int modify(ChatFriendListEntity chatFriendListEntity);\n List<ChatFriendListEntity> selectBySenderId(ChatFriendListEntity chatFriendListEntity);\n List<ChatFriendListEntity> selectByLinkId(ChatFriendListEntity chatFriendListEntity);\n\n List<ChatFriendListEntity> selectByReceiverId(ChatFriendListEntity chatFriendListEntity);\n\n}"
}
] | import com.blbd.volunteer.dao.entity.ChatFriendListEntity;
import com.blbd.volunteer.service.ChatFriendListService;
import com.blbd.volunteer.dao.ChatFriendListEntityMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List; | 1,662 | package com.blbd.volunteer.service.impl;
/**
* @author [email protected]
* @description 针对表【chat_friend_list】的数据库操作Service实现
* @createDate 2023-11-05 15:51:06
*/
@Service
public class ChatFriendListServiceImpl implements ChatFriendListService {
@Autowired
ChatFriendListEntityMapper chatFriendListEntityMapper;
// 添加至好友列表(双向添加) | package com.blbd.volunteer.service.impl;
/**
* @author [email protected]
* @description 针对表【chat_friend_list】的数据库操作Service实现
* @createDate 2023-11-05 15:51:06
*/
@Service
public class ChatFriendListServiceImpl implements ChatFriendListService {
@Autowired
ChatFriendListEntityMapper chatFriendListEntityMapper;
// 添加至好友列表(双向添加) | public int addFriendList(ChatFriendListEntity chatFriendListEntity){ | 0 | 2023-11-02 05:55:45+00:00 | 4k |
baguchan/BetterWithAquatic | src/main/java/baguchan/better_with_aquatic/mixin/client/EntityPlayerSPMixin.java | [
{
"identifier": "BetterWithAquatic",
"path": "src/main/java/baguchan/better_with_aquatic/BetterWithAquatic.java",
"snippet": "public class BetterWithAquatic implements GameStartEntrypoint, ModInitializer {\n\n\tpublic static final String MOD_ID = \"better_with_aquatic\";\n\tprivate static final boolean enable_drowned;\n\tprivate static final boolean enable_swim;\n\tpublic static ConfigHandler config;\n\tstatic {\n\t\tProperties prop = new Properties();\n\t\tprop.setProperty(\"starting_block_id\", \"3200\");\n\t\tprop.setProperty(\"starting_item_id\", \"26000\");\n\t\tprop.setProperty(\"starting_entity_id\", \"600\");\n\t\tprop.setProperty(\"enable_swim\", \"true\");\n\t\tprop.setProperty(\"enable_drowned\", \"true\");\n\t\tconfig = new ConfigHandler(BetterWithAquatic.MOD_ID, prop);\n\t\tentityID = config.getInt(\"starting_entity_id\");\n\t\tenable_swim = config.getBoolean(\"enable_swim\");\n\t\tenable_drowned = config.getBoolean(\"enable_drowned\");\n\t\tconfig.updateConfig();\n\t}\n\n\tpublic static int entityID;\n\n\t@Override\n\tpublic void onInitialize() {\n\t\tNetworkHelper.register(SwimPacket.class, true, false);\n\t}\n\t@Override\n\tpublic void beforeGameStart() {\n\t\tBlock.lightBlock[Block.fluidWaterFlowing.id] = 1;\n\t\tBlock.lightBlock[Block.fluidWaterStill.id] = 1;\n\t\tModBlocks.createBlocks();\n\t\tModItems.onInitialize();\n\n\t\tEntityHelper.Core.createEntity(EntityFish.class, entityID, \"Fish\");\n\t\tEntityHelper.Core.createEntity(EntityAnglerFish.class, entityID + 1, \"AnglerFish\");\n\t\tEntityHelper.Core.createEntity(EntityDrowned.class, entityID + 2, \"Drowned\");\n\t\tEntityHelper.Core.createEntity(EntityFrog.class, entityID + 3, \"Frog\");\n\n\t\tMobInfoRegistry.register(EntityFish.class, \"section.better_with_aquatic.fish.name\", \"section.better_with_aquatic.fish.desc\", 3, 20, new MobInfoRegistry.MobDrop[]{new MobInfoRegistry.MobDrop(Item.foodFishRaw.getDefaultStack(), 1.0f, 1, 1)});\n\t\tMobInfoRegistry.register(EntityAnglerFish.class, \"section.better_with_aquatic.angler_fish.name\", \"section.better_with_aquatic.angler_fish.desc\", 3, 20, new MobInfoRegistry.MobDrop[]{new MobInfoRegistry.MobDrop(ModItems.small_bulb.getDefaultStack(), 1.0f, 1, 1)});\n\t\tMobInfoRegistry.register(EntityDrowned.class, \"section.better_with_aquatic.drowned.name\", \"section.better_with_aquatic.drowned.desc\", 20, 300, new MobInfoRegistry.MobDrop[]{new MobInfoRegistry.MobDrop(Item.cloth.getDefaultStack(), 0.66f, 1, 2)});\n\t\tMobInfoRegistry.register(EntityFrog.class, \"section.better_with_aquatic.frog.name\", \"section.better_with_aquatic.frog.desc\", 8, 0, new MobInfoRegistry.MobDrop[]{});\n\n\t\tStatList.mobEncounterStats.put(\"Fish\", new StatMob(0x1050000 + EntityDispatcher.getEntityID(EntityFish.class), \"stat.encounterMob\", \"Fish\").registerStat());\n\t\tStatList.mobEncounterStats.put(\"AnglerFish\", new StatMob(0x1050000 + EntityDispatcher.getEntityID(EntityAnglerFish.class), \"stat.encounterMob\", \"AnglerFish\").registerStat());\n\t\tStatList.mobEncounterStats.put(\"Drowned\", new StatMob(0x1050000 + EntityDispatcher.getEntityID(EntityDrowned.class), \"stat.encounterMob\", \"Drowned\").registerStat());\n\t\tStatList.mobEncounterStats.put(\"Frog\", new StatMob(0x1050000 + EntityDispatcher.getEntityID(EntityFrog.class), \"stat.encounterMob\", \"Frog\").registerStat());\n\t}\n\n\t@Override\n\tpublic void afterGameStart() {\n\t}\n\n\n\tpublic static boolean isEnableSwim() {\n\t\treturn enable_swim;\n\t}\n\n\tpublic static boolean isEnableDrowned() {\n\t\treturn enable_drowned;\n\t}\n}"
},
{
"identifier": "ISwiming",
"path": "src/main/java/baguchan/better_with_aquatic/api/ISwiming.java",
"snippet": "public interface ISwiming {\n\tvoid setSwimming(boolean swiming);\n\n\tboolean isSwimming();\n\n\tfloat getSwimAmount(float p_20999_);\n}"
}
] | import baguchan.better_with_aquatic.BetterWithAquatic;
import baguchan.better_with_aquatic.api.ISwiming;
import net.minecraft.client.Minecraft;
import net.minecraft.client.entity.player.EntityPlayerSP;
import net.minecraft.core.block.material.Material;
import net.minecraft.core.entity.player.EntityPlayer;
import net.minecraft.core.util.helper.MathHelper;
import net.minecraft.core.world.World;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.Unique;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; | 1,849 | package baguchan.better_with_aquatic.mixin.client;
@Mixin(value = EntityPlayerSP.class, remap = false)
public abstract class EntityPlayerSPMixin extends EntityPlayer implements ISwiming {
@Shadow
protected Minecraft mc;
@Unique
private boolean pressedSprint = false;
public EntityPlayerSPMixin(World world) {
super(world);
}
@Shadow
private boolean isBlockTranslucent(int i, int j, int k) {
return false;
}
@Inject(method = "checkInTile", at = @At(value = "HEAD"), cancellable = true)
protected void checkInTile(double d, double d1, double d2, CallbackInfoReturnable<Boolean> cir) {
if (!this.noPhysics && this.isSwimming()) {
int i = MathHelper.floor_double(d);
int j = MathHelper.floor_double(d1);
int k = MathHelper.floor_double(d2);
double d3 = d - (double) i;
double d4 = d2 - (double) k;
if (this.isBlockTranslucent(i, j, k)) {
boolean flag = !this.isBlockTranslucent(i - 1, j, k);
boolean flag1 = !this.isBlockTranslucent(i + 1, j, k);
boolean flag2 = !this.isBlockTranslucent(i, j, k - 1);
boolean flag3 = !this.isBlockTranslucent(i, j, k + 1);
int byte0 = -1;
double d5 = 9999.0;
if (flag && d3 < d5) {
d5 = d3;
byte0 = 0;
}
if (flag1 && 1.0 - d3 < d5) {
d5 = 1.0 - d3;
byte0 = 1;
}
if (flag2 && d4 < d5) {
d5 = d4;
byte0 = 4;
}
if (flag3 && 1.0 - d4 < d5) {
double d6 = 1.0 - d4;
byte0 = 5;
}
float f = 0.1f;
if (byte0 == 0) {
this.xd = -f;
}
if (byte0 == 1) {
this.xd = f;
}
if (byte0 == 4) {
this.zd = -f;
}
if (byte0 == 5) {
this.zd = f;
}
}
cir.setReturnValue(false);
}
}
@Inject(method = "onLivingUpdate", at = @At(value = "TAIL"))
public void onLivingUpdateSwiming(CallbackInfo ci) {
if (this.isUnderLiquid(Material.water) && !this.isSneaking()) { | package baguchan.better_with_aquatic.mixin.client;
@Mixin(value = EntityPlayerSP.class, remap = false)
public abstract class EntityPlayerSPMixin extends EntityPlayer implements ISwiming {
@Shadow
protected Minecraft mc;
@Unique
private boolean pressedSprint = false;
public EntityPlayerSPMixin(World world) {
super(world);
}
@Shadow
private boolean isBlockTranslucent(int i, int j, int k) {
return false;
}
@Inject(method = "checkInTile", at = @At(value = "HEAD"), cancellable = true)
protected void checkInTile(double d, double d1, double d2, CallbackInfoReturnable<Boolean> cir) {
if (!this.noPhysics && this.isSwimming()) {
int i = MathHelper.floor_double(d);
int j = MathHelper.floor_double(d1);
int k = MathHelper.floor_double(d2);
double d3 = d - (double) i;
double d4 = d2 - (double) k;
if (this.isBlockTranslucent(i, j, k)) {
boolean flag = !this.isBlockTranslucent(i - 1, j, k);
boolean flag1 = !this.isBlockTranslucent(i + 1, j, k);
boolean flag2 = !this.isBlockTranslucent(i, j, k - 1);
boolean flag3 = !this.isBlockTranslucent(i, j, k + 1);
int byte0 = -1;
double d5 = 9999.0;
if (flag && d3 < d5) {
d5 = d3;
byte0 = 0;
}
if (flag1 && 1.0 - d3 < d5) {
d5 = 1.0 - d3;
byte0 = 1;
}
if (flag2 && d4 < d5) {
d5 = d4;
byte0 = 4;
}
if (flag3 && 1.0 - d4 < d5) {
double d6 = 1.0 - d4;
byte0 = 5;
}
float f = 0.1f;
if (byte0 == 0) {
this.xd = -f;
}
if (byte0 == 1) {
this.xd = f;
}
if (byte0 == 4) {
this.zd = -f;
}
if (byte0 == 5) {
this.zd = f;
}
}
cir.setReturnValue(false);
}
}
@Inject(method = "onLivingUpdate", at = @At(value = "TAIL"))
public void onLivingUpdateSwiming(CallbackInfo ci) {
if (this.isUnderLiquid(Material.water) && !this.isSneaking()) { | if (BetterWithAquatic.isEnableSwim() && mc.gameSettings.keySprint.isPressed()) { | 0 | 2023-11-08 23:02:14+00:00 | 4k |
Suff99/ExtraShells | common/src/main/java/mc/craig/software/extra_shells/client/models/ShellEntryRegistry.java | [
{
"identifier": "ESModelRegistry",
"path": "common/src/main/java/mc/craig/software/extra_shells/ESModelRegistry.java",
"snippet": "public class ESModelRegistry {\n\n public static SeaBlueShellModel TOMMY_EXT_MODEL;\n public static EngineersShellModel ENGINEERS_EXT_MODEL;\n public static EllenShellModel ELLEN_EXT_MODEL;\n public static MoffatBoxShell MOFFAT_EXT_MODEL;\n public static RTDShellModel RTD_EXT_MODEL;\n public static ChibnallShellModel CHIBNALL_EXT_MODEL;\n public static GlasgowInspiredShellModel GLASGOW_EXT_MODEL;\n public static JackShellModel JACK_CUSTOM_EXT_MODEL;\n public static LegoIdeasShellModel LEGO_IDEAS_EXT_MODEL;\n\n public static HudolinShellModel HUDOLIN_EXT_MODEL;\n public static HudolinDoorModel HUDOLIN_INT_MODEL;\n public static ModelLayerLocation HUDOLIN_EXT, HUDOLIN_INT;\n\n public static SeaBlueDoorModel TOMMY_INT_MODEL;\n public static EngineerDoorModel ENGINEERS_INT_MODEL;\n public static EllenDoorModel ELLEN_INT_MODEL;\n public static MoffatDoorModel MOFFAT_INT_MODEL;\n public static RTDDoorModel RTD_INT_MODEL;\n public static ChibnallDoorModel CHIBNALL_INT_MODEL;\n public static RTD2DoorModel RTD2_INT_MODEL;\n public static GlasgowInspiredDoorModel GLASGOW_INT_MODEL;\n public static JackDoorModel JACK_CUSTOM_INT_MODEL;\n public static LegoIdeasDoorModel LEGO_IDEAS_INT_MODEL;\n\n public static ModelLayerLocation JACK_CUSTOM_EXT, TOMMY_EXT, ENGINEERS_EXT, ELLEN_EXT, MOFFAT_EXT, RTD_EXT, CHIBNALL_EXT, GLASGOW_EXT, LEGO_IDEAS_EXT;\n public static ModelLayerLocation JACK_CUSTOM_INT, TOMMY_INT, ENGINEERS_INT, ELLEN_INT, MOFFAT_INT, RTD_INT, RTD2_INT, CHIBNALL_INT, GLASGOW_INT, LEGO_IDEAS_INT;\n\n\n\n public static void init() {\n ENGINEERS_EXT = register(new ModelLayerLocation(new ResourceLocation(ExtraShells.MODID, \"engineers_ext\"), \"engineers_ext\"), EngineersShellModel::createBodyLayer);\n TOMMY_EXT = register(new ModelLayerLocation(new ResourceLocation(ExtraShells.MODID, \"tommy_ext\"), \"tommy_ext\"), SeaBlueShellModel::createBodyLayer);\n ELLEN_EXT = register(new ModelLayerLocation(new ResourceLocation(ExtraShells.MODID, \"ellen_ext\"), \"ellen_ext\"), EllenShellModel::createBodyLayer);\n MOFFAT_EXT = register(new ModelLayerLocation(new ResourceLocation(ExtraShells.MODID, \"moffat_ext\"), \"moffat_ext\"), MoffatBoxShell::createBodyLayer);\n RTD_EXT = register(new ModelLayerLocation(new ResourceLocation(ExtraShells.MODID, \"rtd_ext\"), \"rtd_ext\"), RTDShellModel::createBodyLayer);\n GLASGOW_EXT = register(new ModelLayerLocation(new ResourceLocation(ExtraShells.MODID, \"glasgow_ext\"), \"glasgow_ext\"), GlasgowInspiredShellModel::createBodyLayer);\n CHIBNALL_EXT = register(new ModelLayerLocation(new ResourceLocation(ExtraShells.MODID, \"chibnall_ext\"), \"chibnall_ext\"), ChibnallShellModel::createBodyLayer);\n JACK_CUSTOM_EXT = register(new ModelLayerLocation(new ResourceLocation(ExtraShells.MODID, \"jack_ext\"), \"jack_ext\"), JackShellModel::createBodyLayer);\n LEGO_IDEAS_EXT = register(new ModelLayerLocation(new ResourceLocation(ExtraShells.MODID, \"lego_ideas_ext\"), \"lego_ideas_ext\"), LegoIdeasShellModel::createBodyLayer);\n\n ENGINEERS_INT = register(new ModelLayerLocation(new ResourceLocation(ExtraShells.MODID, \"engineers_int\"), \"engineers_int\"), EngineerDoorModel::createBodyLayer);\n TOMMY_INT = register(new ModelLayerLocation(new ResourceLocation(ExtraShells.MODID, \"tommy_int\"), \"tommy_int\"), SeaBlueDoorModel::createBodyLayer);\n ELLEN_INT = register(new ModelLayerLocation(new ResourceLocation(ExtraShells.MODID, \"ellen_int\"), \"ellen_int\"), EllenDoorModel::createBodyLayer);\n MOFFAT_INT = register(new ModelLayerLocation(new ResourceLocation(ExtraShells.MODID, \"moffat_int\"), \"moffat_int\"), MoffatDoorModel::createBodyLayer);\n RTD_INT = register(new ModelLayerLocation(new ResourceLocation(ExtraShells.MODID, \"rtd_int\"), \"rtd_int\"), RTDDoorModel::createBodyLayer);\n GLASGOW_INT = register(new ModelLayerLocation(new ResourceLocation(ExtraShells.MODID, \"glasgow_int_model\"), \"glasgow_int_model\"), GlasgowInspiredDoorModel::createBodyLayer);\n CHIBNALL_INT = register(new ModelLayerLocation(new ResourceLocation(ExtraShells.MODID, \"chibnall_int_model\"), \"chibnall_int_model\"), ChibnallDoorModel::createBodyLayer);\n RTD2_INT = register(new ModelLayerLocation(new ResourceLocation(ExtraShells.MODID, \"rtd2_int_model\"), \"rtd2_int_model\"), RTD2DoorModel::createBodyLayer);\n JACK_CUSTOM_INT = register(new ModelLayerLocation(new ResourceLocation(ExtraShells.MODID, \"jack_int_model\"), \"jack_int_model\"), JackDoorModel::createBodyLayer);\n LEGO_IDEAS_INT = register(new ModelLayerLocation(new ResourceLocation(ExtraShells.MODID, \"lego_ideas_int\"), \"lego_ideas_int\"), LegoIdeasDoorModel::createBodyLayer);\n\n HUDOLIN_EXT = register(new ModelLayerLocation(new ResourceLocation(ExtraShells.MODID, \"hudolin_ext\"), \"hudolin_ext\"), HudolinShellModel::createBodyLayer);\n HUDOLIN_INT = register(new ModelLayerLocation(new ResourceLocation(ExtraShells.MODID, \"hudolin_int\"), \"hudolin_int\"), HudolinDoorModel::createBodyLayer);\n\n }\n\n public static void setupModelInstances(EntityModelSet entityModels) {\n\n // Shell\n ESModelRegistry.TOMMY_EXT_MODEL = new SeaBlueShellModel(entityModels.bakeLayer(ESModelRegistry.TOMMY_EXT));\n ESModelRegistry.ENGINEERS_EXT_MODEL = new EngineersShellModel(entityModels.bakeLayer(ESModelRegistry.ENGINEERS_EXT));\n ESModelRegistry.ELLEN_EXT_MODEL = new EllenShellModel(entityModels.bakeLayer(ESModelRegistry.ELLEN_EXT));\n ESModelRegistry.MOFFAT_EXT_MODEL = new MoffatBoxShell(entityModels.bakeLayer(ESModelRegistry.MOFFAT_EXT));\n ESModelRegistry.RTD_EXT_MODEL = new RTDShellModel(entityModels.bakeLayer(ESModelRegistry.RTD_EXT));\n ESModelRegistry.GLASGOW_EXT_MODEL = new GlasgowInspiredShellModel(entityModels.bakeLayer(ESModelRegistry.GLASGOW_EXT));\n ESModelRegistry.CHIBNALL_EXT_MODEL = new ChibnallShellModel(entityModels.bakeLayer(ESModelRegistry.CHIBNALL_EXT));\n ESModelRegistry.LEGO_IDEAS_EXT_MODEL = new LegoIdeasShellModel(entityModels.bakeLayer(ESModelRegistry.LEGO_IDEAS_EXT));\n ESModelRegistry.HUDOLIN_EXT_MODEL = new HudolinShellModel(entityModels.bakeLayer(ESModelRegistry.HUDOLIN_EXT));\n ESModelRegistry.JACK_CUSTOM_EXT_MODEL = new JackShellModel(entityModels.bakeLayer(ESModelRegistry.JACK_CUSTOM_EXT));\n ESModelRegistry.ELLEN_EXT_MODEL = new EllenShellModel(entityModels.bakeLayer(ESModelRegistry.ELLEN_EXT));\n\n // Interior Door\n ESModelRegistry.TOMMY_INT_MODEL = new SeaBlueDoorModel(entityModels.bakeLayer(ESModelRegistry.TOMMY_INT));\n ESModelRegistry.ENGINEERS_INT_MODEL = new EngineerDoorModel(entityModels.bakeLayer(ESModelRegistry.ENGINEERS_INT));\n ESModelRegistry.ELLEN_INT_MODEL = new EllenDoorModel(entityModels.bakeLayer(ESModelRegistry.ELLEN_INT));\n ESModelRegistry.MOFFAT_INT_MODEL = new MoffatDoorModel(entityModels.bakeLayer(ESModelRegistry.MOFFAT_INT));\n ESModelRegistry.GLASGOW_INT_MODEL = new GlasgowInspiredDoorModel(entityModels.bakeLayer(ESModelRegistry.GLASGOW_INT));\n ESModelRegistry.RTD_INT_MODEL = new RTDDoorModel(entityModels.bakeLayer(ESModelRegistry.RTD_INT));\n ESModelRegistry.CHIBNALL_INT_MODEL = new ChibnallDoorModel(entityModels.bakeLayer(ESModelRegistry.CHIBNALL_INT));\n ESModelRegistry.RTD2_INT_MODEL = new RTD2DoorModel(entityModels.bakeLayer(ESModelRegistry.RTD2_INT));\n ESModelRegistry.LEGO_IDEAS_INT_MODEL = new LegoIdeasDoorModel(entityModels.bakeLayer(ESModelRegistry.LEGO_IDEAS_INT));\n ESModelRegistry.HUDOLIN_INT_MODEL = new HudolinDoorModel(entityModels.bakeLayer(ESModelRegistry.HUDOLIN_EXT));\n ESModelRegistry.JACK_CUSTOM_INT_MODEL = new JackDoorModel(entityModels.bakeLayer(ESModelRegistry.JACK_CUSTOM_INT));\n ESModelRegistry.ELLEN_INT_MODEL = new EllenDoorModel(entityModels.bakeLayer(ESModelRegistry.ELLEN_INT));\n\n ShellEntryRegistry.init();\n }\n\n @ExpectPlatform\n public static ModelLayerLocation register(ModelLayerLocation location, Supplier<LayerDefinition> definitionSupplier) {\n throw new RuntimeException(PlatformWarning.addWarning(ESModelRegistry.class));\n }\n\n}"
},
{
"identifier": "ESShellRegistry",
"path": "common/src/main/java/mc/craig/software/extra_shells/ESShellRegistry.java",
"snippet": "public class ESShellRegistry {\n\n public static final DeferredRegistry<ShellTheme> SHELL_THEMES = DeferredRegistry.create(ExtraShells.MODID, ShellTheme.SHELL_THEME_REGISTRY_KEY);\n\n public static final RegistrySupplierHolder<ShellTheme, ShellTheme> ENGINEERS = registerShellTheme(\"engineers\");\n public static final RegistrySupplierHolder<ShellTheme, ShellTheme> SEA_BLUE = registerShellTheme(\"sea_blue\");\n public static final RegistrySupplierHolder<ShellTheme, ShellTheme> MOFFAT_ERA = registerShellTheme(\"moffat_era\");\n public static final RegistrySupplierHolder<ShellTheme, ShellTheme> RTD_ERA = registerShellTheme(\"rtd_era\");\n public static final RegistrySupplierHolder<ShellTheme, ShellTheme> GLASGOW = registerShellTheme(\"glasgow\");\n public static final RegistrySupplierHolder<ShellTheme, ShellTheme> LEGO = registerShellTheme(\"lego\");\n public static final RegistrySupplierHolder<ShellTheme, ShellTheme> HUDOLIN = registerShellTheme(\"hudolin\");\n public static final RegistrySupplierHolder<ShellTheme, ShellTheme> CHIBNALL_RTD_ERA = registerShellTheme(\"chibnall_rtd_era\");\n public static final RegistrySupplierHolder<ShellTheme, ShellTheme> JACK_CUSTOM = registerShellTheme(\"jack_custom\");\n public static final RegistrySupplierHolder<ShellTheme, ShellTheme> ELLEN = registerShellTheme(\"ellen\");\n\n\n public static final RegistrySupplierHolder<ShellTheme, ShellTheme> TRIGHT_JODIE = registerShellTheme(\"tright_jodie\");\n\n\n private static RegistrySupplierHolder<ShellTheme, ShellTheme> registerShellTheme(String id) {\n return SHELL_THEMES.registerHolder(id, () -> new ShellTheme(new ResourceLocation(ExtraShells.MODID, id)));\n }\n\n\n\n}"
}
] | import mc.craig.software.extra_shells.ESModelRegistry;
import mc.craig.software.extra_shells.ESShellRegistry;
import whocraft.tardis_refined.client.model.blockentity.shell.ShellModelCollection;
import whocraft.tardis_refined.common.tardis.themes.ShellTheme; | 2,714 | package mc.craig.software.extra_shells.client.models;
public class ShellEntryRegistry {
public static void init(){ | package mc.craig.software.extra_shells.client.models;
public class ShellEntryRegistry {
public static void init(){ | ShellModelCollection.registerShellEntry(ESShellRegistry.ENGINEERS.get(), ESModelRegistry.ENGINEERS_EXT_MODEL, ESModelRegistry.ENGINEERS_INT_MODEL); | 0 | 2023-11-04 22:53:31+00:00 | 4k |
Sorenon/GitCraft | src/main/java/com/example/mc/RepoBlockEntity.java | [
{
"identifier": "ExampleMod",
"path": "src/main/java/com/example/ExampleMod.java",
"snippet": "public class ExampleMod implements ModInitializer {\n public static final ResourceLocation OPEN_SCREEN = new ResourceLocation(\"gitcraft\", \"open_screen\");\n\n public static final RepoBlock REPO_BLOCK = new RepoBlock(BlockBehaviour.Properties.of());\n public static final BlockEntityType<RepoBlockEntity> REPO_BLOCK_ENTITY = FabricBlockEntityTypeBuilder.create(RepoBlockEntity::new, REPO_BLOCK).build();\n public static final BlockItem REPO_ITEM = new BlockItem(REPO_BLOCK, new Item.Properties());\n public static final Item RESET = new Item(new Item.Properties());\n public static final Item STATUS = new Item(new Item.Properties());\n\n @Override\n public void onInitialize() {\n CommandRegistrationCallback.EVENT.register((dispatcher, registryAccess, environment) -> {\n dispatcher.register(\n Commands.literal(\"git_init\").then(\n Commands.argument(\"from\", BlockPosArgument.blockPos()).then(\n Commands.argument(\"to\", BlockPosArgument.blockPos())\n .executes(\n commandContext -> createRepo(commandContext.getSource(), BoundingBox.fromCorners(BlockPosArgument.getLoadedBlockPos(commandContext, \"from\"), BlockPosArgument.getLoadedBlockPos(commandContext, \"to\")), null)\n ))));\n dispatcher.register(\n Commands.literal(\"git_clone\").then(\n Commands.argument(\"remote\", StringArgumentType.string()).then(\n Commands.argument(\"pos\", BlockPosArgument.blockPos())\n .executes(\n commandContext -> cloneRepo(commandContext.getSource(), BlockPosArgument.getLoadedBlockPos(commandContext, \"pos\"), StringArgumentType.getString(commandContext, \"remote\")))\n )));\n });\n\n\n Registry.register(BuiltInRegistries.ITEM, new ResourceLocation(\"gitcraft\", \"reset\"), RESET);\n Registry.register(BuiltInRegistries.ITEM, new ResourceLocation(\"gitcraft\", \"status\"), STATUS);\n Registry.register(BuiltInRegistries.ITEM, new ResourceLocation(\"gitcraft\", \"repo\"), REPO_ITEM);\n Registry.register(BuiltInRegistries.BLOCK, new ResourceLocation(\"gitcraft\", \"repo\"), REPO_BLOCK);\n Registry.register(BuiltInRegistries.BLOCK_ENTITY_TYPE, new ResourceLocation(\"gitcraft\", \"repo\"), REPO_BLOCK_ENTITY);\n }\n\n public static int createRepo(CommandSourceStack commandSourceStack, BoundingBox boundingBox, String remote) {\n var player = commandSourceStack.getPlayer();\n if (player != null) {\n var name = String.valueOf(new Random().nextLong());\n\n var stack = new ItemStack(REPO_ITEM);\n var tag = new CompoundTag();\n tag.putInt(\"x1\", boundingBox.minX());\n tag.putInt(\"x2\", boundingBox.maxX());\n tag.putInt(\"y1\", boundingBox.minY());\n tag.putInt(\"y2\", boundingBox.maxY());\n tag.putInt(\"z1\", boundingBox.minZ());\n tag.putInt(\"z2\", boundingBox.maxZ());\n tag.putString(\"name\", name);\n BlockItem.setBlockEntityData(stack, REPO_BLOCK_ENTITY, tag);\n player.addItem(stack);\n\n try {\n Git.init().setDirectory(repoDir(commandSourceStack.getLevel(), name).toFile()).call().close();\n commandSourceStack.sendSystemMessage(Component.literal(\"Repo created with id: \" + name));\n } catch (GitAPIException e) {\n throw new RuntimeException(e);\n }\n }\n return 1;\n }\n\n public static int cloneRepo(CommandSourceStack commandSourceStack, BlockPos pos, String remote) {\n var player = commandSourceStack.getPlayer();\n if (player != null) {\n var name = String.valueOf(new Random().nextLong());\n var path = repoDir(commandSourceStack.getLevel(), name);\n\n try {\n Git.cloneRepository().setURI(remote).setDirectory(path.toFile()).call().close();\n commandSourceStack.sendSystemMessage(Component.literal(\"Repo created with id: \" + name + \" from: \" + remote));\n } catch (GitAPIException e) {\n System.err.println(e);\n throw new RuntimeException(e);\n }\n\n try {\n StringReader reader = new StringReader(Files.readString(path.resolve(\"blocks.gc\")).lines().findFirst().get());\n int x = reader.readInt();\n reader.read();\n int y = reader.readInt();\n reader.read();\n int z = reader.readInt();\n\n var stack = new ItemStack(REPO_ITEM);\n var tag = new CompoundTag();\n tag.putInt(\"x1\", pos.getX());\n tag.putInt(\"x2\", pos.getX() + x);\n tag.putInt(\"y1\", pos.getY());\n tag.putInt(\"y2\", pos.getY() + y);\n tag.putInt(\"z1\", pos.getZ());\n tag.putInt(\"z2\", pos.getZ() + z);\n tag.putString(\"name\", name);\n BlockItem.setBlockEntityData(stack, REPO_BLOCK_ENTITY, tag);\n player.addItem(stack);\n\n } catch (IOException | CommandSyntaxException e) {\n throw new RuntimeException(e);\n }\n\n }\n return 1;\n }\n\n public static Path repoDir(ServerLevel serverLevel, String name) {\n return serverLevel.getServer().getWorldPath(LevelResource.ROOT).getParent().resolve(\"repos/\" + name);\n }\n}"
},
{
"identifier": "GCBlocks",
"path": "src/main/java/com/example/GCBlocks.java",
"snippet": "public class GCBlocks {\n public static BlockState[][][] load(String in, Vec3i size, Level level) throws CommandSyntaxException {\n BlockState[][][] blockStates = new BlockState[size.getX()][size.getY()][size.getZ()];\n\n boolean skip = true;\n\n for (var line : in.lines().toList()) {\n if (skip) {\n skip = false;\n continue;\n }\n var reader = new StringReader(line);\n int x = reader.readInt();\n reader.read();\n int y = reader.readInt();\n reader.read();\n int z = reader.readInt();\n reader.read();\n var blockState = NbtUtils.readBlockState(level.holderLookup(Registries.BLOCK), new TagParser(reader).readStruct());\n blockStates[x][y][z] = blockState;\n }\n\n return blockStates;\n }\n\n public static void load(Level level, BoundingBox boundingBox, Path path) throws IOException, CommandSyntaxException {\n var size = new Vec3i(boundingBox.getXSpan(), boundingBox.getYSpan(), boundingBox.getZSpan());\n var blocks = load(Files.readString(path), size, level);\n\n var bp = new BlockPos.MutableBlockPos();\n for (int x = 0; x < size.getX(); x++) {\n for (int y = 0; y < size.getY(); y++) {\n for (int z = 0; z < size.getZ(); z++) {\n if (blocks[x][y][z] != null) {\n level.setBlock(bp.set(boundingBox.minX(), boundingBox.minY(), boundingBox.minZ()).move(x, y, z), blocks[x][y][z], 2);\n } else {\n level.setBlock(bp.set(boundingBox.minX(), boundingBox.minY(), boundingBox.minZ()).move(x, y, z), Blocks.AIR.defaultBlockState(), 2);\n }\n }\n }\n }\n }\n\n public static void save(Level level, BoundingBox box, Path path) throws IOException {\n var str = save(level, box);\n Files.writeString(path, str);\n }\n\n public static String save(Level level, BoundingBox box) {\n var bp = new BlockPos.MutableBlockPos();\n var str = new StringBuilder();\n\n str.append(box.getXSpan());\n str.append(\",\");\n str.append(box.getYSpan());\n str.append(\",\");\n str.append(box.getZSpan());\n str.append(\"\\n\");\n\n for (int x = box.minX(); x < box.maxX() + 1; x++) {\n for (int y = box.minY(); y < box.maxY() + 1; y++) {\n for (int z = box.minZ(); z < box.maxZ() + 1; z++) {\n var blockState = level.getBlockState(bp.set(x, y, z));\n if (blockState.getBlock() instanceof RepoBlock) {\n blockState = Blocks.AIR.defaultBlockState();\n }\n str.append(x - box.minX());\n str.append(\",\");\n str.append(y - box.minY());\n str.append(\",\");\n str.append(z - box.minZ());\n str.append(\",\");\n str.append(NbtUtils.writeBlockState(blockState));\n str.append(\"\\n\");\n }\n }\n }\n return str.toString();\n }\n}"
}
] | import com.example.ExampleMod;
import com.example.GCBlocks;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import net.minecraft.core.BlockPos;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.network.chat.Component;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.levelgen.structure.BoundingBox;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.revwalk.RevCommit;
import java.io.IOException;
import java.nio.file.Path;
import java.util.Stack; | 2,728 | package com.example.mc;
public class RepoBlockEntity extends BlockEntity {
public BoundingBox boundingBox;
public String name;
public Git git;
public boolean powered;
public int cooldown = 0;
public Stack<RevCommit> replayingCommits = null;
public RepoBlockEntity(BlockPos blockPos, BlockState blockState) {
super(ExampleMod.REPO_BLOCK_ENTITY, blockPos, blockState);
}
@Override
public void load(CompoundTag compoundTag) {
if (compoundTag.contains("name")) {
boundingBox = new BoundingBox(
compoundTag.getInt("x1"),
compoundTag.getInt("y1"),
compoundTag.getInt("z1"),
compoundTag.getInt("x2"),
compoundTag.getInt("y2"),
compoundTag.getInt("z2")
);
name = compoundTag.getString("name");
}
powered = compoundTag.getBoolean("powered");
this.setLevel(level);
}
@Override
public void setLevel(Level level) {
super.setLevel(level);
if (level instanceof ServerLevel && this.name != null) {
if (this.boundingBox.isInside(this.getBlockPos().getX(), this.getBlockPos().getY(), this.getBlockPos().getZ())) {
level.setBlock(this.getBlockPos(), Blocks.AIR.defaultBlockState(), 2);
((ServerLevel) level).getServer().sendSystemMessage(Component.literal("Cannot place repo within boundaries"));
return;
}
if (git == null) {
try {
git = Git.open(this.getPath().toFile());
} catch (IOException e) {
System.err.println(e);
}
System.out.println(git);
}
}
}
public Path getPath() {
return ExampleMod.repoDir((ServerLevel) this.level, this.name);
}
@Override
protected void saveAdditional(CompoundTag tag) {
if (this.boundingBox != null) {
tag.putInt("x1", boundingBox.minX());
tag.putInt("x2", boundingBox.maxX());
tag.putInt("y1", boundingBox.minY());
tag.putInt("y2", boundingBox.maxY());
tag.putInt("z1", boundingBox.minZ());
tag.putInt("z2", boundingBox.maxZ());
tag.putString("name", name);
}
tag.putBoolean("powered", powered);
}
public void onUse(ServerPlayer serverPlayer, InteractionHand interactionHand) {
if (this.git == null) return;
var stack = serverPlayer.getItemInHand(interactionHand);
if (stack.getItem() == ExampleMod.RESET) {
try { | package com.example.mc;
public class RepoBlockEntity extends BlockEntity {
public BoundingBox boundingBox;
public String name;
public Git git;
public boolean powered;
public int cooldown = 0;
public Stack<RevCommit> replayingCommits = null;
public RepoBlockEntity(BlockPos blockPos, BlockState blockState) {
super(ExampleMod.REPO_BLOCK_ENTITY, blockPos, blockState);
}
@Override
public void load(CompoundTag compoundTag) {
if (compoundTag.contains("name")) {
boundingBox = new BoundingBox(
compoundTag.getInt("x1"),
compoundTag.getInt("y1"),
compoundTag.getInt("z1"),
compoundTag.getInt("x2"),
compoundTag.getInt("y2"),
compoundTag.getInt("z2")
);
name = compoundTag.getString("name");
}
powered = compoundTag.getBoolean("powered");
this.setLevel(level);
}
@Override
public void setLevel(Level level) {
super.setLevel(level);
if (level instanceof ServerLevel && this.name != null) {
if (this.boundingBox.isInside(this.getBlockPos().getX(), this.getBlockPos().getY(), this.getBlockPos().getZ())) {
level.setBlock(this.getBlockPos(), Blocks.AIR.defaultBlockState(), 2);
((ServerLevel) level).getServer().sendSystemMessage(Component.literal("Cannot place repo within boundaries"));
return;
}
if (git == null) {
try {
git = Git.open(this.getPath().toFile());
} catch (IOException e) {
System.err.println(e);
}
System.out.println(git);
}
}
}
public Path getPath() {
return ExampleMod.repoDir((ServerLevel) this.level, this.name);
}
@Override
protected void saveAdditional(CompoundTag tag) {
if (this.boundingBox != null) {
tag.putInt("x1", boundingBox.minX());
tag.putInt("x2", boundingBox.maxX());
tag.putInt("y1", boundingBox.minY());
tag.putInt("y2", boundingBox.maxY());
tag.putInt("z1", boundingBox.minZ());
tag.putInt("z2", boundingBox.maxZ());
tag.putString("name", name);
}
tag.putBoolean("powered", powered);
}
public void onUse(ServerPlayer serverPlayer, InteractionHand interactionHand) {
if (this.git == null) return;
var stack = serverPlayer.getItemInHand(interactionHand);
if (stack.getItem() == ExampleMod.RESET) {
try { | GCBlocks.load(level, this.boundingBox, this.getPath().resolve("blocks.gc")); | 1 | 2023-11-05 03:18:32+00:00 | 4k |
Svydovets-Bobocode-Java-Ultimate-3-0/Bring | src/test/java/com/bobocode/svydovets/ioc/util/NameResolverTest.java | [
{
"identifier": "resolveBeanName",
"path": "src/main/java/svydovets/util/NameResolver.java",
"snippet": "public static String resolveBeanName(Class<?> beanClass) {\n log.trace(\"Call resolveBeanName({}) for class base bean\", beanClass);\n if (beanClass.isAnnotationPresent(RestController.class)) {\n var beanValue = beanClass.getAnnotation(RestController.class).value();\n if (!beanValue.isEmpty()) {\n return beanValue;\n }\n }\n\n if (beanClass.isAnnotationPresent(Configuration.class)) {\n var beanValue = beanClass.getAnnotation(Configuration.class).value();\n if (!beanValue.isEmpty()) {\n return beanValue;\n }\n }\n\n if (beanClass.isAnnotationPresent(Component.class)) {\n var beanValue = beanClass.getAnnotation(Component.class).value();\n if (!beanValue.isEmpty()) {\n return beanValue;\n }\n }\n\n String beanName = setFirstCharacterToLowercase(beanClass.getSimpleName());\n log.trace(\"Bean name is not specified explicitly, simple class name has been used {}\", beanName);\n\n return beanName;\n}"
},
{
"identifier": "resolveRequestParameterName",
"path": "src/main/java/svydovets/util/NameResolver.java",
"snippet": "public static String resolveRequestParameterName(Parameter parameter) {\n if (parameter.isAnnotationPresent(PathVariable.class)) {\n var parameterName = parameter.getAnnotation(PathVariable.class).value();\n if (!parameterName.isEmpty()) {\n return parameterName;\n }\n }\n\n if (parameter.isAnnotationPresent(RequestParam.class)) {\n var parameterName = parameter.getAnnotation(RequestParam.class).value();\n if (!parameterName.isEmpty()) {\n return parameterName;\n }\n }\n return parameter.getName();\n}"
},
{
"identifier": "CommonService",
"path": "src/test/java/com/bobocode/svydovets/source/base/CommonService.java",
"snippet": "@Component\npublic class CommonService {\n}"
},
{
"identifier": "MessageService",
"path": "src/test/java/com/bobocode/svydovets/source/base/MessageService.java",
"snippet": "@Component(\"messageService\")\npublic class MessageService {\n private String message;\n\n public String getMessage() {\n return message;\n }\n\n public void setMessage(String message) {\n this.message = message;\n }\n}"
},
{
"identifier": "BasePackageBeansConfig",
"path": "src/test/java/com/bobocode/svydovets/source/config/BasePackageBeansConfig.java",
"snippet": "@Configuration\n@ComponentScan(\"com.bobocode.svydovets.source.base\")\npublic class BasePackageBeansConfig {\n}"
},
{
"identifier": "BasePackageWithAdditionalBeansConfig",
"path": "src/test/java/com/bobocode/svydovets/source/config/BasePackageWithAdditionalBeansConfig.java",
"snippet": "@Configuration\n@ComponentScan(\"com.bobocode.svydovets.source.base\")\npublic class BasePackageWithAdditionalBeansConfig {\n\n @Bean(\"megaTrimService\")\n public TrimService trimService() {\n return new TrimService();\n }\n\n @Bean\n public OrderService orderService() {\n return new OrderService();\n }\n\n @Bean\n @Scope\n public CopyService copyService() {\n return new CopyService();\n }\n\n @Bean\n @Scope(ApplicationContext.SCOPE_PROTOTYPE)\n public PrintLnService printLnService() {\n return new PrintLnService();\n }\n}"
},
{
"identifier": "NonInterfaceConfiguration",
"path": "src/test/java/com/bobocode/svydovets/source/interfaces/NonInterfaceConfiguration.java",
"snippet": "@Configuration(\"mainConfig\")\npublic class NonInterfaceConfiguration {\n}"
},
{
"identifier": "AllMethodRestController",
"path": "src/test/java/com/bobocode/svydovets/source/web/AllMethodRestController.java",
"snippet": "@RestController\n@RequestMapping(\"/method\")\npublic class AllMethodRestController {\n\n @GetMapping(\"/get\")\n public void doGetMethod() {\n System.out.println(\"doGetMethod\");\n }\n\n @PostMapping(\"/post\")\n public void doPostMethod() {\n System.out.println(\"doPostMethod\");\n }\n\n @PutMapping(\"/put\")\n public void doPutMethod() {\n System.out.println(\"doPostMethod\");\n }\n\n @DeleteMapping(\"/delete\")\n public void doDeleteMethod() {\n System.out.println(\"doDeleteMethod\");\n }\n\n @PatchMapping(\"/patch\")\n public void doPatchMethod() {\n System.out.println(\"doPatchMethod\");\n }\n\n}"
},
{
"identifier": "SimpleRestController",
"path": "src/test/java/com/bobocode/svydovets/source/web/SimpleRestController.java",
"snippet": "@RestController(\"simpleContr\")\n@RequestMapping(\"/simple\")\npublic class SimpleRestController {\n\n @GetMapping(\"/hello/{name}\")\n public void helloPath(@PathVariable String name) {\n System.out.println(name);\n }\n\n @GetMapping(\"/goodbye/{name}\")\n public void goodbyePath(@PathVariable(\"bye\") String goodbye) {\n System.out.println(goodbye);\n }\n\n @GetMapping(\"/hello\")\n public void helloRequest(@RequestParam String name) {\n System.out.println(name);\n }\n\n @GetMapping(\"/goodbye\")\n public void goodbyeRequest(@RequestParam(\"bye\") String goodbye) {\n System.out.println(goodbye);\n }\n\n}"
}
] | import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
import static svydovets.util.NameResolver.resolveBeanName;
import static svydovets.util.NameResolver.resolveRequestParameterName;
import java.util.Arrays;
import com.bobocode.svydovets.source.base.CommonService;
import com.bobocode.svydovets.source.base.MessageService;
import com.bobocode.svydovets.source.config.BasePackageBeansConfig;
import com.bobocode.svydovets.source.config.BasePackageWithAdditionalBeansConfig;
import com.bobocode.svydovets.source.interfaces.NonInterfaceConfiguration;
import com.bobocode.svydovets.source.web.AllMethodRestController;
import com.bobocode.svydovets.source.web.SimpleRestController;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import svydovets.core.annotation.Bean;
import svydovets.core.annotation.Component;
import svydovets.core.annotation.Configuration;
import svydovets.web.annotation.PathVariable;
import svydovets.web.annotation.RequestParam;
import svydovets.web.annotation.RestController; | 1,673 | package com.bobocode.svydovets.ioc.util;
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
public class NameResolverTest {
@Test
@Order(1)
public void shouldReturnComponentAnnotationValueIfNameIsSpecifiedExplicitly() {
String beanName = MessageService.class.getAnnotation(Component.class).value();
assertThat(beanName).isEqualTo(resolveBeanName(MessageService.class));
}
@Test
@Order(2)
public void shouldReturnSimpleClassNameIfComponentAnnotationValueIsNotSpecifiedExplicitly() {
String beanName = "commonService";
assertThat(beanName).isEqualTo(resolveBeanName(CommonService.class));
}
@Test
@Order(3)
public void shouldReturnConfigurationAnnotationValueIfNameIsSpecifiedExplicitly() {
String beanName = NonInterfaceConfiguration.class.getAnnotation(Configuration.class).value();
assertThat(beanName).isEqualTo(resolveBeanName(NonInterfaceConfiguration.class));
}
@Test
@Order(4)
public void shouldReturnSimpleClassNameIfConfigurationAnnotationValueIsNotSpecifiedExplicitly() {
String beanName = "basePackageBeansConfig"; | package com.bobocode.svydovets.ioc.util;
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
public class NameResolverTest {
@Test
@Order(1)
public void shouldReturnComponentAnnotationValueIfNameIsSpecifiedExplicitly() {
String beanName = MessageService.class.getAnnotation(Component.class).value();
assertThat(beanName).isEqualTo(resolveBeanName(MessageService.class));
}
@Test
@Order(2)
public void shouldReturnSimpleClassNameIfComponentAnnotationValueIsNotSpecifiedExplicitly() {
String beanName = "commonService";
assertThat(beanName).isEqualTo(resolveBeanName(CommonService.class));
}
@Test
@Order(3)
public void shouldReturnConfigurationAnnotationValueIfNameIsSpecifiedExplicitly() {
String beanName = NonInterfaceConfiguration.class.getAnnotation(Configuration.class).value();
assertThat(beanName).isEqualTo(resolveBeanName(NonInterfaceConfiguration.class));
}
@Test
@Order(4)
public void shouldReturnSimpleClassNameIfConfigurationAnnotationValueIsNotSpecifiedExplicitly() {
String beanName = "basePackageBeansConfig"; | assertThat(beanName).isEqualTo(resolveBeanName(BasePackageBeansConfig.class)); | 4 | 2023-11-07 06:36:50+00:00 | 4k |
oneqxz/RiseLoader | src/main/java/me/oneqxz/riseloader/fxml/components/impl/controllers/UpdatingController.java | [
{
"identifier": "RiseLoaderMain",
"path": "src/main/java/me/oneqxz/riseloader/RiseLoaderMain.java",
"snippet": "public class RiseLoaderMain {\n\n private static final Logger log = LogManager.getLogger(\"RiseLoader\");\n\n public static void main(String[] args) {\n log.info(\"Starting RiseLoader...\");\n\n if(!OSUtils.getRiseFolder().toFile().exists())\n OSUtils.getRiseFolder().toFile().mkdirs();\n\n RiseUI.main(new String[0]);\n }\n\n}"
},
{
"identifier": "RiseUI",
"path": "src/main/java/me/oneqxz/riseloader/RiseUI.java",
"snippet": "public class RiseUI extends Application {\n\n private static final Logger log = LogManager.getLogger(\"RiseLoader\");\n public static final Version version = new Version(\"1.0.8\");\n public static final String serverIp = \"http://riseloader.0x22.xyz\";\n public static final SimpleObjectProperty<Image> backgroundImage = new SimpleObjectProperty<Image>();\n\n @Override\n public void start(Stage stage) throws IOException {\n loadBackgroundImage();\n if(!Elua.getElua().isEluaAccepted())\n {\n new EluaAccept(() -> {try{load(stage);}catch (Exception e){e.printStackTrace();System.exit(0);}}).show();\n }\n else\n {\n load(stage);\n }\n }\n\n private void load(Stage stage) throws IOException\n {\n Loading loading = new Loading();\n Stage loadingStage = loading.show(true);\n\n loading.setStageText(\"Detecting os\");\n if(OSUtils.getOS() == OSUtils.OS.UNDEFINED)\n {\n log.info(\"Cannot detect OS!\");\n loadingStage.close();\n new ErrorBox().show(new IllegalStateException(\"Can't detect OS! \" + OSUtils.getOS().name()));\n }\n else\n {\n log.info(\"Detected OS: \" + OSUtils.getOS().name());\n }\n\n loading.setStageText(\"Initializing DiscordRPC\");\n DiscordRichPresence.getInstance();\n loading.setStageText(\"DiscordRPC ready\");\n\n Thread thread = new Thread(() ->\n {\n loading.setStageTextLater(\"Fetching scripts\");\n PublicInstance.getInstance();\n\n loading.setStageTextLater(\"Parsing settings\");\n Settings.getSettings();\n\n loading.setStageTextLater(\"Fetching rise files\");\n log.info(\"Getting Rise information...\");\n Response resp = null;\n try {\n resp = Requests.get(serverIp + \"/loader\");\n } catch (IOException e) {\n e.printStackTrace();\n\n Platform.runLater(() -> {\n loadingStage.close();\n new ErrorBox().show(e);\n });\n\n return;\n }\n if(resp.getStatusCode() == 200)\n {\n try {\n loading.setStageTextLater(\"Parsing rise files\");\n log.info(resp.getStatusCode() + \", writing info\");\n JSONObject json = resp.getJSON();\n\n JSONObject files = json.getJSONObject(\"files\");\n JSONObject client = json.getJSONObject(\"client\");\n\n if(version.needToUpdate(client.getString(\"loader_version\")))\n {\n loading.setStageTextLater(\"Updating...\");\n log.info(\"New version detected! Updating...\");\n try {\n Platform.runLater(() ->\n {\n Loading.close(loadingStage);\n try {\n new Updater().show();\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n });\n return;\n }\n catch (Exception e)\n {\n new ErrorBox().show(e);\n loadingStage.close();\n e.printStackTrace();\n }\n }\n\n JSONObject versions = client.getJSONObject(\"versions\");\n\n PublicBeta publicBeta = new PublicBeta(versions.getJSONObject(\"beta\").getString(\"version\"), versions.getJSONObject(\"beta\").getLong(\"lastUpdated\"));\n loading.setStageTextLater(\"Parsed Public beta version\");\n Release release = new Release(versions.getJSONObject(\"release\").getString(\"version\"), versions.getJSONObject(\"release\").getLong(\"lastUpdated\"));\n loading.setStageTextLater(\"Parsed Release version\");\n\n RiseInfo.createNew(\n files.getJSONObject(\"natives\"),\n files.getJSONObject(\"java\"),\n files.getJSONObject(\"rise\"),\n new ClientInfo(publicBeta, release, client.getString(\"release_changelog\"), client.getString(\"loader_version\")),\n client.getString(\"discord_invite\"),\n () -> {return client.getJSONObject(\"startup\").getString(\"normal\");},\n () -> {return client.getJSONObject(\"startup\").getString(\"optimized\");}\n );\n\n loading.setStageTextLater(\"Finalizing...\");\n Platform.runLater(() ->\n {\n try {\n Loading.close(loadingStage);\n MainScene.createScene(stage);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n });\n }\n catch (Exception e)\n {\n Platform.runLater(() -> {\n loadingStage.close();\n new ErrorBox().show(e);\n });\n }\n }\n else\n {\n Platform.runLater(() -> {\n loadingStage.close();\n new ErrorBox().show(new RuntimeException(\"/loader returned invalid status code\"));\n });\n }\n });\n thread.start();\n }\n\n private static void loadBackgroundImage()\n {\n String customImage = Settings.getSettings().getString(\"personalization.background\", null);\n Image image = null;\n\n if(customImage == null || !new File(OSUtils.getRiseFolder().toFile(), \".config\\\\\" + customImage).exists() || new Image(\"file:///\" + new File(OSUtils.getRiseFolder().toFile(), \".config\\\\\" + customImage)).isError())\n image = new Image(\"/background.jpg\");\n else\n image = new Image(\"file:///\" + new File(OSUtils.getRiseFolder().toFile(), \".config\\\\\" + customImage));\n\n backgroundImage.setValue(image);\n\n }\n\n public static void main(String[] args) {\n Runtime.getRuntime().addShutdownHook(new Thread(() ->\n {\n if(DiscordRichPresence.isRegistered())\n DiscordRichPresence.getInstance().shutdown();\n }));\n launch();\n }\n}"
},
{
"identifier": "ErrorBox",
"path": "src/main/java/me/oneqxz/riseloader/fxml/components/impl/ErrorBox.java",
"snippet": "public class ErrorBox extends Component {\n @Override\n public Stage show(Object... args) {\n try {\n Stage stage = new Stage();\n FX.showScene(\"RiseLoader error\", \"error.fxml\", stage, new ErrorBoxController((Throwable) args[0]));\n FX.setMinimizeAndClose(stage, \"minimizeBtn\", \"closeBtn\", args.length == 1 || (boolean) args[1]);\n FX.setDraggable(stage.getScene(), \"riseLogo\");\n stage.setIconified(false);\n return stage;\n }\n catch (Exception e)\n {\n throw new RuntimeException(e);\n }\n }\n}"
},
{
"identifier": "Controller",
"path": "src/main/java/me/oneqxz/riseloader/fxml/controllers/Controller.java",
"snippet": "public abstract class Controller {\n\n protected Parent root;\n protected Stage stage;\n\n public void init(Parent root, Stage stage)\n {\n this.root = root;\n this.stage = stage;\n this.init();\n }\n\n protected abstract void init();\n\n protected void onlyNumbers(TextInputControl text)\n {\n text.textProperty().addListener((observable, oldValue, newValue) -> {\n if (!newValue.matches(\"\\\\d*\")) {\n text.setText(newValue.replaceAll(\"[^\\\\d]\", \"\"));\n }\n });\n }\n\n protected void rangedInput(TextInputControl text, int min, int max)\n {\n text.textProperty().addListener((observable, oldValue, newValue) -> {\n try\n {\n if(newValue.isEmpty())\n {\n return;\n }\n\n int i = Integer.parseInt(newValue);\n if(i < min)\n text.setText(String.valueOf(min));\n else if(i > max)\n text.setText(String.valueOf(max));\n }\n catch (Exception e)\n {\n\n }\n });\n }\n\n protected void callPatternMath(TextInputControl text, String regex, CallRangeMath runnable)\n {\n text.textProperty().addListener((observable, oldValue, newValue) -> {\n runnable.call(Pattern.compile(regex).matcher(newValue).matches());\n });\n }\n\n public interface CallRangeMath {\n void call(boolean isMath);\n }\n}"
},
{
"identifier": "OSUtils",
"path": "src/main/java/me/oneqxz/riseloader/utils/OSUtils.java",
"snippet": "public class OSUtils {\n\n public static OS getOS()\n {\n String os = System.getProperty(\"os.name\").toLowerCase();\n if(os.contains(\"win\"))\n return OS.WINDOWS;\n else if(os.contains(\"mac\"))\n return OS.MACOS;\n else if(os.contains(\"nix\") || os.contains(\"nux\") || os.indexOf(\"aix\") > 0)\n return OS.LINUX;\n else\n return OS.UNDEFINED;\n }\n\n public static Path getRiseFolder()\n {\n return Path.of(System.getProperty(\"user.home\"), \".rise\");\n }\n\n public static String getFileExtension(Path path) {\n String fileName = path.getFileName().toString();\n int index = fileName.lastIndexOf('.');\n if (index > 0 && index < fileName.length() - 1) {\n return fileName.substring(index);\n }\n return \"\";\n }\n\n public enum OS {\n WINDOWS,\n LINUX,\n MACOS,\n UNDEFINED\n }\n}"
},
{
"identifier": "Requests",
"path": "src/main/java/me/oneqxz/riseloader/utils/requests/Requests.java",
"snippet": "public class Requests {\n\n public static Response get(String serverUrl) throws IOException {\n URL url = new URL(serverUrl);\n HttpURLConnection connection = (HttpURLConnection) url.openConnection();\n connection.setRequestMethod(\"GET\");\n setHeaders(connection);\n\n int responseCode = connection.getResponseCode();\n\n InputStream inputStream = connection.getInputStream();\n ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();\n byte[] buffer = new byte[1024];\n int bytesRead;\n\n while ((bytesRead = inputStream.read(buffer)) != -1) {\n byteArrayOutputStream.write(buffer, 0, bytesRead);\n }\n\n byte[] content = byteArrayOutputStream.toByteArray();\n\n inputStream.close();\n byteArrayOutputStream.close();\n connection.disconnect();\n\n return new Response(content, responseCode);\n }\n\n\n public static void setHeaders(HttpURLConnection connection)\n {\n connection.setRequestProperty(\"rise-0x22\", \"0x22/8cycbi9360M54qUu5cMZYRNjvpw69pYBVaSFDKQbfEfRyHoukC3nqUu5\");\n connection.setRequestProperty(\"User-Agent\", \"0x22/\" + RiseUI.version.getVersion());\n }\n\n}"
}
] | import javafx.application.Platform;
import javafx.scene.control.ProgressBar;
import me.oneqxz.riseloader.RiseLoaderMain;
import me.oneqxz.riseloader.RiseUI;
import me.oneqxz.riseloader.fxml.components.impl.ErrorBox;
import me.oneqxz.riseloader.fxml.controllers.Controller;
import me.oneqxz.riseloader.utils.OSUtils;
import me.oneqxz.riseloader.utils.requests.Requests;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Random; | 2,798 | package me.oneqxz.riseloader.fxml.components.impl.controllers;
public class UpdatingController extends Controller {
ProgressBar mainProgress;
@Override
protected void init() {
this.mainProgress = (ProgressBar) root.lookup("#mainProgress");
new Thread(() ->
{
try {
String currentFilePath = this.getClass().getProtectionDomain().getCodeSource().getLocation().toURI().getPath();
String tempFilePath = "update" + new Random().nextInt(10000) + ".temp_jar";
| package me.oneqxz.riseloader.fxml.components.impl.controllers;
public class UpdatingController extends Controller {
ProgressBar mainProgress;
@Override
protected void init() {
this.mainProgress = (ProgressBar) root.lookup("#mainProgress");
new Thread(() ->
{
try {
String currentFilePath = this.getClass().getProtectionDomain().getCodeSource().getLocation().toURI().getPath();
String tempFilePath = "update" + new Random().nextInt(10000) + ".temp_jar";
| downloadUpdate(RiseUI.serverIp + "/file/loader.jar", tempFilePath); | 1 | 2023-11-01 01:40:52+00:00 | 4k |
YufiriaMazenta/CrypticLib | nms/v1_18_R1/src/main/java/crypticlib/nms/tile/v1_18_R1/V1_18_R1NbtTileEntity.java | [
{
"identifier": "V1_18_R1NbtTagCompound",
"path": "nms/v1_18_R1/src/main/java/crypticlib/nms/nbt/v1_18_R1/V1_18_R1NbtTagCompound.java",
"snippet": "public class V1_18_R1NbtTagCompound extends NbtTagCompound {\n\n public V1_18_R1NbtTagCompound() {\n super(V1_18_R1NbtTranslator.INSTANCE);\n }\n\n public V1_18_R1NbtTagCompound(Object nmsNbtCompound) {\n super(nmsNbtCompound, V1_18_R1NbtTranslator.INSTANCE);\n }\n\n public V1_18_R1NbtTagCompound(Map<String, Object> nbtValueMap) {\n super(nbtValueMap, V1_18_R1NbtTranslator.INSTANCE);\n }\n\n public V1_18_R1NbtTagCompound(String mojangson) {\n super(mojangson, V1_18_R1NbtTranslator.INSTANCE);\n }\n\n @Override\n public void fromNms(@NotNull Object nmsNbt) {\n NBTTagCompound nms = (NBTTagCompound) nmsNbt;\n for (String key : nms.d()) {\n nbtMap.put(key, nbtTranslator.translateNmsNbt(nms.c(key)));\n }\n }\n\n @Override\n public @NotNull NBTTagCompound toNms() {\n NBTTagCompound nbtTagCompound = new NBTTagCompound();\n for (String key : nbtMap.keySet()) {\n nbtTagCompound.a(key, (NBTBase) get(key).toNms());\n }\n return nbtTagCompound;\n }\n\n @Override\n public void fromMojangson(String mojangson) {\n try {\n fromNms(MojangsonParser.a(mojangson));\n } catch (Throwable e) {\n throw new RuntimeException(e);\n }\n }\n\n @Override\n public NbtTagCompound clone() {\n return new V1_18_R1NbtTagCompound(toString());\n }\n\n}"
},
{
"identifier": "NbtTileEntity",
"path": "nms/common/src/main/java/crypticlib/nms/tile/NbtTileEntity.java",
"snippet": "public abstract class NbtTileEntity {\n\n protected BlockState bukkit;\n protected NbtTagCompound nbtTagCompound;\n\n public NbtTileEntity(BlockState bukkit) {\n this.bukkit = bukkit;\n fromBukkit();\n }\n\n public BlockState bukkit() {\n return bukkit;\n }\n\n public void setBukkit(TileState bukkit) {\n this.bukkit = bukkit;\n }\n\n public NbtTagCompound nbtTagCompound() {\n return nbtTagCompound;\n }\n\n public void setNbtTagCompound(NbtTagCompound nbtTagCompound) {\n this.nbtTagCompound = nbtTagCompound;\n }\n\n public abstract void saveNbtToTileEntity();\n\n public abstract void fromBukkit();\n\n}"
},
{
"identifier": "ReflectUtil",
"path": "common/src/main/java/crypticlib/util/ReflectUtil.java",
"snippet": "public class ReflectUtil {\n\n public static Field getField(@NotNull Class<?> clazz, @NotNull String fieldName) {\n try {\n return clazz.getField(fieldName);\n } catch (NoSuchFieldException e) {\n throw new RuntimeException(e);\n }\n }\n\n public static Field getDeclaredField(@NotNull Class<?> clazz, @NotNull String fieldName) {\n try {\n return clazz.getDeclaredField(fieldName);\n } catch (NoSuchFieldException e) {\n throw new RuntimeException(e);\n }\n }\n\n public static Object getFieldObj(@NotNull Field field, @Nullable Object owner) {\n try {\n return field.get(owner);\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }\n\n public static Object getDeclaredFieldObj(@NotNull Field field, @Nullable Object owner) {\n try {\n field.setAccessible(true);\n return field.get(owner);\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }\n\n public static Method getMethod(@NotNull Class<?> clazz, @NotNull String methodName, Class<?>... argClasses) {\n try {\n return clazz.getMethod(methodName, argClasses);\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }\n\n public static Method getDeclaredMethod(@NotNull Class<?> clazz, @NotNull String methodName, Class<?>... argClasses) {\n try {\n return clazz.getDeclaredMethod(methodName, argClasses);\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }\n\n public static Object invokeMethod(@NotNull Method method, @Nullable Object invokeObj, Object... args) {\n try {\n method.setAccessible(true);\n return method.invoke(invokeObj, args);\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }\n\n public static Object invokeDeclaredMethod(@NotNull Method method, @Nullable Object invokeObj, Object... args) {\n try {\n method.setAccessible(true);\n return method.invoke(invokeObj, args);\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }\n\n public static <T> Constructor<T> getConstructor(@NotNull Class<T> clazz, Class<?>... argClasses) {\n try {\n return clazz.getConstructor(argClasses);\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }\n\n public static <T> Constructor<T> getDeclaredConstructor(@NotNull Class<T> obj, Class<?>... argClasses) {\n try {\n return obj.getDeclaredConstructor(argClasses);\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }\n\n public static <T> T invokeConstructor(@NotNull Constructor<T> constructor, Object... args) {\n try {\n return constructor.newInstance(args);\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }\n\n public static <T> T invokeDeclaredConstructor(@NotNull Constructor<T> constructor, Object... args) {\n try {\n constructor.setAccessible(true);\n return constructor.newInstance(args);\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }\n\n public static <T> T newInstance(Class<T> clazz, Object... args) {\n Class<?>[] argClasses = new Class[args.length];\n for (int i = 0; i < args.length; i++) {\n argClasses[i] = args[i].getClass();\n }\n Constructor<T> constructor = getConstructor(clazz, argClasses);\n return invokeConstructor(constructor, args);\n }\n\n public static <T> T newDeclaredInstance(Class<T> clazz, Object... args) {\n Class<?>[] argClasses = new Class[args.length];\n for (int i = 0; i < args.length; i++) {\n argClasses[i] = args[i].getClass();\n }\n Constructor<T> constructor = getDeclaredConstructor(clazz, argClasses);\n return invokeDeclaredConstructor(constructor, args);\n }\n\n}"
}
] | import crypticlib.nms.nbt.v1_18_R1.V1_18_R1NbtTagCompound;
import crypticlib.nms.tile.NbtTileEntity;
import crypticlib.util.ReflectUtil;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.world.level.block.entity.TileEntity;
import org.bukkit.block.BlockState;
import org.bukkit.craftbukkit.v1_18_R1.block.CraftBlockEntityState;
import java.lang.reflect.Method; | 1,920 | package crypticlib.nms.tile.v1_18_R1;
public class V1_18_R1NbtTileEntity extends NbtTileEntity {
public V1_18_R1NbtTileEntity(BlockState bukkit) {
super(bukkit);
}
@Override
public void saveNbtToTileEntity() {
CraftBlockEntityState<?> craftTileEntity = ((CraftBlockEntityState<?>) bukkit); | package crypticlib.nms.tile.v1_18_R1;
public class V1_18_R1NbtTileEntity extends NbtTileEntity {
public V1_18_R1NbtTileEntity(BlockState bukkit) {
super(bukkit);
}
@Override
public void saveNbtToTileEntity() {
CraftBlockEntityState<?> craftTileEntity = ((CraftBlockEntityState<?>) bukkit); | Method getSnapshotMethod = ReflectUtil.getDeclaredMethod(CraftBlockEntityState.class, "getSnapshot"); | 2 | 2023-11-07 12:39:20+00:00 | 4k |
Traben-0/resource_explorer | common/src/main/java/traben/resource_explorer/explorer/REResourceFile.java | [
{
"identifier": "SpriteAtlasTextureAccessor",
"path": "common/src/main/java/traben/resource_explorer/mixin/SpriteAtlasTextureAccessor.java",
"snippet": "@Mixin(SpriteAtlasTexture.class)\npublic interface SpriteAtlasTextureAccessor {\n @Accessor\n int getWidth();\n\n @Accessor\n int getHeight();\n}"
},
{
"identifier": "outputResourceToPackInternal",
"path": "common/src/main/java/traben/resource_explorer/explorer/REExplorer.java",
"snippet": "@SuppressWarnings(\"ResultOfMethodCallIgnored\")\nstatic boolean outputResourceToPackInternal(REResourceFile reResourceFile) {\n //only save existing file resources\n if (reResourceFile.resource == null)\n return false;\n\n Path resourcePackFolder = MinecraftClient.getInstance().getResourcePackDir();\n File thisPackFolder = new File(resourcePackFolder.toFile(), \"resource_explorer/\");\n\n if (validateOutputResourcePack(thisPackFolder)) {\n if (thisPackFolder.exists()) {\n File assets = new File(thisPackFolder, \"assets\");\n if (!assets.exists()) {\n assets.mkdir();\n }\n File namespace = new File(assets, reResourceFile.identifier.getNamespace());\n if (!namespace.exists()) {\n namespace.mkdir();\n }\n String[] pathList = reResourceFile.identifier.getPath().split(\"/\");\n String file = pathList[pathList.length - 1];\n String directories = reResourceFile.identifier.getPath().replace(file, \"\");\n File directoryFolder = new File(namespace, directories);\n if (!directoryFolder.exists()) {\n directoryFolder.mkdirs();\n }\n if (directoryFolder.exists()) {\n\n File outputFile = new File(directoryFolder, file);\n try {\n byte[] buffer = reResourceFile.resource.getInputStream().readAllBytes();\n OutputStream outStream = new FileOutputStream(outputFile);\n outStream.write(buffer);\n IOUtils.closeQuietly(outStream);\n return true;\n } catch (IOException e) {\n e.printStackTrace();\n ResourceExplorerClient.log(\" Exporting resource file failed for: \" + reResourceFile.identifier);\n }\n }\n }\n }\n return false;\n}"
}
] | import net.minecraft.client.MinecraftClient;
import net.minecraft.client.font.MultilineText;
import net.minecraft.client.texture.AbstractTexture;
import net.minecraft.client.texture.NativeImage;
import net.minecraft.client.texture.NativeImageBackedTexture;
import net.minecraft.client.texture.SpriteAtlasTexture;
import net.minecraft.resource.Resource;
import net.minecraft.resource.metadata.ResourceMetadata;
import net.minecraft.text.OrderedText;
import net.minecraft.text.Text;
import net.minecraft.util.Identifier;
import org.jetbrains.annotations.Nullable;
import traben.resource_explorer.mixin.SpriteAtlasTextureAccessor;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;
import static traben.resource_explorer.explorer.REExplorer.outputResourceToPackInternal; | 2,250 | }
@Override
public int hashCode() {
return Objects.hash(identifier);
}
@Override
boolean canExport() {
return resource != null;
}
@Override
public String toString() {
return toString(0);
}
@Override
public String toString(int indent) {
return " ".repeat(Math.max(0, indent)) + "\\ " +
displayName + "\n";
}
@Override
public String getDisplayName() {
return displayName;
}
@Override
OrderedText getDisplayText() {
return displayText;
}
@Override
List<Text> getExtraText(boolean smallMode) {
ArrayList<Text> lines = new ArrayList<>();
lines.add(trimmedTextToWidth(" " + translated("resource_explorer.detail.type") + ": " + fileType.toString() +
(hasMetaData ? " + " + translated("resource_explorer.detail.metadata") : "")));
if (resource != null) {
lines.add(trimmedTextToWidth(" " + translated("resource_explorer.detail.pack") + ": " + resource.getResourcePackName().replace("file/", "")));
} else {
lines.add(trimmedTextToWidth("§8§o " + translated("resource_explorer.detail.built_msg")));
}
if (smallMode) return lines;
switch (fileType) {
case PNG -> {
lines.add(trimmedTextToWidth(" " + translated("resource_explorer.detail.height") + ": " + height));
lines.add(trimmedTextToWidth(" " + translated("resource_explorer.detail.width") + ": " + width));
if (hasMetaData && height > width && height % width == 0) {
lines.add(trimmedTextToWidth(" " + translated("resource_explorer.detail.frame_count") + ": " + (height / width)));
}
}
case TXT, PROPERTIES, JSON -> {
if (readTextByLineBreaks != null) {
lines.add(trimmedTextToWidth(" " + translated("resource_explorer.detail.lines") + ": " + height));
lines.add(trimmedTextToWidth(" " + translated("resource_explorer.detail.character_count") + ": " + width));
}
}
default -> {
}//lines.add(trimmedTextToWidth(" //todo "));//todo
}
return lines;
}
MultilineText getTextLines() {
if (!fileType.isRawTextType())
return MultilineText.EMPTY;
if (readTextByLineBreaks == null) {
if (resource != null) {
try {
InputStream in = resource.getInputStream();
try {
ArrayList<Text> text = new ArrayList<>();
String readString = new String(in.readAllBytes(), StandardCharsets.UTF_8);
in.close();
//make tabs smaller
String reducedTabs = readString.replaceAll("(\t| {4})", " ");
String[] splitByLines = reducedTabs.split("\n");
width = readString.length();
height = splitByLines.length;
//trim lines to width now
for (int i = 0; i < splitByLines.length; i++) {
splitByLines[i] = trimmedStringToWidth(splitByLines[i], 178);
}
int lineCount = 0;
for (String line :
splitByLines) {
lineCount++;
if (lineCount > 512) {//todo set limit in config
text.add(Text.of("§l§4-- TEXT LONGER THAN " + 512 + " LINES --"));
text.add(Text.of("§r§o " + (height - lineCount) + " lines skipped."));
text.add(Text.of("§l§4-- END --"));
break;
}
text.add(Text.of(line));
}
readTextByLineBreaks = MultilineText.createFromTexts(MinecraftClient.getInstance().textRenderer, text);
} catch (Exception e) {
//resource.close();
in.close();
readTextByLineBreaks = MultilineText.EMPTY;
}
} catch (Exception ignored) {
readTextByLineBreaks = MultilineText.EMPTY;
}
} else {
readTextByLineBreaks = MultilineText.create(MinecraftClient.getInstance().textRenderer, Text.of(" ERROR: no file info could be read"));
}
}
return readTextByLineBreaks;
}
public void exportToOutputPack(REExplorer.REExportContext context) { | package traben.resource_explorer.explorer;
public class REResourceFile extends REResourceEntry {
public static final REResourceFile FAILED_FILE = new REResourceFile();
public final Identifier identifier;
@Nullable
public final Resource resource;
public final FileType fileType;
public final LinkedList<String> folderStructureList;
final AbstractTexture abstractTexture;
private final String displayName;
private final OrderedText displayText;
public MultilineText readTextByLineBreaks = null;
public int height = 1;
public int width = 1;
boolean imageDone = false;
Boolean hasMetaData = null;
private REResourceFile() {
//failed file
this.identifier = new Identifier("search_failed:fail");
this.resource = null;
this.abstractTexture = null;
this.fileType = FileType.OTHER;
displayName = "search_failed";
folderStructureList = new LinkedList<>();
this.displayText = Text.of("search_failed").asOrderedText();
}
public REResourceFile(Identifier identifier, AbstractTexture texture) {
this.identifier = identifier;
this.resource = null;
this.abstractTexture = texture;
//try to capture some sizes
if (abstractTexture instanceof SpriteAtlasTexture atlasTexture) {
width = ((SpriteAtlasTextureAccessor) atlasTexture).getWidth();
height = ((SpriteAtlasTextureAccessor) atlasTexture).getHeight();
} else if (abstractTexture instanceof NativeImageBackedTexture nativeImageBackedTexture) {
NativeImage image = nativeImageBackedTexture.getImage();
if (image != null) {
width = image.getWidth();
height = image.getHeight();
}
}
this.fileType = FileType.getType(this.identifier);
//split out folder hierarchy
String[] splitDirectories = this.identifier.getPath().split("/");
LinkedList<String> directories = new LinkedList<>(List.of(splitDirectories));
//final entry is display file name
displayName = directories.getLast();
directories.removeLast();
//remainder is folder hierarchy, which can be empty
folderStructureList = directories;
this.displayText = trimmedTextToWidth(displayName).asOrderedText();
}
public REResourceFile(Identifier identifier, @Nullable Resource resource) {
this.identifier = identifier;
this.resource = resource;
this.abstractTexture = null;
this.fileType = FileType.getType(this.identifier);
//split out folder hierarchy
String[] splitDirectories = this.identifier.getPath().split("/");
LinkedList<String> directories = new LinkedList<>(List.of(splitDirectories));
//final entry is display file name
displayName = directories.getLast();
directories.removeLast();
//remainder is folder hierarchy, which can be empty
folderStructureList = directories;
this.displayText = trimmedTextToWidth(displayName).asOrderedText();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
REResourceFile that = (REResourceFile) o;
return identifier.equals(that.identifier);
}
@Override
public int hashCode() {
return Objects.hash(identifier);
}
@Override
boolean canExport() {
return resource != null;
}
@Override
public String toString() {
return toString(0);
}
@Override
public String toString(int indent) {
return " ".repeat(Math.max(0, indent)) + "\\ " +
displayName + "\n";
}
@Override
public String getDisplayName() {
return displayName;
}
@Override
OrderedText getDisplayText() {
return displayText;
}
@Override
List<Text> getExtraText(boolean smallMode) {
ArrayList<Text> lines = new ArrayList<>();
lines.add(trimmedTextToWidth(" " + translated("resource_explorer.detail.type") + ": " + fileType.toString() +
(hasMetaData ? " + " + translated("resource_explorer.detail.metadata") : "")));
if (resource != null) {
lines.add(trimmedTextToWidth(" " + translated("resource_explorer.detail.pack") + ": " + resource.getResourcePackName().replace("file/", "")));
} else {
lines.add(trimmedTextToWidth("§8§o " + translated("resource_explorer.detail.built_msg")));
}
if (smallMode) return lines;
switch (fileType) {
case PNG -> {
lines.add(trimmedTextToWidth(" " + translated("resource_explorer.detail.height") + ": " + height));
lines.add(trimmedTextToWidth(" " + translated("resource_explorer.detail.width") + ": " + width));
if (hasMetaData && height > width && height % width == 0) {
lines.add(trimmedTextToWidth(" " + translated("resource_explorer.detail.frame_count") + ": " + (height / width)));
}
}
case TXT, PROPERTIES, JSON -> {
if (readTextByLineBreaks != null) {
lines.add(trimmedTextToWidth(" " + translated("resource_explorer.detail.lines") + ": " + height));
lines.add(trimmedTextToWidth(" " + translated("resource_explorer.detail.character_count") + ": " + width));
}
}
default -> {
}//lines.add(trimmedTextToWidth(" //todo "));//todo
}
return lines;
}
MultilineText getTextLines() {
if (!fileType.isRawTextType())
return MultilineText.EMPTY;
if (readTextByLineBreaks == null) {
if (resource != null) {
try {
InputStream in = resource.getInputStream();
try {
ArrayList<Text> text = new ArrayList<>();
String readString = new String(in.readAllBytes(), StandardCharsets.UTF_8);
in.close();
//make tabs smaller
String reducedTabs = readString.replaceAll("(\t| {4})", " ");
String[] splitByLines = reducedTabs.split("\n");
width = readString.length();
height = splitByLines.length;
//trim lines to width now
for (int i = 0; i < splitByLines.length; i++) {
splitByLines[i] = trimmedStringToWidth(splitByLines[i], 178);
}
int lineCount = 0;
for (String line :
splitByLines) {
lineCount++;
if (lineCount > 512) {//todo set limit in config
text.add(Text.of("§l§4-- TEXT LONGER THAN " + 512 + " LINES --"));
text.add(Text.of("§r§o " + (height - lineCount) + " lines skipped."));
text.add(Text.of("§l§4-- END --"));
break;
}
text.add(Text.of(line));
}
readTextByLineBreaks = MultilineText.createFromTexts(MinecraftClient.getInstance().textRenderer, text);
} catch (Exception e) {
//resource.close();
in.close();
readTextByLineBreaks = MultilineText.EMPTY;
}
} catch (Exception ignored) {
readTextByLineBreaks = MultilineText.EMPTY;
}
} else {
readTextByLineBreaks = MultilineText.create(MinecraftClient.getInstance().textRenderer, Text.of(" ERROR: no file info could be read"));
}
}
return readTextByLineBreaks;
}
public void exportToOutputPack(REExplorer.REExportContext context) { | boolean exported = outputResourceToPackInternal(this); | 1 | 2023-11-05 17:35:39+00:00 | 4k |
cypcodestudio/rbacspring | rbacspring/src/main/java/com/cypcode/rbacspring/service/WUserService.java | [
{
"identifier": "Role",
"path": "rbacspring/src/main/java/com/cypcode/rbacspring/entity/Role.java",
"snippet": "@Entity\n@Table(name = \"Role\")\n@JsonIgnoreProperties(ignoreUnknown = true)\npublic class Role implements Serializable{\n\n\tprivate static final long serialVersionUID = 5926468583005150707L;\n\t\n\t@Id\n\t@GeneratedValue(strategy = GenerationType.IDENTITY)\n\tLong id;\n\n\t@Column(name = \"name\", nullable = false)\n\tprivate String name;\n\t\n\t\n\tpublic Long getId() {\n\t\treturn id;\n\t}\n\n\tpublic void setId(Long id) {\n\t\tthis.id = id;\n\t}\n\n\tpublic String getName() {\n\t\treturn name;\n\t}\n\n\tpublic void setName(String name) {\n\t\tthis.name = name;\n\t}\n\n}"
},
{
"identifier": "User",
"path": "rbacspring/src/main/java/com/cypcode/rbacspring/entity/User.java",
"snippet": "@Entity\n@Table(name = \"WUser\")\n@JsonIgnoreProperties(ignoreUnknown = true)\npublic class User implements Serializable, UserDetails{\n\n\tprivate static final long serialVersionUID = 5926468583005150707L;\n\t\n\t@Id\n\t@GeneratedValue(strategy = GenerationType.IDENTITY)\n\tLong id;\n\n\t@Column(name = \"username\", unique = true)\n\tprivate String username;\n\n\t@Column(name = \"password\")\n\tprivate String password;\n\n\t@Column(name = \"entity_no\", unique = true)\n\tprivate String entityNo;\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 username\n\t */\n\t@Override\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\t@Override\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 entityNo\n\t */\n\tpublic String getEntityNo() {\n\t\treturn entityNo;\n\t}\n\n\t/**\n\t * @param entityNo the entityNo to set\n\t */\n\tpublic void setEntityNo(String entityNo) {\n\t\tthis.entityNo = entityNo;\n\t}\n\n\t@Override\n\tpublic Collection<? extends GrantedAuthority> getAuthorities() {\n\t\t// TODO Auto-generated method stub\n\t\treturn null;\n\t}\n\n\t@Override\n\tpublic boolean isAccountNonExpired() {\n\t\t// TODO Auto-generated method stub\n\t\treturn false;\n\t}\n\n\t@Override\n\tpublic boolean isAccountNonLocked() {\n\t\t// TODO Auto-generated method stub\n\t\treturn false;\n\t}\n\n\t@Override\n\tpublic boolean isCredentialsNonExpired() {\n\t\t// TODO Auto-generated method stub\n\t\treturn false;\n\t}\n\n\t@Override\n\tpublic boolean isEnabled() {\n\t\t// TODO Auto-generated method stub\n\t\treturn false;\n\t}\n\t\n\t\n\n}"
},
{
"identifier": "UserRole",
"path": "rbacspring/src/main/java/com/cypcode/rbacspring/entity/UserRole.java",
"snippet": "@Entity\n@Table(name = \"UserRole\")\n@JsonIgnoreProperties(ignoreUnknown = true)\npublic class UserRole implements Serializable{\n\n\tprivate static final long serialVersionUID = 5926468583005150707L;\n\t\n\t@Id\n\t@GeneratedValue(strategy = GenerationType.IDENTITY)\n\tLong id;\n\t\n\t@ManyToOne\n\t@JoinColumn(name = \"user_id\", insertable = true, updatable = true)\n\tprivate User user;\n\t\n\t@ManyToOne\n\t@JoinColumn(name = \"role_id\", insertable = true, updatable = true)\n\tprivate Role role;\n\t\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 user\n\t */\n\tpublic User getUser() {\n\t\treturn user;\n\t}\n\n\t/**\n\t * @param user the user to set\n\t */\n\tpublic void setUser(User user) {\n\t\tthis.user = user;\n\t}\n\n\t/**\n\t * @return the role\n\t */\n\tpublic Role getRole() {\n\t\treturn role;\n\t}\n\n\t/**\n\t * @param role the role to set\n\t */\n\tpublic void setRole(Role role) {\n\t\tthis.role = role;\n\t}\n}"
},
{
"identifier": "UserRegisterRequestDTO",
"path": "rbacspring/src/main/java/com/cypcode/rbacspring/entity/dto/UserRegisterRequestDTO.java",
"snippet": "@Data\n@Getter\n@Setter\n@AllArgsConstructor\n@NoArgsConstructor\n@ToString\npublic class UserRegisterRequestDTO {\n\n\tprivate String username;\n\n\tprivate String password;\n\n\tprivate String entityNo;\n\t\n\tprivate String firstname;\n\n\tprivate String lastname;\n\n\tprivate String initial;\n\n\tprivate String idNumber;\n\n\tprivate Date startDate;\n\n\tprivate Date endDate;\n\t\n\tprivate String email;\n\t\n\tprivate String mobile;\n\n\tprivate List<String> roleList = new ArrayList<>();\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 entityNo\n\t */\n\tpublic String getEntityNo() {\n\t\treturn entityNo;\n\t}\n\n\t/**\n\t * @param entityNo the entityNo to set\n\t */\n\tpublic void setEntityNo(String entityNo) {\n\t\tthis.entityNo = entityNo;\n\t}\n\n\t/**\n\t * @return the firstname\n\t */\n\tpublic String getFirstname() {\n\t\treturn firstname;\n\t}\n\n\t/**\n\t * @param firstname the firstname to set\n\t */\n\tpublic void setFirstname(String firstname) {\n\t\tthis.firstname = firstname;\n\t}\n\n\t/**\n\t * @return the lastname\n\t */\n\tpublic String getLastname() {\n\t\treturn lastname;\n\t}\n\n\t/**\n\t * @param lastname the lastname to set\n\t */\n\tpublic void setLastname(String lastname) {\n\t\tthis.lastname = lastname;\n\t}\n\n\t/**\n\t * @return the initial\n\t */\n\tpublic String getInitial() {\n\t\treturn initial;\n\t}\n\n\t/**\n\t * @param initial the initial to set\n\t */\n\tpublic void setInitial(String initial) {\n\t\tthis.initial = initial;\n\t}\n\n\t/**\n\t * @return the idNumber\n\t */\n\tpublic String getIdNumber() {\n\t\treturn idNumber;\n\t}\n\n\t/**\n\t * @param idNumber the idNumber to set\n\t */\n\tpublic void setIdNumber(String idNumber) {\n\t\tthis.idNumber = idNumber;\n\t}\n\n\t/**\n\t * @return the startDate\n\t */\n\tpublic Date getStartDate() {\n\t\treturn startDate;\n\t}\n\n\t/**\n\t * @param startDate the startDate to set\n\t */\n\tpublic void setStartDate(Date startDate) {\n\t\tthis.startDate = startDate;\n\t}\n\n\t/**\n\t * @return the endDate\n\t */\n\tpublic Date getEndDate() {\n\t\treturn endDate;\n\t}\n\n\t/**\n\t * @param endDate the endDate to set\n\t */\n\tpublic void setEndDate(Date endDate) {\n\t\tthis.endDate = endDate;\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 mobile\n\t */\n\tpublic String getMobile() {\n\t\treturn mobile;\n\t}\n\n\t/**\n\t * @param mobile the mobile to set\n\t */\n\tpublic void setMobile(String mobile) {\n\t\tthis.mobile = mobile;\n\t}\n\n\tpublic List<String> getRoleList() {\n\t\treturn roleList;\n\t}\n\n\tpublic void setRoleList(List<String> roleList) {\n\t\tthis.roleList = roleList;\n\t}\n\t\n\t\n}"
},
{
"identifier": "IUserRepository",
"path": "rbacspring/src/main/java/com/cypcode/rbacspring/repository/IUserRepository.java",
"snippet": "@Repository\npublic interface IUserRepository extends JpaRepository<User, Long> {\n User findUserByUsernameAndPassword(String username, String password);\n \n User findByUsername(String username);\n}"
},
{
"identifier": "IUserRoleRepository",
"path": "rbacspring/src/main/java/com/cypcode/rbacspring/repository/IUserRoleRepository.java",
"snippet": "@Repository\npublic interface IUserRoleRepository extends JpaRepository<UserRole, Long>{\n\t\n\tList<UserRole> findAllByUserId(Long id);\n\n}"
},
{
"identifier": "SecurityPrincipal",
"path": "rbacspring/src/main/java/com/cypcode/rbacspring/security/SecurityPrincipal.java",
"snippet": "@Service\npublic class SecurityPrincipal {\n\tprivate static SecurityPrincipal securityPrincipal = null;\n\n\tprivate Authentication principal = SecurityContextHolder.getContext().getAuthentication();\n\n\tprivate static WUserService userService;\n\n\t@Autowired\n\tprivate SecurityPrincipal(WUserService userService) {\n\t\tthis.userService = userService;\n\t}\n\n\tpublic static SecurityPrincipal getInstance() {\n\t\tsecurityPrincipal = new SecurityPrincipal(userService);\n\t\treturn securityPrincipal;\n\t}\n\n\tpublic User getLoggedInPrincipal() {\n\t\tif (principal != null) {\n\t\t\tUserDetails loggedInPrincipal = (UserDetails) principal.getPrincipal();\n\t\t\treturn userService.findByUsername(loggedInPrincipal.getUsername());\n\t\t}\n\t\treturn null;\n\t}\n\n\tpublic Collection<?> getLoggedInPrincipalAuthorities() {\n\t\treturn ((UserDetails) principal.getPrincipal()).getAuthorities();\n\t}\n\n}"
}
] | import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;
import com.cypcode.rbacspring.entity.Role;
import com.cypcode.rbacspring.entity.User;
import com.cypcode.rbacspring.entity.UserRole;
import com.cypcode.rbacspring.entity.dto.UserRegisterRequestDTO;
import com.cypcode.rbacspring.repository.IUserRepository;
import com.cypcode.rbacspring.repository.IUserRoleRepository;
import com.cypcode.rbacspring.security.SecurityPrincipal;
import jakarta.transaction.Transactional; | 2,904 | package com.cypcode.rbacspring.service;
@Service
@Transactional
public class WUserService implements UserDetailsService {
private static final Logger LOG = LoggerFactory.getLogger(WUserService.class);
@Autowired
private IUserRepository userRepository;
@Autowired
private IUserRoleRepository userRoleRepository;
@Autowired
WRoleService roleService;
@Override
public UserDetails loadUserByUsername(String username) { | package com.cypcode.rbacspring.service;
@Service
@Transactional
public class WUserService implements UserDetailsService {
private static final Logger LOG = LoggerFactory.getLogger(WUserService.class);
@Autowired
private IUserRepository userRepository;
@Autowired
private IUserRoleRepository userRoleRepository;
@Autowired
WRoleService roleService;
@Override
public UserDetails loadUserByUsername(String username) { | User user = userRepository.findByUsername(username); | 1 | 2023-11-05 05:38:31+00:00 | 4k |
txline0420/nacos-dm | core/src/main/java/com/alibaba/nacos/core/control/remote/RemoteTpsCheckRequestParser.java | [
{
"identifier": "Request",
"path": "api/src/main/java/com/alibaba/nacos/api/remote/request/Request.java",
"snippet": "@SuppressWarnings(\"PMD.AbstractClassShouldStartWithAbstractNamingRule\")\npublic abstract class Request implements Payload {\n \n private final Map<String, String> headers = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);\n \n private String requestId;\n \n /**\n * put header.\n *\n * @param key key of value.\n * @param value value.\n */\n public void putHeader(String key, String value) {\n headers.put(key, value);\n }\n \n /**\n * put headers .\n *\n * @param headers headers to put.\n */\n public void putAllHeader(Map<String, String> headers) {\n if (headers == null || headers.isEmpty()) {\n return;\n }\n this.headers.putAll(headers);\n }\n \n /**\n * get a header value .\n *\n * @param key key of value.\n * @return return value of key. return null if not exist.\n */\n public String getHeader(String key) {\n return headers.get(key);\n }\n \n /**\n * get a header value of default value.\n *\n * @param key key of value.\n * @param defaultValue default value if key is not exist.\n * @return return final value.\n */\n public String getHeader(String key, String defaultValue) {\n String value = headers.get(key);\n return (value == null) ? defaultValue : value;\n }\n \n /**\n * Getter method for property <tt>requestId</tt>.\n *\n * @return property value of requestId\n */\n public String getRequestId() {\n return requestId;\n }\n \n /**\n * Setter method for property <tt>requestId</tt>.\n *\n * @param requestId value to be assigned to property requestId\n */\n public void setRequestId(String requestId) {\n this.requestId = requestId;\n }\n \n /**\n * Getter method for property <tt>type</tt>.\n *\n * @return property value of type\n */\n public abstract String getModule();\n \n /**\n * Getter method for property <tt>headers</tt>.\n *\n * @return property value of headers\n */\n public Map<String, String> getHeaders() {\n return headers;\n }\n \n public void clearHeaders() {\n this.headers.clear();\n }\n \n @Override\n public String toString() {\n return this.getClass().getSimpleName() + \"{\" + \"headers=\" + headers + \", requestId='\" + requestId + '\\'' + '}';\n }\n}"
},
{
"identifier": "RequestMeta",
"path": "api/src/main/java/com/alibaba/nacos/api/remote/request/RequestMeta.java",
"snippet": "public class RequestMeta {\n \n private String connectionId = \"\";\n \n private String clientIp = \"\";\n \n private String clientVersion = \"\";\n \n private Map<String, String> labels = new HashMap<>();\n\n /**\n * Getter method for property <tt>clientVersion</tt>.\n *\n * @return property value of clientVersion\n */\n public String getClientVersion() {\n return clientVersion;\n }\n \n /**\n * Setter method for property <tt>clientVersion</tt>.\n *\n * @param clientVersion value to be assigned to property clientVersion\n */\n public void setClientVersion(String clientVersion) {\n this.clientVersion = clientVersion;\n }\n \n /**\n * Getter method for property <tt>labels</tt>.\n *\n * @return property value of labels\n */\n public Map<String, String> getLabels() {\n return labels;\n }\n \n /**\n * Setter method for property <tt>labels</tt>.\n *\n * @param labels value to be assigned to property labels\n */\n public void setLabels(Map<String, String> labels) {\n this.labels = labels;\n }\n \n /**\n * Getter method for property <tt>connectionId</tt>.\n *\n * @return property value of connectionId\n */\n public String getConnectionId() {\n return connectionId;\n }\n \n /**\n * Setter method for property <tt>connectionId</tt>.\n *\n * @param connectionId value to be assigned to property connectionId\n */\n public void setConnectionId(String connectionId) {\n this.connectionId = connectionId;\n }\n \n /**\n * Getter method for property <tt>clientIp</tt>.\n *\n * @return property value of clientIp\n */\n public String getClientIp() {\n return clientIp;\n }\n \n /**\n * Setter method for property <tt>clientIp</tt>.\n *\n * @param clientIp value to be assigned to property clientIp\n */\n public void setClientIp(String clientIp) {\n this.clientIp = clientIp;\n }\n \n @Override\n public String toString() {\n return \"RequestMeta{\" + \"connectionId='\" + connectionId + '\\'' + \", clientIp='\" + clientIp + '\\''\n + \", clientVersion='\" + clientVersion + '\\'' + \", labels=\" + labels + '}';\n }\n}"
},
{
"identifier": "TpsCheckRequest",
"path": "plugin/control/src/main/java/com/alibaba/nacos/plugin/control/tps/request/TpsCheckRequest.java",
"snippet": "public class TpsCheckRequest {\n \n private String pointName;\n \n private long timestamp = System.currentTimeMillis();\n \n private String connectionId;\n \n private String clientIp;\n \n private long count = 1;\n \n public TpsCheckRequest() {\n \n }\n \n public TpsCheckRequest(String pointName, String connectionId, String clientIp) {\n this.connectionId = connectionId;\n this.clientIp = clientIp;\n this.pointName = pointName;\n }\n \n public long getTimestamp() {\n return timestamp;\n }\n \n public void setTimestamp(long timestamp) {\n this.timestamp = timestamp;\n }\n \n public String getConnectionId() {\n return connectionId;\n }\n \n public long getCount() {\n return count;\n }\n \n public void setCount(long count) {\n this.count = count;\n }\n \n public void setConnectionId(String connectionId) {\n this.connectionId = connectionId;\n }\n \n public String getClientIp() {\n return clientIp;\n }\n \n public void setClientIp(String clientIp) {\n this.clientIp = clientIp;\n }\n \n public String getPointName() {\n return pointName;\n }\n \n public void setPointName(String pointName) {\n this.pointName = pointName;\n }\n \n}"
}
] | import com.alibaba.nacos.api.remote.request.Request;
import com.alibaba.nacos.api.remote.request.RequestMeta;
import com.alibaba.nacos.plugin.control.tps.request.TpsCheckRequest; | 1,934 | /*
*
* Copyright 1999-2021 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.alibaba.nacos.core.control.remote;
/**
* remote tps check request parser.
*
* @author shiyiyue
*/
@SuppressWarnings("PMD.AbstractClassShouldStartWithAbstractNamingRule")
public abstract class RemoteTpsCheckRequestParser {
public RemoteTpsCheckRequestParser() {
RemoteTpsCheckRequestParserRegistry.register(this);
}
/**
* parse tps check request.
*
* @param request request.
* @param meta meta.
* @return
*/ | /*
*
* Copyright 1999-2021 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.alibaba.nacos.core.control.remote;
/**
* remote tps check request parser.
*
* @author shiyiyue
*/
@SuppressWarnings("PMD.AbstractClassShouldStartWithAbstractNamingRule")
public abstract class RemoteTpsCheckRequestParser {
public RemoteTpsCheckRequestParser() {
RemoteTpsCheckRequestParserRegistry.register(this);
}
/**
* parse tps check request.
*
* @param request request.
* @param meta meta.
* @return
*/ | public abstract TpsCheckRequest parse(Request request, RequestMeta meta); | 2 | 2023-11-02 01:34:09+00:00 | 4k |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.