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
MalithShehan/layered-architecture-Malith-Shehan
src/main/java/lk/ijse/layeredarchitecture/dao/custom/impl/OrderDetailsDAOImpl.java
[ { "identifier": "SQLUtil", "path": "src/main/java/lk/ijse/layeredarchitecture/dao/SQLUtil.java", "snippet": "public class SQLUtil {\n public static <T> T execute(String sql, Object... args) throws SQLException, ClassNotFoundException {\n Connection connection = DBConnection.getDbConnection().getConnection();\n PreparedStatement pstm = connection.prepareStatement(sql);\n for (int i=0;i< args.length; i++){\n pstm.setObject(i+1,args[i]);\n }\n if (sql.startsWith(\"SELECT\")){\n return (T)pstm.executeQuery();\n }else {\n return (T)(Boolean)(pstm.executeUpdate()>0);\n }\n }\n}" }, { "identifier": "OrderDetailsDAO", "path": "src/main/java/lk/ijse/layeredarchitecture/dao/custom/OrderDetailsDAO.java", "snippet": "public interface OrderDetailsDAO extends CrudDAO<OrderDetails> {\n}" }, { "identifier": "OrderDetailDTO", "path": "src/main/java/lk/ijse/layeredarchitecture/dto/OrderDetailDTO.java", "snippet": "public class OrderDetailDTO implements Serializable {\n\n private String oid;\n private String itemCode;\n private int qty;\n private BigDecimal unitPrice;\n\n public OrderDetailDTO() {\n }\n\n public OrderDetailDTO(String itemCode, int qty, BigDecimal unitPrice) {\n this.itemCode = itemCode;\n this.qty = qty;\n this.unitPrice = unitPrice;\n }\n\n public OrderDetailDTO(String oid, String itemCode, int qty, BigDecimal unitPrice) {\n this.oid = oid;\n this.itemCode = itemCode;\n this.qty = qty;\n this.unitPrice = unitPrice;\n }\n\n public String getOid() {\n return oid;\n }\n\n public void setOid(String oid) {\n this.oid = oid;\n }\n\n public String getItemCode() {\n return itemCode;\n }\n\n public void setItemCode(String itemCode) {\n this.itemCode = itemCode;\n }\n\n public int getQty() {\n return qty;\n }\n\n public void setQty(int qty) {\n this.qty = qty;\n }\n\n public BigDecimal getUnitPrice() {\n return unitPrice;\n }\n\n public void setUnitPrice(BigDecimal unitPrice) {\n this.unitPrice = unitPrice;\n }\n\n @Override\n public String toString() {\n return \"OrderDetailDTO{\" +\n \"itemCode='\" + itemCode + '\\'' +\n \", qty=\" + qty +\n \", unitPrice=\" + unitPrice +\n '}';\n }\n}" }, { "identifier": "OrderDetails", "path": "src/main/java/lk/ijse/layeredarchitecture/entity/OrderDetails.java", "snippet": "public class OrderDetails {\n private String oid;\n private String itemCode;\n private int qty;\n private BigDecimal unitPrice;\n\n public void setOid(String oid) {\n this.oid = oid;\n }\n\n public void setItemCode(String itemCode) {\n this.itemCode = itemCode;\n }\n\n public void setQty(int qty) {\n this.qty = qty;\n }\n\n public void setUnitPrice(BigDecimal unitPrice) {\n this.unitPrice = unitPrice;\n }\n\n public String getOid() {\n return oid;\n }\n\n public String getItemCode() {\n return itemCode;\n }\n\n public int getQty() {\n return qty;\n }\n\n public BigDecimal getUnitPrice() {\n return unitPrice;\n }\n\n public OrderDetails(String oid, String itemCode, int qty, BigDecimal unitPrice) {\n this.oid = oid;\n this.itemCode = itemCode;\n this.qty = qty;\n this.unitPrice = unitPrice;\n }\n}" } ]
import com.example.layeredarchitecture.dao.SQLUtil; import com.example.layeredarchitecture.dao.custom.OrderDetailsDAO; import com.example.layeredarchitecture.dto.OrderDetailDTO; import com.example.layeredarchitecture.entity.OrderDetails; import java.sql.SQLException; import java.util.ArrayList;
1,029
package com.example.layeredarchitecture.dao.custom.impl; public class OrderDetailsDAOImpl implements OrderDetailsDAO { @Override public ArrayList<OrderDetails> getAll() throws SQLException, ClassNotFoundException { return null; } @Override public boolean save(OrderDetails entity) throws SQLException, ClassNotFoundException {
package com.example.layeredarchitecture.dao.custom.impl; public class OrderDetailsDAOImpl implements OrderDetailsDAO { @Override public ArrayList<OrderDetails> getAll() throws SQLException, ClassNotFoundException { return null; } @Override public boolean save(OrderDetails entity) throws SQLException, ClassNotFoundException {
return SQLUtil.execute("INSERT INTO OrderDetails (oid, itemCode, unitPrice, qty) VALUES (?,?,?,?)", entity.getOid(), entity.getItemCode(), entity.getUnitPrice(), entity.getQty());
0
2023-12-16 04:19:09+00:00
2k
f1den/MrCrayfishGunMod
src/main/java/com/mrcrayfish/guns/Config.java
[ { "identifier": "SwayType", "path": "src/main/java/com/mrcrayfish/guns/client/SwayType.java", "snippet": "public enum SwayType\n{\n DIRECTIONAL(Vector3f.XN, Vector3f.YN),\n DRAG(Vector3f.XP, Vector3f.YP);\n\n Vector3f pitchRotation;\n Vector3f yawRotation;\n\n SwayType(Vector3f pitchRotation, Vector3f yawRotation)\n {\n this.pitchRotation = pitchRotation;\n this.yawRotation = yawRotation;\n }\n\n public Vector3f getPitchRotation()\n {\n return this.pitchRotation;\n }\n\n public Vector3f getYawRotation()\n {\n return this.yawRotation;\n }\n}" }, { "identifier": "Crosshair", "path": "src/main/java/com/mrcrayfish/guns/client/render/crosshair/Crosshair.java", "snippet": "public abstract class Crosshair implements IResourceLocation\n{\n public static final Crosshair DEFAULT = new Crosshair(new ResourceLocation(\"default\")) {};\n\n static\n {\n CrosshairHandler.get().register(DEFAULT);\n }\n\n private ResourceLocation id;\n\n /**\n * The default constructor for crosshairs\n *\n * @param id the id for the crosshair\n */\n protected Crosshair(ResourceLocation id)\n {\n this.id = id;\n }\n\n /**\n * Renders the crosshair to the screen. If implementing, positioning is not initially set to\n * the center of the screen. Use windowWidth and windowHeight for calculating the center. It\n * should be considered that the player may not be in a world.\n *\n * @param mc a minecraft instance\n * @param stack the current matrix stack\n * @param windowWidth the scaled width of the window\n * @param windowHeight the scaled height of the window\n * @param partialTicks\n */\n public void render(Minecraft mc, PoseStack stack, int windowWidth, int windowHeight, float partialTicks) {}\n\n /**\n * Ticks the crosshair for any logic\n */\n public void tick() {}\n\n /**\n * Called when the held gun is fired\n */\n public void onGunFired() {}\n\n /**\n * Gets the id of the crosshair\n */\n @Override\n\n public final ResourceLocation getLocation()\n {\n return this.id;\n }\n\n /**\n * Test for default crosshair (aka normal minecraft crosshair)\n */\n public final boolean isDefault()\n {\n return this == DEFAULT;\n }\n}" }, { "identifier": "ButtonAlignment", "path": "src/main/java/com/mrcrayfish/guns/client/screen/ButtonAlignment.java", "snippet": "public enum ButtonAlignment\n{\n LEFT, RIGHT\n}" } ]
import com.mrcrayfish.guns.client.SwayType; import com.mrcrayfish.guns.client.render.crosshair.Crosshair; import com.mrcrayfish.guns.client.screen.ButtonAlignment; import net.minecraftforge.common.ForgeConfigSpec; import org.apache.commons.lang3.tuple.Pair; import java.util.Collections; import java.util.List;
1,497
package com.mrcrayfish.guns; public class Config { /** * Client related config options */ public static class Client { public final Sounds sounds; public final Display display; public final Particle particle; public final Controls controls; public final Experimental experimental; public final ForgeConfigSpec.BooleanValue hideConfigButton; public final ForgeConfigSpec.EnumValue<ButtonAlignment> buttonAlignment; public Client(ForgeConfigSpec.Builder builder) { builder.push("client"); { this.sounds = new Sounds(builder); this.display = new Display(builder); this.particle = new Particle(builder); this.controls = new Controls(builder); this.experimental = new Experimental(builder); } builder.pop(); this.hideConfigButton = builder.comment("If enabled, hides the config button from the backpack screen").define("hideConfigButton", false); this.buttonAlignment = builder.comment("The alignment of the buttons in the backpack inventory screen").defineEnum("buttonAlignment", ButtonAlignment.RIGHT); } } /** * Sound related config options */ public static class Sounds { public final ForgeConfigSpec.BooleanValue playSoundWhenHeadshot; public final ForgeConfigSpec.ConfigValue<String> headshotSound; public final ForgeConfigSpec.BooleanValue playSoundWhenCritical; public final ForgeConfigSpec.ConfigValue<String> criticalSound; public final ForgeConfigSpec.DoubleValue impactSoundDistance; public Sounds(ForgeConfigSpec.Builder builder) { builder.comment("Control sounds triggered by guns").push("sounds"); { this.playSoundWhenHeadshot = builder.comment("If true, a sound will play when you successfully hit a headshot on a entity with a gun").define("playSoundWhenHeadshot", true); this.headshotSound = builder.comment("The sound to play when a headshot occurs").define("headshotSound", "minecraft:entity.player.attack.knockback"); this.playSoundWhenCritical = builder.comment("If true, a sound will play when you successfully hit a critical on a entity with a gun").define("playSoundWhenCritical", true); this.criticalSound = builder.comment("The sound to play when a critical occurs").define("criticalSound", "minecraft:entity.player.attack.crit"); this.impactSoundDistance = builder.comment("The maximum distance impact sounds from bullet can be heard").defineInRange("impactSoundDistance", 32.0, 0.0, 32.0); } builder.pop(); } } /** * Display related config options */ public static class Display { public final ForgeConfigSpec.BooleanValue oldAnimations; public final ForgeConfigSpec.ConfigValue<String> crosshair; public final ForgeConfigSpec.BooleanValue cooldownIndicator; public final ForgeConfigSpec.BooleanValue weaponSway; public final ForgeConfigSpec.DoubleValue swaySensitivity; public final ForgeConfigSpec.EnumValue<SwayType> swayType; public final ForgeConfigSpec.BooleanValue cameraRollEffect; public final ForgeConfigSpec.DoubleValue cameraRollAngle; public final ForgeConfigSpec.BooleanValue restrictCameraRollToWeapons; public final ForgeConfigSpec.BooleanValue sprintAnimation; public final ForgeConfigSpec.DoubleValue bobbingIntensity; public Display(ForgeConfigSpec.Builder builder) { builder.comment("Configuration for display related options").push("display"); { this.oldAnimations = builder.comment("If true, uses the old animation poses for weapons. This is only for nostalgic reasons and not recommended to switch back.").define("oldAnimations", false);
package com.mrcrayfish.guns; public class Config { /** * Client related config options */ public static class Client { public final Sounds sounds; public final Display display; public final Particle particle; public final Controls controls; public final Experimental experimental; public final ForgeConfigSpec.BooleanValue hideConfigButton; public final ForgeConfigSpec.EnumValue<ButtonAlignment> buttonAlignment; public Client(ForgeConfigSpec.Builder builder) { builder.push("client"); { this.sounds = new Sounds(builder); this.display = new Display(builder); this.particle = new Particle(builder); this.controls = new Controls(builder); this.experimental = new Experimental(builder); } builder.pop(); this.hideConfigButton = builder.comment("If enabled, hides the config button from the backpack screen").define("hideConfigButton", false); this.buttonAlignment = builder.comment("The alignment of the buttons in the backpack inventory screen").defineEnum("buttonAlignment", ButtonAlignment.RIGHT); } } /** * Sound related config options */ public static class Sounds { public final ForgeConfigSpec.BooleanValue playSoundWhenHeadshot; public final ForgeConfigSpec.ConfigValue<String> headshotSound; public final ForgeConfigSpec.BooleanValue playSoundWhenCritical; public final ForgeConfigSpec.ConfigValue<String> criticalSound; public final ForgeConfigSpec.DoubleValue impactSoundDistance; public Sounds(ForgeConfigSpec.Builder builder) { builder.comment("Control sounds triggered by guns").push("sounds"); { this.playSoundWhenHeadshot = builder.comment("If true, a sound will play when you successfully hit a headshot on a entity with a gun").define("playSoundWhenHeadshot", true); this.headshotSound = builder.comment("The sound to play when a headshot occurs").define("headshotSound", "minecraft:entity.player.attack.knockback"); this.playSoundWhenCritical = builder.comment("If true, a sound will play when you successfully hit a critical on a entity with a gun").define("playSoundWhenCritical", true); this.criticalSound = builder.comment("The sound to play when a critical occurs").define("criticalSound", "minecraft:entity.player.attack.crit"); this.impactSoundDistance = builder.comment("The maximum distance impact sounds from bullet can be heard").defineInRange("impactSoundDistance", 32.0, 0.0, 32.0); } builder.pop(); } } /** * Display related config options */ public static class Display { public final ForgeConfigSpec.BooleanValue oldAnimations; public final ForgeConfigSpec.ConfigValue<String> crosshair; public final ForgeConfigSpec.BooleanValue cooldownIndicator; public final ForgeConfigSpec.BooleanValue weaponSway; public final ForgeConfigSpec.DoubleValue swaySensitivity; public final ForgeConfigSpec.EnumValue<SwayType> swayType; public final ForgeConfigSpec.BooleanValue cameraRollEffect; public final ForgeConfigSpec.DoubleValue cameraRollAngle; public final ForgeConfigSpec.BooleanValue restrictCameraRollToWeapons; public final ForgeConfigSpec.BooleanValue sprintAnimation; public final ForgeConfigSpec.DoubleValue bobbingIntensity; public Display(ForgeConfigSpec.Builder builder) { builder.comment("Configuration for display related options").push("display"); { this.oldAnimations = builder.comment("If true, uses the old animation poses for weapons. This is only for nostalgic reasons and not recommended to switch back.").define("oldAnimations", false);
this.crosshair = builder.comment("The custom crosshair to use for weapons. Go to (Options > Controls > Mouse Settings > Crosshair) in game to change this!").define("crosshair", Crosshair.DEFAULT.getLocation().toString());
1
2023-12-18 15:04:35+00:00
2k
JenningsCrane/JDBC-Simple-Chat
Chat/src/main/java/edu/school21/chat/models/Repository/UsersRepositoryJdbcImpl.java
[ { "identifier": "Chatroom", "path": "Chat/src/main/java/edu/school21/chat/models/Chat/Chatroom.java", "snippet": "public class Chatroom {\n private Long chatRoomId;\n private String chatRoomName;\n private User chatRoomOwner;\n private List<Message> chatRoomMessages;\n\n public Chatroom(Long id, String name, User owner, List<Message> messages) {\n this.chatRoomId = id;\n this.chatRoomName = name;\n this.chatRoomOwner = owner;\n this.chatRoomMessages = messages;\n }\n\n public Long getChatRoomId() {\n return chatRoomId;\n }\n\n public void setChatRoomId(Long chatRoomId) {\n this.chatRoomId = chatRoomId;\n }\n\n public String getChatRoomName() {\n return chatRoomName;\n }\n\n public void setChatRoomName(String chatRoomName) {\n this.chatRoomName = chatRoomName;\n }\n\n public User getChatRoomOwner() {\n return chatRoomOwner;\n }\n\n public void setChatRoomOwner(User chatRoomOwner) {\n this.chatRoomOwner = chatRoomOwner;\n }\n\n public List<Message> getChatRoomMessages() {\n return chatRoomMessages;\n }\n\n public void setChatRoomMessages(List<Message> chatRoomMessages) {\n this.chatRoomMessages = chatRoomMessages;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (o == null || getClass() != o.getClass()) return false;\n Chatroom chatRoom = (Chatroom) o;\n return Objects.equals(chatRoomId, chatRoom.chatRoomId);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(chatRoomId);\n }\n\n @Override\n public String toString() {\n return \"ChatRoom{\" +\n \"id=\" + chatRoomId +\n \", chatName='\" + chatRoomName + '\\'' +\n \", chatOwner='\" + chatRoomOwner + '\\'' +\n '}';\n }\n}" }, { "identifier": "User", "path": "Chat/src/main/java/edu/school21/chat/models/Chat/User.java", "snippet": "public class User {\n private Long userId;\n private String login;\n private String password;\n private List<Chatroom> createdRooms;\n private List<Chatroom> socializesRooms;\n\n public User(Long id, String login, String password, List<Chatroom> createdRooms, List<Chatroom> socializesRooms) {\n this.userId = id;\n this.login = login;\n this.password = password;\n this.createdRooms = createdRooms;\n this.socializesRooms = socializesRooms;\n }\n\n public Long getUserId() {\n return userId;\n }\n\n public void setUserId(Long id) {\n this.userId = id;\n }\n\n public String getLogin() {\n return login;\n }\n\n public void setLogin(String login) {\n this.login = login;\n }\n\n public String getPassword() {\n return password;\n }\n\n public void setPassword(String password) {\n this.password = password;\n }\n\n public List<Chatroom> getCreatedRooms() {\n return createdRooms;\n }\n\n public void setCreatedRooms(List<Chatroom> createdRooms) {\n this.createdRooms = createdRooms;\n }\n\n public List<Chatroom> getSocializesRooms() {\n return socializesRooms;\n }\n\n public void setSocializesRooms(List<Chatroom> socializesRooms) {\n this.socializesRooms = socializesRooms;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (o == null || getClass() != o.getClass()) return false;\n User user = (User) o;\n return Objects.equals(userId, user.userId);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(userId);\n }\n\n @Override\n public String toString() {\n return \"User{\" +\n \"id=\" + userId +\n \", login='\" + login + '\\'' +\n \", password='\" + password + '\\'' +\n '}';\n }\n}" } ]
import edu.school21.chat.models.Chat.Chatroom; import edu.school21.chat.models.Chat.User; import javax.sql.DataSource; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List;
1,269
package edu.school21.chat.models.Repository; public class UsersRepositoryJdbcImpl implements UsersRepository{ private static Connection connection; private static final String SQL_QUERY = "SELECT Chatroom.chatroomid, Chatroom.chatroomname, Chatroom.chatroomowner, \"U*\".userid, \"U*\".login, \"U*\".password\n" + "FROM (SELECT * FROM Chat.Users LIMIT ? OFFSET ?) as \"U*\"\n" + "JOIN Chat.user_chatrooms ON user_chatrooms.userid = \"U*\".userid\n" + "JOIN Chat.Chatroom ON user_chatrooms.chatroomid = chatroom.chatroomid"; public UsersRepositoryJdbcImpl(DataSource dataSource) throws SQLException { UsersRepositoryJdbcImpl.connection = dataSource.getConnection(); } @Override
package edu.school21.chat.models.Repository; public class UsersRepositoryJdbcImpl implements UsersRepository{ private static Connection connection; private static final String SQL_QUERY = "SELECT Chatroom.chatroomid, Chatroom.chatroomname, Chatroom.chatroomowner, \"U*\".userid, \"U*\".login, \"U*\".password\n" + "FROM (SELECT * FROM Chat.Users LIMIT ? OFFSET ?) as \"U*\"\n" + "JOIN Chat.user_chatrooms ON user_chatrooms.userid = \"U*\".userid\n" + "JOIN Chat.Chatroom ON user_chatrooms.chatroomid = chatroom.chatroomid"; public UsersRepositoryJdbcImpl(DataSource dataSource) throws SQLException { UsersRepositoryJdbcImpl.connection = dataSource.getConnection(); } @Override
public List<User> findAll(int page, int size) throws SQLException {
1
2023-12-17 05:34:09+00:00
2k
Qzimyion/BucketEm
src/main/java/com/qzimyion/bucketem/items/ModItemGroups.java
[ { "identifier": "Bucketem", "path": "src/main/java/com/qzimyion/bucketem/Bucketem.java", "snippet": "public class Bucketem implements ModInitializer {\n\n\tpublic static final String MOD_ID = \"bucketem\";\n\tpublic static final Logger LOGGER = LoggerFactory.getLogger(MOD_ID);\n\n\t@Override\n\tpublic void onInitialize() {\n\t\tModItems.registerItems();\n\t\tModItemGroups.registerItemGroups();\n\t\tModEvents.registerEvents();\n\t\tDispenserBehaviorRegistry.registerDispenserBehavior();\n\t\tModStatusEffectsRegistry.registerStatusEffects();\n\t\tModPotionsRegistry.registerPotions();\n\t\tModPotionsRegistry.registerPotionRecipes();\n\t}\n}" }, { "identifier": "ModItems", "path": "src/main/java/com/qzimyion/bucketem/items/ModItems.java", "snippet": "public class ModItems {\n\n //Buckets\n public static final Item STRIDER_BUCKET = registerItem(\"strider_bucket\", new EntityBucketItem(EntityType.STRIDER, Fluids.LAVA, SoundEvents.ITEM_BUCKET_EMPTY_LAVA, new FabricItemSettings().maxCount(1)));\n public static final Item SQUID_BUCKET = registerItem(\"squid_bucket\", new EntityBucketItem(EntityType.SQUID, Fluids.WATER, SoundEvents.ITEM_BUCKET_EMPTY_FISH, new FabricItemSettings().maxCount(1)));\n public static final Item GLOW_SQUID_BUCKET = registerItem(\"glow_squid_bucket\", new EntityBucketItem(EntityType.GLOW_SQUID, Fluids.WATER, SoundEvents.ITEM_BUCKET_EMPTY_FISH, new FabricItemSettings().maxCount(1)));\n public static final Item TEMPERATE_FROG_BUCKET = registerItem(\"temperate_frog_bucket\", new TemperateFrogBuckets(Fluids.WATER ,new FabricItemSettings().maxCount(1)));\n public static final Item TROPICAL_FROG_BUCKET = registerItem(\"tropical_frog_bucket\", new TropicalFrogBuckets(Fluids.WATER , new FabricItemSettings().maxCount(1)));\n public static final Item TUNDRA_FROG_BUCKET = registerItem(\"tundra_frog_bucket\", new TundraFrogBuckets(Fluids.WATER ,new FabricItemSettings().maxCount(1)));\n public static final Item TURTLE_BUCKET = registerItem(\"turtle_bucket\", new EntityBucketItem(EntityType.TURTLE, Fluids.WATER, SoundEvents.ITEM_BUCKET_EMPTY_FISH, new FabricItemSettings().maxCount(1)));\n public static final Item DRY_TEMPERATE_FROG_BUCKET = registerItem(\"dry_temperate_frog_bucket\", new DryTemperateFrogBuckets(new FabricItemSettings().maxCount(1)));\n public static final Item DRY_TROPICAL_FROG_BUCKET = registerItem(\"dry_tropical_frog_bucket\", new DryTropicalFrogBuckets(new FabricItemSettings().maxCount(1)));\n public static final Item DRY_TUNDRA_FROG_BUCKET = registerItem(\"dry_tundra_frog_bucket\", new DryTundraFrogBuckets(new FabricItemSettings().maxCount(1)));\n\n\n //Books\n public static final Item ALLAY_POSSESSED_BOOK = registerItem(\"allay_possessed_book\", new EntityBook(EntityType.ALLAY ,new FabricItemSettings().maxCount(1).rarity(Rarity.UNCOMMON)));\n public static final Item VEX_POSSESSED_BOOK = registerItem(\"vex_possessed_book\", new EntityBook(EntityType.VEX, new FabricItemSettings().maxCount(1).rarity(Rarity.UNCOMMON)));\n\n //Bottles\n public static final Item BEE_BOTTLE = registerItem(\"bee_bottle\", new EntityBottle(EntityType.BEE ,new FabricItemSettings().maxCount(1)));\n public static final Item SILVERFISH_BOTTLE = registerItem(\"silverfish_bottle\", new EntityBottle(EntityType.SILVERFISH, new FabricItemSettings().maxCount(1)));\n public static final Item ENDERMITE_BOTTLE = registerItem(\"endermite_bottle\", new EntityBottle(EntityType.ENDERMITE, new FabricItemSettings().maxCount(1)));\n public static final Item SLIME_BOTTLE = registerItem(\"slime_bottle\", new SlimeBottle(new FabricItemSettings().maxCount(1).recipeRemainder(GLASS_BOTTLE)));\n public static final Item MAGMA_CUBE_BOTTLE = registerItem(\"magma_bottle\", new MagmaCubeBottle(new FabricItemSettings().maxCount(1).recipeRemainder(GLASS_BOTTLE)));\n\n\n private static Item registerItem(String name, Item item)\n {\n return Registry.register(Registries.ITEM, new Identifier(Bucketem.MOD_ID, name), item);\n }\n\n public static void registerItems(){\n\n Bucketem.LOGGER.info(\"Registering mod Items\");\n }\n}" }, { "identifier": "VEX_POSSESSED_BOOK", "path": "src/main/java/com/qzimyion/bucketem/items/ModItems.java", "snippet": "public static final Item VEX_POSSESSED_BOOK = registerItem(\"vex_possessed_book\", new EntityBook(EntityType.VEX, new FabricItemSettings().maxCount(1).rarity(Rarity.UNCOMMON)));" } ]
import com.qzimyion.bucketem.Bucketem; import net.fabricmc.fabric.api.itemgroup.v1.ItemGroupEvents; import static com.qzimyion.bucketem.items.ModItems.*; import static com.qzimyion.bucketem.items.ModItems.VEX_POSSESSED_BOOK; import static net.minecraft.item.Items.*;
1,456
package com.qzimyion.bucketem.items; public class ModItemGroups { public static void registerItemGroups(){ ItemGroupEvents.modifyEntriesEvent(net.minecraft.item.ItemGroups.TOOLS).register(content -> { content.addAfter(LAVA_BUCKET, STRIDER_BUCKET); content.addAfter(TADPOLE_BUCKET, DRY_TEMPERATE_FROG_BUCKET, DRY_TUNDRA_FROG_BUCKET, DRY_TROPICAL_FROG_BUCKET, TEMPERATE_FROG_BUCKET, TUNDRA_FROG_BUCKET, TROPICAL_FROG_BUCKET, DRY_TEMPERATE_FROG_BUCKET, DRY_TROPICAL_FROG_BUCKET, DRY_TUNDRA_FROG_BUCKET, GLOW_SQUID_BUCKET, SQUID_BUCKET, TURTLE_BUCKET); content.addAfter(MILK_BUCKET, BEE_BOTTLE, SILVERFISH_BOTTLE, ENDERMITE_BOTTLE, SLIME_BOTTLE, MAGMA_CUBE_BOTTLE, ALLAY_POSSESSED_BOOK, VEX_POSSESSED_BOOK); });
package com.qzimyion.bucketem.items; public class ModItemGroups { public static void registerItemGroups(){ ItemGroupEvents.modifyEntriesEvent(net.minecraft.item.ItemGroups.TOOLS).register(content -> { content.addAfter(LAVA_BUCKET, STRIDER_BUCKET); content.addAfter(TADPOLE_BUCKET, DRY_TEMPERATE_FROG_BUCKET, DRY_TUNDRA_FROG_BUCKET, DRY_TROPICAL_FROG_BUCKET, TEMPERATE_FROG_BUCKET, TUNDRA_FROG_BUCKET, TROPICAL_FROG_BUCKET, DRY_TEMPERATE_FROG_BUCKET, DRY_TROPICAL_FROG_BUCKET, DRY_TUNDRA_FROG_BUCKET, GLOW_SQUID_BUCKET, SQUID_BUCKET, TURTLE_BUCKET); content.addAfter(MILK_BUCKET, BEE_BOTTLE, SILVERFISH_BOTTLE, ENDERMITE_BOTTLE, SLIME_BOTTLE, MAGMA_CUBE_BOTTLE, ALLAY_POSSESSED_BOOK, VEX_POSSESSED_BOOK); });
Bucketem.LOGGER.info("Registering mod Item Groups");
0
2023-12-16 08:12:37+00:00
2k
devOS-Sanity-Edition/blocky-bass
src/main/java/one/devos/nautical/blocky_bass/block/BlockyBassBlockEntity.java
[ { "identifier": "BlockyBass", "path": "src/main/java/one/devos/nautical/blocky_bass/BlockyBass.java", "snippet": "public class BlockyBass implements ModInitializer {\n\tpublic static final String ID = \"blocky_bass\";\n\tpublic static final Logger LOGGER = LoggerFactory.getLogger(ID);\n\n\tpublic static final Block BLOCK = new BlockyBassBlock(FabricBlockSettings.copyOf(Blocks.OAK_PLANKS).nonOpaque());\n\n\tpublic static final BlockEntityType<BlockyBassBlockEntity> BLOCK_ENTITY = FabricBlockEntityTypeBuilder.create(BlockyBassBlockEntity::new)\n\t\t\t\t\t.addBlock(BLOCK)\n\t\t\t\t\t.build();\n\n\tpublic static final Item ITEM = new BlockItem(BLOCK, new FabricItemSettings());\n\n\t@Override\n\tpublic void onInitialize() {\n\t\tResourceLocation id = id(\"blocky_bass\");\n\t\tRegistry.register(BuiltInRegistries.BLOCK, id, BLOCK);\n\t\tRegistry.register(BuiltInRegistries.BLOCK_ENTITY_TYPE, id, BLOCK_ENTITY);\n\t\tRegistry.register(BuiltInRegistries.ITEM, id, ITEM);\n\n\t\tItemGroupEvents.modifyEntriesEvent(CreativeModeTabs.FUNCTIONAL_BLOCKS)\n\t\t\t\t.register(entries -> entries.addAfter(Blocks.JUKEBOX, ITEM));\n\n\t\tLootTableEvents.MODIFY.register(BlockyBass::modifyLoot);\n\t}\n\n\tprivate static void modifyLoot(ResourceManager manager, LootDataManager loot, ResourceLocation id, LootTable.Builder builder, LootTableSource source) {\n\t\tif (id.equals(BuiltInLootTables.FISHING_TREASURE)) {\n\t\t\t// don't add a new pool, only fish up 1 item\n\t\t\tbuilder.modifyPools(pool -> pool.add(LootItem.lootTableItem(ITEM)));\n\t\t}\n\t}\n\n\tpublic static ResourceLocation id(String path) {\n\t\treturn new ResourceLocation(ID, path);\n\t}\n}" }, { "identifier": "RandomlyFlap", "path": "src/main/java/one/devos/nautical/blocky_bass/block/BassPartRotation.java", "snippet": "public static class RandomlyFlap extends BassPartRotation {\n\tprivate boolean active = false;\n\n\t@Override\n\tpublic void tick(RandomSource random) {\n\t\tif (random.nextFloat() < TOGGLE_CHANCE) {\n\t\t\tthis.active = !this.active;\n\t\t}\n\t\tif (this.active) {\n\t\t\tsuper.tick(random);\n\t\t} else {\n\t\t\tthis.tickInactive();\n\t\t}\n\t}\n\n\t@Override\n\tprotected boolean toggleDirection(RandomSource random) {\n\t\treturn this.current == this.target;\n\t}\n}" }, { "identifier": "BlockEntityAccessor", "path": "src/main/java/one/devos/nautical/blocky_bass/mixin/BlockEntityAccessor.java", "snippet": "@Mixin(BlockEntity.class)\npublic interface BlockEntityAccessor {\n\t@Accessor\n\t@Mutable\n\tvoid setType(BlockEntityType<?> type);\n}" } ]
import net.minecraft.core.BlockPos; import net.minecraft.nbt.CompoundTag; import net.minecraft.network.protocol.Packet; import net.minecraft.network.protocol.game.ClientGamePacketListener; import net.minecraft.network.protocol.game.ClientboundBlockEntityDataPacket; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.JukeboxBlock; import net.minecraft.world.level.block.entity.JukeboxBlockEntity; import net.minecraft.world.level.block.state.BlockState; import one.devos.nautical.blocky_bass.BlockyBass; import one.devos.nautical.blocky_bass.block.BassPartRotation.RandomlyFlap; import one.devos.nautical.blocky_bass.mixin.BlockEntityAccessor; import org.jetbrains.annotations.Nullable;
926
package one.devos.nautical.blocky_bass.block; public class BlockyBassBlockEntity extends JukeboxBlockEntity { public final BassPartRotation head; public final BassPartRotation mouth; public final BassPartRotation tail; public BlockyBassBlockEntity(BlockPos pos, BlockState state) { super(pos, state); ((BlockEntityAccessor) this).setType(BlockyBass.BLOCK_ENTITY); this.head = new BassPartRotation(); this.mouth = new BassPartRotation();
package one.devos.nautical.blocky_bass.block; public class BlockyBassBlockEntity extends JukeboxBlockEntity { public final BassPartRotation head; public final BassPartRotation mouth; public final BassPartRotation tail; public BlockyBassBlockEntity(BlockPos pos, BlockState state) { super(pos, state); ((BlockEntityAccessor) this).setType(BlockyBass.BLOCK_ENTITY); this.head = new BassPartRotation(); this.mouth = new BassPartRotation();
this.tail = new BassPartRotation.RandomlyFlap();
1
2023-12-18 05:18:17+00:00
2k
lpyleo/disk-back-end
file-web/src/main/java/com/disk/file/advice/GlobalExceptionHandlerAdvice.java
[ { "identifier": "RestResult", "path": "file-web/src/main/java/com/disk/file/common/RestResult.java", "snippet": "@Data\npublic class RestResult<T> {\n private Boolean success = true;\n private Integer code;\n private String message;\n private T data;\n\n // 自定义返回数据\n public RestResult data(T param) {\n this.setData(param);\n return this;\n }\n\n // 自定义状态信息\n public RestResult message(String message) {\n this.setMessage(message);\n return this;\n }\n\n // 自定义状态码\n public RestResult code(Integer code) {\n this.setCode(code);\n return this;\n }\n\n // 设置结果,形参为结果枚举\n public static RestResult setResult(ResultCodeEnum result) {\n RestResult r = new RestResult();\n r.setSuccess(result.getSuccess());\n r.setCode(result.getCode());\n r.setMessage(result.getMessage());\n return r;\n }\n\n // 通用返回成功\n public static RestResult success() {\n RestResult r = new RestResult();\n r.setSuccess(ResultCodeEnum.SUCCESS.getSuccess());\n r.setCode(ResultCodeEnum.SUCCESS.getCode());\n r.setMessage(ResultCodeEnum.SUCCESS.getMessage());\n return r;\n }\n\n // 通用返回失败,未知错误\n public static RestResult fail() {\n RestResult r = new RestResult();\n r.setSuccess(ResultCodeEnum.UNKNOWN_ERROR.getSuccess());\n r.setCode(ResultCodeEnum.UNKNOWN_ERROR.getCode());\n r.setMessage(ResultCodeEnum.UNKNOWN_ERROR.getMessage());\n return r;\n }\n\n}" }, { "identifier": "ResultCodeEnum", "path": "file-web/src/main/java/com/disk/file/common/ResultCodeEnum.java", "snippet": "@Getter\npublic enum ResultCodeEnum {\n SUCCESS(true,20000,\"成功\"),\n UNKNOWN_ERROR(false,20001,\"未知错误\"),\n PARAM_ERROR(false,20002,\"参数错误\"),\n NULL_POINT(false, 20003, \"空指针异常\"),\n INDEX_OUT_OF_BOUNDS(false, 20004, \"下标越界异常\"),\n ;\n\n // 响应是否成功\n private Boolean success;\n // 响应状态码\n private Integer code;\n // 响应信息\n private String message;\n\n ResultCodeEnum(boolean success, Integer code, String message) {\n this.success = success;\n this.code = code;\n this.message = message;\n }\n}" } ]
import com.disk.file.common.RestResult; import com.disk.file.common.ResultCodeEnum; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; import lombok.extern.slf4j.Slf4j;
687
package com.disk.file.advice; @Slf4j @ControllerAdvice public class GlobalExceptionHandlerAdvice { /**-------- 通用异常处理方法 --------**/ @ExceptionHandler(Exception.class) @ResponseBody
package com.disk.file.advice; @Slf4j @ControllerAdvice public class GlobalExceptionHandlerAdvice { /**-------- 通用异常处理方法 --------**/ @ExceptionHandler(Exception.class) @ResponseBody
public RestResult error(Exception e) {
0
2023-12-17 05:12:43+00:00
2k
ReChronoRain/HyperCeiler
app/src/main/java/com/sevtinge/hyperceiler/utils/log/XposedLogUtils.java
[ { "identifier": "logLevel", "path": "app/src/main/java/com/sevtinge/hyperceiler/utils/log/LogManager.java", "snippet": "public static int logLevel = getLogLevel();" }, { "identifier": "XposedInit", "path": "app/src/main/java/com/sevtinge/hyperceiler/XposedInit.java", "snippet": "public class XposedInit extends BaseXposedInit implements IXposedHookInitPackageResources {\n private final String TAG = \"HyperCeiler\";\n\n @Override\n public void initZygote(IXposedHookZygoteInit.StartupParam startupParam) throws Throwable {\n super.initZygote(startupParam);\n if (mPrefsMap.getBoolean(\"system_framework_allow_uninstall\")) new AllowUninstall().initZygote(startupParam);\n if (mPrefsMap.getBoolean(\"system_framework_screen_all_rotations\")) ScreenRotation.initRes();\n if (mPrefsMap.getBoolean(\"system_framework_clean_share_menu\")) CleanShareMenu.initRes();\n if (mPrefsMap.getBoolean(\"system_framework_clean_open_menu\")) CleanOpenMenu.initRes();\n if (mPrefsMap.getBoolean(\"system_framework_volume_separate_control\")) VolumeSeparateControlForSettings.initRes();\n if (mPrefsMap.getBoolean(\"system_framework_allow_manage_all_notifications\")) new AllowManageAllNotifications().initZygote(startupParam);\n if (startupParam != null) {\n new BackgroundBlurDrawable().initZygote(startupParam);\n new SystemFrameworkForCorePatch().initZygote(startupParam);\n }\n }\n\n @Override\n public void handleLoadPackage(XC_LoadPackage.LoadPackageParam lpparam) throws Throwable {\n EzXHelper.initHandleLoadPackage(lpparam);\n EzXHelper.setLogTag(TAG);\n EzXHelper.setToastTag(TAG);\n\n init(lpparam);\n new SystemFrameworkForCorePatch().handleLoadPackage(lpparam);\n }\n\n @Override\n public void handleInitPackageResources(XC_InitPackageResources.InitPackageResourcesParam resparam) throws Throwable {\n switch (resparam.packageName) {\n case \"com.miui.tsmclient\":\n if (mPrefsMap.getBoolean(\"tsmclient_auto_nfc\")) {\n AutoNfc.INSTANCE.initResource(resparam);\n }\n break;\n\n case \"com.miui.home\":\n if (mPrefsMap.getBoolean(\"home_other_icon_monet_color\")) {\n EnableIconMonetColor.INSTANCE.initResource(resparam);\n }\n if (mPrefsMap.getBoolean(\"home_other_allow_share_apk\")) {\n new AllowShareApk().initResource(resparam);\n }\n break;\n\n case \"com.miui.securitycenter\":\n if (mPrefsMap.getBoolean(\"security_center_sidebar_line_color\")) {\n SidebarLineCustom.INSTANCE.initResource(resparam);\n }\n break;\n\n case \"com.android.systemui\":\n if (mPrefsMap.getBoolean(\"system_ui_navigation_handle_custom\")) {\n HandleLineCustom.INSTANCE.initResource(resparam);\n }\n break;\n }\n }\n}" }, { "identifier": "PrefsMap", "path": "app/src/main/java/com/sevtinge/hyperceiler/utils/PrefsMap.java", "snippet": "public class PrefsMap<K, V> extends HashMap<K, V> {\n\n public Object getObject(String key, Object defValue) {\n return get(key) == null ? defValue : get(key);\n }\n\n public int getInt(String key, int defValue) {\n key = \"prefs_key_\" + key;\n return get(key) == null ? defValue : (Integer) get(key);\n }\n\n public String getString(String key, String defValue) {\n key = \"prefs_key_\" + key;\n return get(key) == null ? defValue : (String) get(key);\n }\n\n public int getStringAsInt(String key, int defValue) {\n key = \"prefs_key_\" + key;\n return get(key) == null ? defValue : Integer.parseInt((String) get(key));\n }\n\n @SuppressWarnings(\"unchecked\")\n public Set<String> getStringSet(String key) {\n key = \"prefs_key_\" + key;\n return get(key) == null ? new LinkedHashSet<>() : (Set<String>) get(key);\n }\n\n public boolean getBoolean(String key) {\n key = \"prefs_key_\" + key;\n return get(key) == null ? false : (Boolean) get(key);\n }\n\n}" } ]
import static com.sevtinge.hyperceiler.utils.log.LogManager.logLevel; import com.sevtinge.hyperceiler.XposedInit; import com.sevtinge.hyperceiler.utils.PrefsMap; import de.robv.android.xposed.XposedBridge;
1,132
package com.sevtinge.hyperceiler.utils.log; public class XposedLogUtils { public static final PrefsMap<String, Object> mPrefsMap = XposedInit.mPrefsMap; public static void logI(String msg) {
package com.sevtinge.hyperceiler.utils.log; public class XposedLogUtils { public static final PrefsMap<String, Object> mPrefsMap = XposedInit.mPrefsMap; public static void logI(String msg) {
if (logLevel < 3) return;
0
2023-10-27 17:17:42+00:00
2k
thebatmanfuture/fofa_search
src/main/java/org/fofaviewer/utils/RequestUtil.java
[ { "identifier": "FofaConfig", "path": "src/main/java/org/fofaviewer/main/FofaConfig.java", "snippet": "public class FofaConfig {\n private static FofaConfig config = null;\n private boolean checkStatus;\n private String email;\n private String key;\n private final String page = \"1\";\n public final int max = 10000;\n private String size = \"1000\";\n public String API = \"https://fofa.info\";\n public String personalInfoAPI = \"https://fofa.info/api/v1/info/my?email=%s&key=%s\";\n public final String path = \"/api/v1/search/all\";\n public static final String TIP_API = \"https://api.fofa.info/v1/search/tip?q=\";\n //public static final String TIP_API = Locale.getDefault()==Locale.CHINA ? \"https://api.fofa.so/v1/search/tip?q=\"\n public ArrayList<String> fields = new ArrayList<String>(){{add(\"host\");add(\"ip\");add(\"domain\");add(\"port\");add(\"protocol\");add(\"server\");}};//title,cert\";\n\n private FofaConfig(){\n this.email = \"\";\n this.key = \"\";\n }\n\n public static FofaConfig getInstance(){\n if (config == null) {\n config = new FofaConfig();\n }\n return config;\n }\n\n public String getEmail() {\n return email;\n }\n\n public String getKey() {\n return key;\n }\n\n public void setEmail(String email) {\n this.email = email;\n }\n\n public void setKey(String key) {\n this.key = key;\n }\n\n public void setAPI(String API) {\n this.API = API;\n }\n\n public String getSize() {\n return this.size;\n }\n\n public void setSize(String size){\n this.size = size;\n }\n\n public String getParam(String page, boolean isAll) {\n String all = isAll ? \"&full=true\" : \"\";\n StringBuilder builder = new StringBuilder(API).append(path).append(\"?email=\").append(email).append(\"&key=\").append(key).append(all).append(\"&page=\");\n if(page != null) {\n return builder.append(page).append(\"&size=\").append(size).append(\"&fields=\").append(getFields()).append(\"&qbase64=\").toString();\n }else{\n return builder.append(this.page).append(\"&size=\").append(size).append(\"&fields=\").append(getFields()).append(\"&qbase64=\").toString();\n }\n }\n\n public String getFields(){\n StringBuilder builder = new StringBuilder();\n for(String i : this.fields){\n builder.append(i).append(\",\");\n }\n String a = builder.toString();\n return a.substring(0,a.length()-1);\n }\n\n public boolean getCheckStatus() {\n return checkStatus;\n }\n\n public void setCheckStatus(boolean checkStatus) {\n this.checkStatus = checkStatus;\n }\n}" }, { "identifier": "ProxyConfig", "path": "src/main/java/org/fofaviewer/main/ProxyConfig.java", "snippet": "public class ProxyConfig {\n public enum ProxyType {HTTP, SOCKS5 }\n private static ProxyConfig config;\n private boolean status;\n private ProxyType proxy_type;\n private String proxy_ip;\n private String proxy_port;\n private String proxy_user;\n private String proxy_password;\n\n private ProxyConfig() {\n status = false;\n proxy_type = ProxyType.HTTP;\n proxy_ip = \"\";\n proxy_port = \"\";\n proxy_password = \"\";\n proxy_user = \"\";\n }\n public static ProxyConfig getInstance(){\n if (config == null) {\n config = new ProxyConfig();\n }\n return config;\n }\n\n public Proxy getProxy() {\n if(!this.proxy_user.equals(\"\") && !this.proxy_password.equals(\"\")){\n Authenticator.setDefault(new Authenticator(){\n public PasswordAuthentication getPasswordAuthentication() {\n return (new PasswordAuthentication(proxy_user, proxy_password.toCharArray()));\n }\n });\n }else{\n Authenticator.setDefault(null);\n }\n switch (this.proxy_type){\n case HTTP: return Proxies.httpProxy(this.proxy_ip, Integer.parseInt(this.proxy_port));\n case SOCKS5: return Proxies.socksProxy(this.proxy_ip, Integer.parseInt(this.proxy_port));\n }\n return null;\n }\n\n public void setProxy_type(ProxyType proxy_type) {\n this.proxy_type = proxy_type;\n }\n\n public String getProxy_ip() {\n return proxy_ip;\n }\n\n public void setProxy_ip(String proxy_ip) {\n this.proxy_ip = proxy_ip;\n }\n\n public String getProxy_port() {\n return proxy_port;\n }\n\n public void setProxy_port(String proxy_port) {\n this.proxy_port = proxy_port;\n }\n\n public String getProxy_user() {\n return proxy_user;\n }\n\n public void setProxy_user(String proxy_user) {\n this.proxy_user = proxy_user;\n }\n\n public String getProxy_password() {\n return proxy_password;\n }\n\n public void setProxy_password(String proxy_password) {\n this.proxy_password = proxy_password;\n }\n\n public boolean getStatus() {\n return status;\n }\n\n public void setStatus(boolean status) {\n this.status = status;\n }\n}" } ]
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import me.gv7.woodpecker.requests.*; import me.gv7.woodpecker.requests.exception.RequestsException; import org.fofaviewer.main.FofaConfig; import org.fofaviewer.main.ProxyConfig; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import javax.net.ssl.*; import java.net.URL; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.security.KeyFactory; import java.security.PrivateKey; import java.security.SecureRandom; import java.security.Signature; import java.security.cert.Certificate; import java.security.cert.X509Certificate; import java.security.spec.PKCS8EncodedKeySpec; import java.sql.Timestamp; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.google.common.hash.Hashing; import org.tinylog.Logger;
1,511
package org.fofaviewer.utils; public class RequestUtil { private static RequestUtil request = null;
package org.fofaviewer.utils; public class RequestUtil { private static RequestUtil request = null;
private ProxyConfig config;
1
2023-10-25 11:13:47+00:00
2k
amithkoujalgi/ollama4j
src/main/java/io/github/amithkoujalgi/ollama4j/core/OllamaAPI.java
[ { "identifier": "OllamaBaseException", "path": "src/main/java/io/github/amithkoujalgi/ollama4j/core/exceptions/OllamaBaseException.java", "snippet": "public class OllamaBaseException extends Exception {\n\n public OllamaBaseException(String s) {\n super(s);\n }\n}" }, { "identifier": "CustomModelFileContentsRequest", "path": "src/main/java/io/github/amithkoujalgi/ollama4j/core/models/request/CustomModelFileContentsRequest.java", "snippet": "@Data\n@AllArgsConstructor\npublic class CustomModelFileContentsRequest {\n private String name;\n private String modelfile;\n\n @Override\n public String toString() {\n try {\n return getObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(this);\n } catch (JsonProcessingException e) {\n throw new RuntimeException(e);\n }\n }\n}" }, { "identifier": "CustomModelFilePathRequest", "path": "src/main/java/io/github/amithkoujalgi/ollama4j/core/models/request/CustomModelFilePathRequest.java", "snippet": "@Data\n@AllArgsConstructor\npublic class CustomModelFilePathRequest {\n private String name;\n private String path;\n\n @Override\n public String toString() {\n try {\n return getObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(this);\n } catch (JsonProcessingException e) {\n throw new RuntimeException(e);\n }\n }\n}" }, { "identifier": "ModelEmbeddingsRequest", "path": "src/main/java/io/github/amithkoujalgi/ollama4j/core/models/request/ModelEmbeddingsRequest.java", "snippet": "@Data\n@AllArgsConstructor\npublic class ModelEmbeddingsRequest {\n private String model;\n private String prompt;\n\n @Override\n public String toString() {\n try {\n return getObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(this);\n } catch (JsonProcessingException e) {\n throw new RuntimeException(e);\n }\n }\n}" }, { "identifier": "ModelRequest", "path": "src/main/java/io/github/amithkoujalgi/ollama4j/core/models/request/ModelRequest.java", "snippet": "@Data\n@AllArgsConstructor\npublic class ModelRequest {\n private String name;\n\n @Override\n public String toString() {\n try {\n return getObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(this);\n } catch (JsonProcessingException e) {\n throw new RuntimeException(e);\n }\n }\n}" }, { "identifier": "Options", "path": "src/main/java/io/github/amithkoujalgi/ollama4j/core/utils/Options.java", "snippet": "@Data\npublic class Options {\n\n private final Map<String, Object> optionsMap;\n}" }, { "identifier": "Utils", "path": "src/main/java/io/github/amithkoujalgi/ollama4j/core/utils/Utils.java", "snippet": "public class Utils {\n public static ObjectMapper getObjectMapper() {\n return new ObjectMapper();\n }\n}" } ]
import io.github.amithkoujalgi.ollama4j.core.exceptions.OllamaBaseException; import io.github.amithkoujalgi.ollama4j.core.models.*; import io.github.amithkoujalgi.ollama4j.core.models.request.CustomModelFileContentsRequest; import io.github.amithkoujalgi.ollama4j.core.models.request.CustomModelFilePathRequest; import io.github.amithkoujalgi.ollama4j.core.models.request.ModelEmbeddingsRequest; import io.github.amithkoujalgi.ollama4j.core.models.request.ModelRequest; import io.github.amithkoujalgi.ollama4j.core.utils.Options; import io.github.amithkoujalgi.ollama4j.core.utils.Utils; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.net.http.HttpClient; import java.net.http.HttpConnectTimeoutException; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.time.Duration; import java.util.ArrayList; import java.util.Base64; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
1,503
package io.github.amithkoujalgi.ollama4j.core; /** The base Ollama API class. */ @SuppressWarnings("DuplicatedCode") public class OllamaAPI { private static final Logger logger = LoggerFactory.getLogger(OllamaAPI.class); private final String host; private long requestTimeoutSeconds = 3; private boolean verbose = true; private BasicAuth basicAuth; /** * Instantiates the Ollama API. * * @param host the host address of Ollama server */ public OllamaAPI(String host) { if (host.endsWith("/")) { this.host = host.substring(0, host.length() - 1); } else { this.host = host; } } /** * Set request timeout in seconds. Default is 3 seconds. * * @param requestTimeoutSeconds the request timeout in seconds */ public void setRequestTimeoutSeconds(long requestTimeoutSeconds) { this.requestTimeoutSeconds = requestTimeoutSeconds; } /** * Set/unset logging of responses * * @param verbose true/false */ public void setVerbose(boolean verbose) { this.verbose = verbose; } /** * Set basic authentication for accessing Ollama server that's behind a reverse-proxy/gateway. * * @param username the username * @param password the password */ public void setBasicAuth(String username, String password) { this.basicAuth = new BasicAuth(username, password); } /** * API to check the reachability of Ollama server. * * @return true if the server is reachable, false otherwise. */ public boolean ping() { String url = this.host + "/api/tags"; HttpClient httpClient = HttpClient.newHttpClient(); HttpRequest httpRequest = null; try { httpRequest = getRequestBuilderDefault(new URI(url)) .header("Accept", "application/json") .header("Content-type", "application/json") .GET() .build(); } catch (URISyntaxException e) { throw new RuntimeException(e); } HttpResponse<String> response = null; try { response = httpClient.send(httpRequest, HttpResponse.BodyHandlers.ofString()); } catch (HttpConnectTimeoutException e) { return false; } catch (IOException | InterruptedException e) { throw new RuntimeException(e); } int statusCode = response.statusCode(); return statusCode == 200; } /** * List available models from Ollama server. * * @return the list */ public List<Model> listModels()
package io.github.amithkoujalgi.ollama4j.core; /** The base Ollama API class. */ @SuppressWarnings("DuplicatedCode") public class OllamaAPI { private static final Logger logger = LoggerFactory.getLogger(OllamaAPI.class); private final String host; private long requestTimeoutSeconds = 3; private boolean verbose = true; private BasicAuth basicAuth; /** * Instantiates the Ollama API. * * @param host the host address of Ollama server */ public OllamaAPI(String host) { if (host.endsWith("/")) { this.host = host.substring(0, host.length() - 1); } else { this.host = host; } } /** * Set request timeout in seconds. Default is 3 seconds. * * @param requestTimeoutSeconds the request timeout in seconds */ public void setRequestTimeoutSeconds(long requestTimeoutSeconds) { this.requestTimeoutSeconds = requestTimeoutSeconds; } /** * Set/unset logging of responses * * @param verbose true/false */ public void setVerbose(boolean verbose) { this.verbose = verbose; } /** * Set basic authentication for accessing Ollama server that's behind a reverse-proxy/gateway. * * @param username the username * @param password the password */ public void setBasicAuth(String username, String password) { this.basicAuth = new BasicAuth(username, password); } /** * API to check the reachability of Ollama server. * * @return true if the server is reachable, false otherwise. */ public boolean ping() { String url = this.host + "/api/tags"; HttpClient httpClient = HttpClient.newHttpClient(); HttpRequest httpRequest = null; try { httpRequest = getRequestBuilderDefault(new URI(url)) .header("Accept", "application/json") .header("Content-type", "application/json") .GET() .build(); } catch (URISyntaxException e) { throw new RuntimeException(e); } HttpResponse<String> response = null; try { response = httpClient.send(httpRequest, HttpResponse.BodyHandlers.ofString()); } catch (HttpConnectTimeoutException e) { return false; } catch (IOException | InterruptedException e) { throw new RuntimeException(e); } int statusCode = response.statusCode(); return statusCode == 200; } /** * List available models from Ollama server. * * @return the list */ public List<Model> listModels()
throws OllamaBaseException, IOException, InterruptedException, URISyntaxException {
0
2023-10-26 19:12:14+00:00
2k
rweisleder/archunit-spring
src/test/java/de/rweisleder/archunit/spring/SpringComponentPredicatesTest.java
[ { "identifier": "ComponentWithoutDependency", "path": "src/test/java/de/rweisleder/archunit/spring/testclasses/component/SpringComponents.java", "snippet": "@Component\npublic static class ComponentWithoutDependency {\n}" }, { "identifier": "ConfigurationWithoutDependency", "path": "src/test/java/de/rweisleder/archunit/spring/testclasses/component/SpringComponents.java", "snippet": "@Configuration\npublic static class ConfigurationWithoutDependency {\n}" }, { "identifier": "ControllerWithoutDependency", "path": "src/test/java/de/rweisleder/archunit/spring/testclasses/component/SpringComponents.java", "snippet": "@Controller\npublic static class ControllerWithoutDependency {\n}" }, { "identifier": "RepositoryWithoutDependency", "path": "src/test/java/de/rweisleder/archunit/spring/testclasses/component/SpringComponents.java", "snippet": "@Repository\npublic static class RepositoryWithoutDependency {\n}" }, { "identifier": "ServiceWithoutDependency", "path": "src/test/java/de/rweisleder/archunit/spring/testclasses/component/SpringComponents.java", "snippet": "@Service\npublic static class ServiceWithoutDependency {\n}" }, { "identifier": "SpringDataRepositoryWithoutDependency", "path": "src/test/java/de/rweisleder/archunit/spring/testclasses/component/SpringComponents.java", "snippet": "public abstract static class SpringDataRepositoryWithoutDependency implements CrudRepository<Object, Object> {\n}" }, { "identifier": "springComponent", "path": "src/main/java/de/rweisleder/archunit/spring/SpringComponentPredicates.java", "snippet": "public static DescribedPredicate<JavaClass> springComponent() {\n DescribedPredicate<JavaClass> hasComponentAnnotation = springAnnotatedWith(\"org.springframework.stereotype.Component\").forSubtype();\n DescribedPredicate<JavaClass> isSpringDataRepository = springDataRepository();\n return hasComponentAnnotation.or(isSpringDataRepository).as(\"Spring component\");\n}" }, { "identifier": "springConfiguration", "path": "src/main/java/de/rweisleder/archunit/spring/SpringComponentPredicates.java", "snippet": "public static DescribedPredicate<JavaClass> springConfiguration() {\n return springAnnotatedWith(\"org.springframework.context.annotation.Configuration\")\n .as(\"Spring configuration\").forSubtype();\n}" }, { "identifier": "springController", "path": "src/main/java/de/rweisleder/archunit/spring/SpringComponentPredicates.java", "snippet": "public static DescribedPredicate<JavaClass> springController() {\n return springAnnotatedWith(\"org.springframework.stereotype.Controller\")\n .as(\"Spring controller\").forSubtype();\n}" }, { "identifier": "springRepository", "path": "src/main/java/de/rweisleder/archunit/spring/SpringComponentPredicates.java", "snippet": "public static DescribedPredicate<JavaClass> springRepository() {\n DescribedPredicate<JavaClass> hasRepositoryAnnotation = springAnnotatedWith(\"org.springframework.stereotype.Repository\").forSubtype();\n DescribedPredicate<JavaClass> isSpringDataRepository = springDataRepository();\n\n return hasRepositoryAnnotation.or(isSpringDataRepository)\n .as(\"Spring repository\");\n}" }, { "identifier": "springService", "path": "src/main/java/de/rweisleder/archunit/spring/SpringComponentPredicates.java", "snippet": "public static DescribedPredicate<JavaClass> springService() {\n return springAnnotatedWith(\"org.springframework.stereotype.Service\")\n .as(\"Spring service\").forSubtype();\n}" }, { "identifier": "importClass", "path": "src/test/java/de/rweisleder/archunit/spring/TestUtils.java", "snippet": "public static JavaClass importClass(Class<?> classToImport) {\n return new ClassFileImporter().importClass(classToImport);\n}" } ]
import static de.rweisleder.archunit.spring.SpringComponentPredicates.springComponent; import static de.rweisleder.archunit.spring.SpringComponentPredicates.springConfiguration; import static de.rweisleder.archunit.spring.SpringComponentPredicates.springController; import static de.rweisleder.archunit.spring.SpringComponentPredicates.springRepository; import static de.rweisleder.archunit.spring.SpringComponentPredicates.springService; import static de.rweisleder.archunit.spring.TestUtils.importClass; import static org.assertj.core.api.Assertions.assertThat; import com.tngtech.archunit.base.DescribedPredicate; import com.tngtech.archunit.core.domain.JavaClass; import de.rweisleder.archunit.spring.testclasses.component.SpringComponents.ComponentWithoutDependency; import de.rweisleder.archunit.spring.testclasses.component.SpringComponents.ConfigurationWithoutDependency; import de.rweisleder.archunit.spring.testclasses.component.SpringComponents.ControllerWithoutDependency; import de.rweisleder.archunit.spring.testclasses.component.SpringComponents.RepositoryWithoutDependency; import de.rweisleder.archunit.spring.testclasses.component.SpringComponents.ServiceWithoutDependency; import de.rweisleder.archunit.spring.testclasses.component.SpringComponents.SpringDataRepositoryWithoutDependency; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; import org.springframework.data.repository.CrudRepository;
1,462
/* * #%L * ArchUnit Spring Integration * %% * Copyright (C) 2023 Roland Weisleder * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ package de.rweisleder.archunit.spring; class SpringComponentPredicatesTest { @Nested class Predicate_springComponent { @Test void provides_a_description() { DescribedPredicate<JavaClass> predicate = springComponent(); assertThat(predicate.getDescription()).isEqualTo("Spring component"); } @Test void accepts_class_annotated_with_Component() { JavaClass componentClass = importClass(ComponentWithoutDependency.class); DescribedPredicate<JavaClass> predicate = springComponent(); assertThat(predicate).accepts(componentClass); } @Test void accepts_class_annotated_with_Configuration() { JavaClass configurationClass = importClass(ConfigurationWithoutDependency.class); DescribedPredicate<JavaClass> predicate = springComponent(); assertThat(predicate).accepts(configurationClass); } @Test void accepts_class_annotated_with_Controller() { JavaClass controllerClass = importClass(ControllerWithoutDependency.class); DescribedPredicate<JavaClass> predicate = springComponent(); assertThat(predicate).accepts(controllerClass); } @Test void accepts_class_annotated_with_Service() { JavaClass serviceClass = importClass(ServiceWithoutDependency.class); DescribedPredicate<JavaClass> predicate = springComponent(); assertThat(predicate).accepts(serviceClass); } @Test void accepts_class_annotated_with_Repository() { JavaClass repositoryClass = importClass(RepositoryWithoutDependency.class); DescribedPredicate<JavaClass> predicate = springComponent(); assertThat(predicate).accepts(repositoryClass); } @Test void accepts_class_implementing_Spring_Data_Repository() {
/* * #%L * ArchUnit Spring Integration * %% * Copyright (C) 2023 Roland Weisleder * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ package de.rweisleder.archunit.spring; class SpringComponentPredicatesTest { @Nested class Predicate_springComponent { @Test void provides_a_description() { DescribedPredicate<JavaClass> predicate = springComponent(); assertThat(predicate.getDescription()).isEqualTo("Spring component"); } @Test void accepts_class_annotated_with_Component() { JavaClass componentClass = importClass(ComponentWithoutDependency.class); DescribedPredicate<JavaClass> predicate = springComponent(); assertThat(predicate).accepts(componentClass); } @Test void accepts_class_annotated_with_Configuration() { JavaClass configurationClass = importClass(ConfigurationWithoutDependency.class); DescribedPredicate<JavaClass> predicate = springComponent(); assertThat(predicate).accepts(configurationClass); } @Test void accepts_class_annotated_with_Controller() { JavaClass controllerClass = importClass(ControllerWithoutDependency.class); DescribedPredicate<JavaClass> predicate = springComponent(); assertThat(predicate).accepts(controllerClass); } @Test void accepts_class_annotated_with_Service() { JavaClass serviceClass = importClass(ServiceWithoutDependency.class); DescribedPredicate<JavaClass> predicate = springComponent(); assertThat(predicate).accepts(serviceClass); } @Test void accepts_class_annotated_with_Repository() { JavaClass repositoryClass = importClass(RepositoryWithoutDependency.class); DescribedPredicate<JavaClass> predicate = springComponent(); assertThat(predicate).accepts(repositoryClass); } @Test void accepts_class_implementing_Spring_Data_Repository() {
JavaClass repositoryClass = importClass(SpringDataRepositoryWithoutDependency.class);
5
2023-10-29 10:50:24+00:00
2k
cybertheye/evolution-from-netty-to-springboot
mimic-tomcat/src/main/java/com/attackonarchitect/handler/MimicHttpInBoundHandler.java
[ { "identifier": "Notifier", "path": "mimic-tomcat/src/main/java/com/attackonarchitect/listener/Notifier.java", "snippet": "public interface Notifier {\n void notifyListeners(Class<?> listener ,Event event);\n}" }, { "identifier": "ServletRequestEvent", "path": "mimic-tomcat/src/main/java/com/attackonarchitect/listener/request/ServletRequestEvent.java", "snippet": "public class ServletRequestEvent implements Event {\n}" }, { "identifier": "ServletRequestListener", "path": "mimic-tomcat/src/main/java/com/attackonarchitect/listener/request/ServletRequestListener.java", "snippet": "public interface ServletRequestListener extends EventListener {\n void requestInitialized();\n}" }, { "identifier": "ServletContext", "path": "mimic-tomcat/src/main/java/com/attackonarchitect/context/ServletContext.java", "snippet": "public interface ServletContext {\n\n /**\n * 设置一个属性\n * @param name\n * @param obj\n */\n <T> void setAttribute(String name, T obj);\n\n /**\n * 取一个属性\n * @param name\n * @return\n */\n Object getAttribute(String name);\n// void register(EventListener listener);\n//\n// void registerAll(List<String> listeners);\n//\n\n Notifier getNotifiler();\n}" } ]
import com.attackonarchitect.listener.Notifier; import com.attackonarchitect.listener.request.ServletRequestEvent; import com.attackonarchitect.listener.request.ServletRequestListener; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.handler.codec.http.HttpRequest; import com.attackonarchitect.context.ServletContext; import com.attackonarchitect.http.*; import java.util.Arrays; import java.util.HashMap; import java.util.Map;
722
package com.attackonarchitect.handler; /** * @description: 这里表示一个请求在web 应用中的最开端,表示初始化开始 * */ public class MimicHttpInBoundHandler extends ChannelInboundHandlerAdapter { private ServletContext servletContext; public MimicHttpInBoundHandler(ServletContext servletContext) { this.servletContext = servletContext; } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { HttpRequest req = (HttpRequest) msg; HttpMTRequest request = HttpRequestProxyFactory.createProxy(req,servletContext).createRequest(); Map<String,String> parameters = new HashMap<>(); this.parseParameters(req,parameters); request.setParametersDepot(parameters); ServletRequestEvent servletRequestEvent = new ServletRequestEvent(); //todo set属性 this.notifyRequestListener(servletRequestEvent); super.channelRead(ctx, request); } private void parseParameters(HttpRequest req, Map<String, String> parameters) { String uri = req.uri(); // 需要支持没有参数 if(!uri.contains("?")) return; String parametersPart = uri.split("\\?")[1]; // name=cy&password=123456 String[] paramParts = parametersPart.split("&"); Arrays.stream(paramParts).forEach(pairParam->{ String[] ps = pairParam.split("="); parameters.put(ps[0],ps[1]); }); } private void notifyRequestListener(ServletRequestEvent sre) { Notifier notifier = (Notifier) servletContext.getAttribute("notifier");
package com.attackonarchitect.handler; /** * @description: 这里表示一个请求在web 应用中的最开端,表示初始化开始 * */ public class MimicHttpInBoundHandler extends ChannelInboundHandlerAdapter { private ServletContext servletContext; public MimicHttpInBoundHandler(ServletContext servletContext) { this.servletContext = servletContext; } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { HttpRequest req = (HttpRequest) msg; HttpMTRequest request = HttpRequestProxyFactory.createProxy(req,servletContext).createRequest(); Map<String,String> parameters = new HashMap<>(); this.parseParameters(req,parameters); request.setParametersDepot(parameters); ServletRequestEvent servletRequestEvent = new ServletRequestEvent(); //todo set属性 this.notifyRequestListener(servletRequestEvent); super.channelRead(ctx, request); } private void parseParameters(HttpRequest req, Map<String, String> parameters) { String uri = req.uri(); // 需要支持没有参数 if(!uri.contains("?")) return; String parametersPart = uri.split("\\?")[1]; // name=cy&password=123456 String[] paramParts = parametersPart.split("&"); Arrays.stream(paramParts).forEach(pairParam->{ String[] ps = pairParam.split("="); parameters.put(ps[0],ps[1]); }); } private void notifyRequestListener(ServletRequestEvent sre) { Notifier notifier = (Notifier) servletContext.getAttribute("notifier");
notifier.notifyListeners(ServletRequestListener.class,sre);
2
2023-10-31 07:16:50+00:00
2k
Changbaiqi/yatori
yatori-core/src/main/java/com/cbq/yatori/core/action/yinghua/LoginAction.java
[ { "identifier": "AccountCacheYingHua", "path": "yatori-core/src/main/java/com/cbq/yatori/core/entity/AccountCacheYingHua.java", "snippet": "@Data\npublic class AccountCacheYingHua implements AccountCache {\n private String session;\n private String token;\n private String code;\n /**\n * 新添加账号状态,0代表未登录,1代表正常登录,2代表登录超时\n */\n private Integer status=0;\n}" }, { "identifier": "User", "path": "yatori-core/src/main/java/com/cbq/yatori/core/entity/User.java", "snippet": "@Data\n@Builder\n@AllArgsConstructor\n@NoArgsConstructor\n@JsonIgnoreProperties(ignoreUnknown = true)\npublic class User {\n private AccountType accountType; //对应账号平台类型\n private String url; //课程平台url\n private String account; //密码\n private String password; //账号\n private AccountCache cache; //账号缓存信息\n private CoursesCostom coursesCostom=new CoursesCostom(); //客制化课程\n}" }, { "identifier": "FileUtils", "path": "yatori-core/src/main/java/com/cbq/yatori/core/utils/FileUtils.java", "snippet": "public class FileUtils {\n private final static String PATH=\"cache\";\n\n static {\n File file = new File(PATH);\n if(!file.exists()){\n file.mkdir();\n }\n }\n public static File saveFile(byte bytes[], String fileName) {\n try {\n InputStream in = new ByteArrayInputStream(bytes);\n FileOutputStream file = new FileOutputStream(PATH+\"/\"+fileName);\n\n int j;\n while ((j = in.read()) != -1) {\n file.write(j);\n }\n file.flush();\n file.close();\n in.close();\n File file1 = new File(PATH+\"/\"+fileName);\n return file1;\n } catch (FileNotFoundException e) {\n throw new RuntimeException(e);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n\n /**\n * 删除文件\n * @param file\n * @return\n */\n public static boolean deleteFile(File file){\n if(file.isFile() && file.exists()){\n file.delete();\n return true;\n }\n return false;\n }\n\n /**\n * 读取指定路径下的文本文件并返回文本字符串\n * @param file\n * @return\n */\n public static String readTxt(File file){\n if(!file.exists()){\n System.out.println(\"配置文件不存在!!!\");\n return null;\n }\n\n String text = \"\";\n try {\n InputStream inputStream = new FileInputStream(file);\n InputStreamReader inputStreamReader = new InputStreamReader(inputStream,getCharsetName(file));\n //FileReader fileReader = new FileReader(file);\n BufferedReader br = new BufferedReader(inputStreamReader);\n String res = null;\n while((res = br.readLine())!=null){\n text+=res;\n }\n } catch (FileNotFoundException e) {\n throw new RuntimeException(e);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n return text;\n }\n\n /**\n * 获取文件编码字符串\n *\n * @param file\n * @return\n */\n public static String getCharsetName(File file) throws IOException {\n InputStream is = Files.newInputStream(file.toPath());\n BufferedInputStream reader = new BufferedInputStream(is);\n byte[] buff = new byte[1024];\n int len = 0;\n// 检测文件编码\n UniversalDetector detector = new UniversalDetector(null);\n while ((len = reader.read(buff)) != -1 && !detector.isDone()) {\n detector.handleData(buff, 0, len);\n }\n detector.dataEnd();\n// 获取编码类型\n String encoding = detector.getDetectedCharset();\n detector.reset();\n reader.close();\n return encoding;\n }\n}" }, { "identifier": "VerificationCodeUtil", "path": "yatori-core/src/main/java/com/cbq/yatori/core/utils/VerificationCodeUtil.java", "snippet": "public class VerificationCodeUtil {\n\n public static String aiDiscern(File file){\n OCREngine ocrEngine = OCREngine.instance();\n try {\n return ocrEngine.recognize(IOUtils.read(file.getPath()));\n } catch (IOException ex) {\n throw new RuntimeException(ex);\n }\n }\n}" } ]
import com.cbq.yatori.core.entity.AccountCacheYingHua; import com.cbq.yatori.core.entity.User; import com.cbq.yatori.core.utils.FileUtils; import com.cbq.yatori.core.utils.VerificationCodeUtil; import com.fasterxml.jackson.databind.ObjectMapper; import lombok.extern.slf4j.Slf4j; import okhttp3.*; import java.io.File; import java.io.IOException; import java.net.SocketTimeoutException; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Random; import java.util.regex.Matcher; import java.util.regex.Pattern;
1,183
package com.cbq.yatori.core.action.yinghua; @Slf4j public class LoginAction {
package com.cbq.yatori.core.action.yinghua; @Slf4j public class LoginAction {
public static String getSESSION(User user){
1
2023-10-30 04:15:41+00:00
2k
hezean/sustc
sustc-api/src/main/java/io/sustc/service/DatabaseService.java
[ { "identifier": "DanmuRecord", "path": "sustc-api/src/main/java/io/sustc/dto/DanmuRecord.java", "snippet": "@Data\npublic class DanmuRecord implements Serializable {\n\n /**\n * The danmu's video {@code bv}.\n */\n private String bv;\n\n /**\n * The danmu's sender {@code mid}.\n */\n private long mid;\n\n /**\n * The danmu's display time (in seconds) since the video starts.\n */\n private float time;\n\n /**\n * The danmu's content.\n */\n private String content;\n\n /**\n * The danmu's post time.\n */\n private Timestamp postTime;\n\n /**\n * The users' {@code mid} who liked this danmu.\n */\n private long[] likedBy;\n}" }, { "identifier": "UserRecord", "path": "sustc-api/src/main/java/io/sustc/dto/UserRecord.java", "snippet": "@Data\npublic class UserRecord implements Serializable {\n\n /**\n * The user's unique ID\n */\n private long mid;\n\n /**\n * The user's name\n */\n private String name;\n\n /**\n * The user's sex\n */\n private String sex;\n\n /**\n * The user's birthday, can be empty\n */\n private String birthday;\n\n /**\n * The user's level\n */\n private short level;\n\n /**\n * The user's current number of coins\n */\n private int coin;\n\n /**\n * The user's personal sign, can be null or empty\n */\n private String sign;\n\n /**\n * The user's identity\n */\n private Identity identity;\n\n /**\n * The user's password\n */\n private String password;\n\n /**\n * The user's unique qq, may be null or empty (not unique when null or empty)\n */\n private String qq;\n\n /**\n * The user's unique wechat, may be null or empty (not unique when null or empty)\n */\n private String wechat;\n\n /**\n * The users' {@code mid}s who are followed by this user\n */\n private long[] following;\n\n public enum Identity {\n USER,\n SUPERUSER,\n }\n}" }, { "identifier": "VideoRecord", "path": "sustc-api/src/main/java/io/sustc/dto/VideoRecord.java", "snippet": "@Data\npublic class VideoRecord implements Serializable {\n\n /**\n * The BV code of this video\n */\n private String bv;\n\n /**\n * The title of this video with length >= 1, the video titles of an owner cannot be the same\n */\n private String title;\n\n /**\n * The owner's {@code mid} of this video\n */\n private long ownerMid;\n\n /**\n * The owner's {@code name} of this video\n */\n private String ownerName;\n\n /**\n * The commit time of this video\n */\n private Timestamp commitTime;\n\n /**\n * The review time of this video, can be null\n */\n private Timestamp reviewTime;\n\n /**\n * The public time of this video, can be null\n */\n private Timestamp publicTime;\n\n /**\n * The length in seconds of this video\n */\n private float duration;\n\n /**\n * The description of this video\n */\n private String description;\n\n /**\n * The reviewer of this video, can be null\n */\n private Long reviewer;\n\n /**\n * The users' {@code mid}s who liked this video\n */\n private long[] like;\n\n /**\n * The users' {@code mid}s who gave coin to this video\n */\n private long[] coin;\n\n /**\n * The users' {@code mid}s who collected to this video\n */\n private long[] favorite;\n\n /**\n * The users' {@code mid}s who have watched this video\n */\n private long[] viewerMids;\n\n /**\n * The watch durations in seconds for the viewers {@code viewerMids}\n */\n private float[] viewTime;\n}" } ]
import io.sustc.dto.DanmuRecord; import io.sustc.dto.UserRecord; import io.sustc.dto.VideoRecord; import java.util.List;
1,215
package io.sustc.service; public interface DatabaseService { /** * Acknowledges the authors of this project. * * @return a list of group members' student-id */ List<Integer> getGroupMembers(); /** * Imports data to an empty database. * Invalid data will not be provided. * * @param danmuRecords danmu records parsed from csv * @param userRecords user records parsed from csv * @param videoRecords video records parsed from csv */ void importData(
package io.sustc.service; public interface DatabaseService { /** * Acknowledges the authors of this project. * * @return a list of group members' student-id */ List<Integer> getGroupMembers(); /** * Imports data to an empty database. * Invalid data will not be provided. * * @param danmuRecords danmu records parsed from csv * @param userRecords user records parsed from csv * @param videoRecords video records parsed from csv */ void importData(
List<DanmuRecord> danmuRecords,
0
2023-10-27 03:27:20+00:00
2k
sngular/pact-annotation-processor
src/test/resources/basic/CharacterDataTypesBuilder.java
[ { "identifier": "CustomDslModifier", "path": "src/main/java/com/sngular/annotation/processor/mapping/CustomDslModifier.java", "snippet": "@FunctionalInterface\npublic interface CustomDslModifier {\n\n PactDslJsonBody apply(final PactDslJsonBody pactDslJsonBody);\n\n}" }, { "identifier": "CharacterDataTypes", "path": "src/test/resources/basic/CharacterDataTypes.java", "snippet": "@PactDslBodyBuilder\npublic class CharacterDataTypes {\n\n @Example(\"nameExample\")\n private String name;\n\n @Example(\"a\")\n private char primitiveChar;\n\n @Example(\"b\")\n private Character charObject;\n\n @Example(\"true\")\n private boolean primitiveBoolean;\n\n @Example(\"false\")\n private Boolean booleanObject;\n\n protected String getName() {\n return name;\n }\n\n protected void setName(final String name) {\n this.name = name;\n }\n\n public char getPrimitiveChar() {\n return primitiveChar;\n }\n\n public void setPrimitiveChar(char primitiveChar) {\n this.primitiveChar = primitiveChar;\n }\n\n public Character getCharObject() {\n return charObject;\n }\n\n public void setCharObject(Character charObject) {\n this.charObject = charObject;\n }\n\n public boolean isPrimitiveBoolean() {\n return primitiveBoolean;\n }\n\n public void setPrimitiveBoolean(boolean primitiveBoolean) {\n this.primitiveBoolean = primitiveBoolean;\n }\n\n public Boolean getBooleanObject() {\n return booleanObject;\n }\n\n public void setBooleanObject(Boolean booleanObject) {\n this.booleanObject = booleanObject;\n }\n}" } ]
import java.math.BigDecimal; import java.math.BigInteger; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.time.Instant; import java.time.LocalDate; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.util.Date; import java.util.List; import java.util.Objects; import au.com.dius.pact.consumer.dsl.DslPart; import au.com.dius.pact.consumer.dsl.PactDslJsonArray; import au.com.dius.pact.consumer.dsl.PactDslJsonBody; import au.com.dius.pact.consumer.dsl.PactDslJsonRootValue; import com.sngular.annotation.processor.mapping.CustomDslModifier; import com.sngular.resources.basic.CharacterDataTypes;
928
package com.sngular.resources.basic; public class CharacterDataTypesBuilder { String name = "nameExample"; String primitiveChar = "a"; String charObject = "b"; boolean primitiveBoolean = true; boolean booleanObject = false; public CharacterDataTypesBuilder setName(final String name) { this.name = name; return this; } public CharacterDataTypesBuilder setPrimitiveChar(final String primitiveChar) { this.primitiveChar = primitiveChar; return this; } public CharacterDataTypesBuilder setCharObject(final String charObject) { this.charObject = charObject; return this; } public CharacterDataTypesBuilder setPrimitiveBoolean(final boolean primitiveBoolean) { this.primitiveBoolean = primitiveBoolean; return this; } public CharacterDataTypesBuilder setBooleanObject(final boolean booleanObject) { this.booleanObject = booleanObject; return this; } public DslPart build() { PactDslJsonBody pactDslJsonBody = new PactDslJsonBody(); if (Objects.nonNull(name)) { pactDslJsonBody.stringType("name", name); } if (Objects.nonNull(primitiveChar)) { pactDslJsonBody.stringType("primitiveChar", primitiveChar); } if (Objects.nonNull(charObject)) { pactDslJsonBody.stringType("charObject", charObject); } if (Objects.nonNull(primitiveBoolean)) { pactDslJsonBody.booleanType("primitiveBoolean", primitiveBoolean); } if (Objects.nonNull(booleanObject)) { pactDslJsonBody.booleanType("booleanObject", booleanObject); } return pactDslJsonBody; }
package com.sngular.resources.basic; public class CharacterDataTypesBuilder { String name = "nameExample"; String primitiveChar = "a"; String charObject = "b"; boolean primitiveBoolean = true; boolean booleanObject = false; public CharacterDataTypesBuilder setName(final String name) { this.name = name; return this; } public CharacterDataTypesBuilder setPrimitiveChar(final String primitiveChar) { this.primitiveChar = primitiveChar; return this; } public CharacterDataTypesBuilder setCharObject(final String charObject) { this.charObject = charObject; return this; } public CharacterDataTypesBuilder setPrimitiveBoolean(final boolean primitiveBoolean) { this.primitiveBoolean = primitiveBoolean; return this; } public CharacterDataTypesBuilder setBooleanObject(final boolean booleanObject) { this.booleanObject = booleanObject; return this; } public DslPart build() { PactDslJsonBody pactDslJsonBody = new PactDslJsonBody(); if (Objects.nonNull(name)) { pactDslJsonBody.stringType("name", name); } if (Objects.nonNull(primitiveChar)) { pactDslJsonBody.stringType("primitiveChar", primitiveChar); } if (Objects.nonNull(charObject)) { pactDslJsonBody.stringType("charObject", charObject); } if (Objects.nonNull(primitiveBoolean)) { pactDslJsonBody.booleanType("primitiveBoolean", primitiveBoolean); } if (Objects.nonNull(booleanObject)) { pactDslJsonBody.booleanType("booleanObject", booleanObject); } return pactDslJsonBody; }
public CharacterDataTypes buildExpectedInstance() {
1
2023-10-25 14:36:38+00:00
2k
MuhammadAttia/caching-workshop
java-caching-poc/src/main/java/com/attia/cachingpoc/controller/ProductController.java
[ { "identifier": "Product", "path": "java-caching-poc/src/main/java/com/attia/cachingpoc/entity/Product.java", "snippet": "@Getter\n@Setter\n@AllArgsConstructor\n@Entity\n@NoArgsConstructor\npublic class Product implements Serializable {\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private Long id;\n\n private String name;\n\n private String description;\n\n private double price;\n\n private boolean available;\n}" }, { "identifier": "ProductService", "path": "java-caching-poc/src/main/java/com/attia/cachingpoc/service/ProductService.java", "snippet": "@Service\npublic class ProductService {\n\n private final ProductRepository productRepository;\n\n private final RMapCache<Long, Product> productRMapCache;\n\n\n public ProductService(ProductRepository productRepository , RMapCache<Long, Product> productRMapCache) {\n this.productRepository = productRepository;\n this.productRMapCache = productRMapCache;\n }\n\n // Cache-Aside -> Read from cache; if there is a miss, go to DB\n public List<Product> getAllProducts() {\n List<Product> cachedProducts = (List<Product>) productRMapCache.readAllValues();\n\n // Check cache\n if (cachedProducts != null && !cachedProducts.isEmpty()) {\n return cachedProducts;\n }\n\n // Get products from DB\n List<Product> products = getProductsFromDB();\n\n // Cache the product listings with an expiration time\n setProductsInCache(products);\n\n return products;\n }\n\n public void setProductsInCache(List<Product> products) {\n // Set the list of products in the cache with a specified key and expiration time\n products.forEach(product -> {\n productRMapCache.put(product.getId(), product);\n\n // Add slight jitter to the expiration time (e.g., within 10% of the original duration)\n // Calculate jitter in milliseconds (e.g., within 10% of the original duration)\n Duration originalDuration = Duration.ofMinutes(10);\n Duration jitter = Duration.ofMinutes((long) (originalDuration.toMinutes() * 0.1 * Math.random()));\n Duration duration = originalDuration.plus(jitter);\n\n // Set the product expiration with jitter\n productRMapCache.expire(Instant.now().plus(duration));\n\n\n });\n }\n\n public List<Product> getProductsFromDB() {\n // Simulate fetching products from the database\n try {\n Thread.sleep(5000);\n } catch (InterruptedException e) {\n throw new RuntimeException(e);\n }\n return productRepository.findAll();\n }\n\n // Write-Through -> Write on cache then write to DB\n public Product updateProduct(Product product) {\n updateProductInCache(product);\n return product;\n }\n\n private void updateProductInCache(Product product) {\n // This will automatically trigger the MapWriter to write to the database after updating cache.\n productRMapCache.put(product.getId(), product);\n }\n\n public Optional<Product> getProductById(Long productId) {\n return Optional.ofNullable(productRMapCache.get(productId));\n }\n}" } ]
import com.attia.cachingpoc.entity.Product; import com.attia.cachingpoc.service.ProductService; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.util.List; import java.util.Optional;
821
package com.attia.cachingpoc.controller; @RestController @RequestMapping("/products") public class ProductController {
package com.attia.cachingpoc.controller; @RestController @RequestMapping("/products") public class ProductController {
private final ProductService productService;
1
2023-10-28 20:15:11+00:00
2k
granny/Pl3xMap
fabric/src/main/java/net/pl3x/map/fabric/client/manager/NetworkManager.java
[ { "identifier": "Constants", "path": "core/src/main/java/net/pl3x/map/core/network/Constants.java", "snippet": "public class Constants {\n public static final String MODID = \"pl3xmap\";\n\n public static final int PROTOCOL = 3;\n\n public static final int SERVER_DATA = 0;\n public static final int MAP_DATA = 1;\n\n public static final int RESPONSE_SUCCESS = 200;\n\n public static final int ERROR_NO_SUCH_MAP = -1;\n public static final int ERROR_NO_SUCH_WORLD = -2;\n public static final int ERROR_NOT_VANILLA_MAP = -3;\n}" }, { "identifier": "Pl3xMapFabricClient", "path": "fabric/src/main/java/net/pl3x/map/fabric/client/Pl3xMapFabricClient.java", "snippet": "public class Pl3xMapFabricClient implements ClientModInitializer {\n private static Pl3xMapFabricClient instance;\n\n private final NetworkManager networkManager;\n private final Scheduler scheduler;\n private final TileManager tileManager;\n private final ExecutorService executor = Pl3xMap.ThreadFactory.createService(\"Pl3xMap-Update\");\n\n public static Pl3xMapFabricClient getInstance() {\n return instance;\n }\n\n private KeyMapping keyBinding;\n private boolean isEnabled;\n private boolean isOnServer;\n private String serverUrl;\n private int tick;\n\n public Pl3xMapFabricClient() {\n instance = this;\n this.networkManager = new NetworkManager(this);\n this.scheduler = new Scheduler();\n this.tileManager = new TileManager(this);\n }\n\n @Override\n public void onInitializeClient() {\n this.keyBinding = KeyBindingHelper.registerKeyBinding(new KeyMapping(\n \"pl3xmap.keymap.toggle\",\n InputConstants.Type.KEYSYM,\n GLFW.GLFW_KEY_M,\n \"pl3xmap.title\"\n ));\n\n getNetworkManager().initialize();\n\n ClientPlayConnectionEvents.JOIN.register((handler, sender, client) -> {\n if (client.isSingleplayer()) {\n return;\n }\n setEnabled(true);\n setIsOnServer(true);\n getScheduler().addTask(0, getNetworkManager()::requestServerData);\n });\n\n ClientPlayConnectionEvents.DISCONNECT.register((handler, client) -> {\n getScheduler().cancelAll();\n setEnabled(false);\n setIsOnServer(false);\n setServerUrl(null);\n getTileManager().clear();\n updateAllMapTextures();\n });\n\n ClientTickEvents.END_CLIENT_TICK.register(client -> {\n if (Minecraft.getInstance().player == null) {\n return;\n }\n while (this.keyBinding.consumeClick()) {\n this.isEnabled = !this.isEnabled;\n MutableComponent onOff = Component.translatable(\"pl3xmap.toggled.\" + (this.isEnabled ? \"on\" : \"off\"));\n MutableComponent component = Component.translatable(\"pl3xmap.toggled.response\", onOff);\n Minecraft.getInstance().player.displayClientMessage(component, true);\n }\n if (this.tick++ >= 20) {\n this.tick = 0;\n getScheduler().tick();\n }\n });\n }\n\n public @NotNull NetworkManager getNetworkManager() {\n return this.networkManager;\n }\n\n public @NotNull Scheduler getScheduler() {\n return this.scheduler;\n }\n\n public @NotNull TileManager getTileManager() {\n return this.tileManager;\n }\n\n public @NotNull ExecutorService getExecutor() {\n return this.executor;\n }\n\n public boolean isEnabled() {\n return this.isEnabled;\n }\n\n public void setEnabled(boolean isEnabled) {\n this.isEnabled = isEnabled;\n }\n\n public boolean isOnServer() {\n return this.isOnServer;\n }\n\n public void setIsOnServer(boolean isOnServer) {\n this.isOnServer = isOnServer;\n }\n\n public @Nullable String getServerUrl() {\n return this.serverUrl;\n }\n\n public void setServerUrl(String url) {\n this.serverUrl = url;\n }\n\n public void updateAllMapTextures() {\n Minecraft.getInstance().gameRenderer.getMapRenderer().maps.values().forEach(tex -> ((MapInstance) tex).updateImage());\n }\n}" }, { "identifier": "MapInstance", "path": "fabric/src/main/java/net/pl3x/map/fabric/client/duck/MapInstance.java", "snippet": "public interface MapInstance {\n void skip();\n\n void setData(byte scale, int centerX, int centerZ, @NotNull String world);\n\n void updateImage();\n}" } ]
import net.minecraft.resources.ResourceLocation; import net.pl3x.map.core.network.Constants; import net.pl3x.map.fabric.client.Pl3xMapFabricClient; import net.pl3x.map.fabric.client.duck.MapInstance; import org.jetbrains.annotations.NotNull; import com.google.common.io.ByteArrayDataInput; import com.google.common.io.ByteArrayDataOutput; import com.google.common.io.ByteStreams; import io.netty.buffer.Unpooled; import net.fabricmc.fabric.api.client.networking.v1.ClientPlayNetworking; import net.minecraft.client.Minecraft; import net.minecraft.network.FriendlyByteBuf;
1,483
/* * MIT License * * Copyright (c) 2020-2023 William Blake Galbreath * * 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.pl3x.map.fabric.client.manager; public class NetworkManager { private final ResourceLocation channel = new ResourceLocation(Constants.MODID, Constants.MODID);
/* * MIT License * * Copyright (c) 2020-2023 William Blake Galbreath * * 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.pl3x.map.fabric.client.manager; public class NetworkManager { private final ResourceLocation channel = new ResourceLocation(Constants.MODID, Constants.MODID);
private final Pl3xMapFabricClient mod;
1
2023-10-26 01:14:31+00:00
2k
jd-opensource/sql-analysis
sql-analysis/src/main/java/com/jd/sql/analysis/replace/SqlReplaceConfig.java
[ { "identifier": "DuccMonitorUtil", "path": "sql-analysis/src/main/java/com/jd/sql/analysis/util/DuccMonitorUtil.java", "snippet": "public class DuccMonitorUtil {\n\n private static Logger log = LoggerFactory.getLogger(DuccMonitorUtil.class);\n private static String duccConfig = \"\";\n\n /**\n * 启动监控\n * @param appName jone或者jdos应用名称\n * @param uri uri格式详解参见:https://git.jd.com/laf/laf-config/wikis/客户端使用指南->UCC配置服务\n * @param moniterKey 存储sql替换配置的key\n */\n public static void start(String appName,String uri,String moniterKey){\n try{\n //todo 配置中心监听\n// //创建ConfiguratorManager 实例,有1个就可以\n// ConfiguratorManager configuratorManager = ConfiguratorManager.getInstance() ;\n// //设置appName,jone或者jdos部署可自动获取,无需配置\n// configuratorManager.setApplication(appName);\n//\n// //resourceName是资源名,命名自定义,多个时不要重复\n// String resourceName = \"sql_analysis_config\";\n//\n// //创建资源对象,此处直接使用ducc远程,Name属性很重要,下面会用到\n// Resource resource = new Resource(resourceName, uri);\n// //给配置管理器添加管理的资源\n// configuratorManager.addResource(resource);\n//\n// //启动之后才可以获取配置\n// configuratorManager.start();\n//\n// //获取配置 (获取指定配置源下指定配置)\n// Property property = configuratorManager.getProperty(resourceName, moniterKey);\n// log.info(\"sql analysis ducc moniterKey:\" + property.getString());\n// duccConfig = property.getString();\n//\n// //添加监听器,配置项维度的监听器\n// configuratorManager.addListener(new PropertyListener.CustomPropertyListener(moniterKey) {\n// @Override\n// public void onUpdate(Property property) {\n// duccConfig = property.getString();\n// log.info(JSON.toJSONString(property));\n// SqlReplaceConfig.initConfig();\n// }\n// });\n }catch (Exception e){\n log.error(\"sql analysis ducc 监听启动失败\");\n }\n\n }\n\n /**\n * 获取ducc配置\n * @return\n */\n public static String getDuccConfig(){\n return duccConfig;\n }\n\n}" }, { "identifier": "GsonUtil", "path": "sql-analysis/src/main/java/com/jd/sql/analysis/util/GsonUtil.java", "snippet": "public class GsonUtil {\n\n private static final Gson GSON = new GsonBuilder().create();\n\n /**\n * 对象、集合转json\n *\n * @param obj 对象\n * @return json\n */\n public static String bean2Json(Object obj) {\n return GSON.toJson(obj);\n }\n\n /**\n * json转对象\n *\n * @param jsonString json\n * @param objClass 对象类型\n * @param <T> 对象类型\n * @return 对象\n */\n public static <T> T json2Bean(String jsonString, Class<T> objClass) {\n return GSON.fromJson(jsonString, objClass);\n }\n\n}" } ]
import com.jd.sql.analysis.util.DuccMonitorUtil; import com.jd.sql.analysis.util.GsonUtil; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.HashMap; import java.util.Objects;
990
package com.jd.sql.analysis.replace; /** * @Author huhaitao21 * @Description sql替换配置 * @Date 18:50 2023/5/25 **/ public class SqlReplaceConfig { static Logger log = LoggerFactory.getLogger(SqlReplaceConfig.class); /** * 配置明细 */ private static HashMap<String,String> sqlReplaceMap = new HashMap<>(); /** * 初始化配置 */ public static void initConfig(){ try{
package com.jd.sql.analysis.replace; /** * @Author huhaitao21 * @Description sql替换配置 * @Date 18:50 2023/5/25 **/ public class SqlReplaceConfig { static Logger log = LoggerFactory.getLogger(SqlReplaceConfig.class); /** * 配置明细 */ private static HashMap<String,String> sqlReplaceMap = new HashMap<>(); /** * 初始化配置 */ public static void initConfig(){ try{
String configStr = DuccMonitorUtil.getDuccConfig();
0
2023-10-25 08:59:26+00:00
2k
easy-do/dnf-admin
be/src/main/java/plus/easydo/dnf/service/impl/DaRoleServiceImpl.java
[ { "identifier": "DaRole", "path": "be/src/main/java/plus/easydo/dnf/entity/DaRole.java", "snippet": "@Data\n@Table(value = \"da_role\")\npublic class DaRole {\n\n /**\n * 角色ID\n */\n @Id(keyType = KeyType.Auto)\n private Long id;\n\n /**\n * 角色名称\n */\n @Column(value = \"role_name\")\n private String roleName;\n\n /**\n * 角色权限字符串\n */\n @Column(value = \"role_key\")\n private String roleKey;\n\n /**\n * 显示顺序\n */\n @Column(value = \"role_sort\")\n private Integer roleSort;\n\n /**\n * 是否默认角色,0否 1是\n */\n @Column(value = \"is_default\")\n private Boolean isDefault;\n\n /**\n * 角色状态(0正常 1停用)\n */\n @Column(value = \"status\")\n private Boolean status;\n\n /**\n * 备注\n */\n @Column(value = \"remark\")\n private String remark;\n\n}" }, { "identifier": "DaUserRole", "path": "be/src/main/java/plus/easydo/dnf/entity/DaUserRole.java", "snippet": "@Data\n@Table(value = \"da_user_role\")\npublic class DaUserRole {\n\n /**\n * 用户ID\n */\n private Long userId;\n\n /**\n * 角色ID\n */\n private Long roleId;\n\n\n}" }, { "identifier": "BaseException", "path": "be/src/main/java/plus/easydo/dnf/exception/BaseException.java", "snippet": "public class BaseException extends RuntimeException {\n\n private static final long serialVersionUID = 1L;\n\n private static final String DEFAULT_ERR_CODE = \"BASE_ERROR\";\n\n private static final String DEFAULT_ERR_MESSAGE = \"基础异常\";\n\n /**\n * 错误码\n */\n private String errCode;\n\n\n public BaseException() {\n super(DEFAULT_ERR_MESSAGE);\n this.errCode = DEFAULT_ERR_CODE;\n }\n\n public BaseException(String message) {\n super(message);\n this.errCode = DEFAULT_ERR_CODE;\n }\n\n public BaseException(String errCode, String message) {\n super(message);\n this.errCode = errCode;\n }\n\n public BaseException(String errCode, String message, Throwable cause) {\n super(message, cause);\n this.errCode = errCode;\n }\n\n public BaseException(String errCode, Throwable cause) {\n super(cause);\n this.errCode = errCode;\n }\n\n public String getErrCode() {\n return errCode;\n }\n}" }, { "identifier": "DaRoleMapper", "path": "be/src/main/java/plus/easydo/dnf/mapper/DaRoleMapper.java", "snippet": "@Mapper\npublic interface DaRoleMapper extends BaseMapper<DaRole> {\n\n\n}" }, { "identifier": "DaRoleQo", "path": "be/src/main/java/plus/easydo/dnf/qo/DaRoleQo.java", "snippet": "@Getter\n@Setter\n@EqualsAndHashCode(callSuper = false)\npublic class DaRoleQo extends PageQo{\n\n /**\n * 角色名称\n */\n private String roleName;\n\n /**\n * 角色权限字符串\n */\n private String roleKey;\n\n /**\n * 显示顺序\n */\n private Integer roleSort;\n\n /**\n * 是否默认角色,0否 1是\n */\n private Boolean isDefault;\n\n /**\n * 角色状态(0正常 1停用)\n */\n private Boolean status;\n\n /**\n * 备注\n */\n private String remark;\n\n}" }, { "identifier": "IDaRoleService", "path": "be/src/main/java/plus/easydo/dnf/service/IDaRoleService.java", "snippet": "public interface IDaRoleService extends IService<DaRole> {\n\n List<DaRole> userRole();\n\n List<String> userRoleCodes(Long userId);\n List<String> userRoleCodes();\n\n void bindingUserRole(Long userId, String roleName);\n\n Page<DaRole> pageRole(DaRoleQo daRoleQo);\n\n void bindingDefaultRole(Long uid);\n}" }, { "identifier": "IDaUserRoleService", "path": "be/src/main/java/plus/easydo/dnf/service/IDaUserRoleService.java", "snippet": "public interface IDaUserRoleService extends IService<DaUserRole> {\n\n List<DaUserRole> userRole();\n\n List<Long> userRoleIds(Long userId);\n\n List<Long> userRoleIds();\n}" } ]
import cn.dev33.satoken.stp.StpUtil; import com.mybatisflex.core.paginate.Page; import com.mybatisflex.core.query.QueryWrapper; import com.mybatisflex.spring.service.impl.ServiceImpl; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; import plus.easydo.dnf.entity.DaRole; import plus.easydo.dnf.entity.DaUserRole; import plus.easydo.dnf.exception.BaseException; import plus.easydo.dnf.mapper.DaRoleMapper; import plus.easydo.dnf.qo.DaRoleQo; import plus.easydo.dnf.service.IDaRoleService; import plus.easydo.dnf.service.IDaUserRoleService; import java.util.Collections; import java.util.List; import java.util.Objects; import static plus.easydo.dnf.entity.table.DaRoleTableDef.DA_ROLE;
1,341
package plus.easydo.dnf.service.impl; /** * 角色信息表 服务层实现。 * * @author mybatis-flex-helper automatic generation * @since 1.0 */ @Service @RequiredArgsConstructor
package plus.easydo.dnf.service.impl; /** * 角色信息表 服务层实现。 * * @author mybatis-flex-helper automatic generation * @since 1.0 */ @Service @RequiredArgsConstructor
public class DaRoleServiceImpl extends ServiceImpl<DaRoleMapper, DaRole> implements IDaRoleService {
3
2023-10-29 03:26:16+00:00
2k
d0ge/sessionless
src/main/java/burp/proxy/ProxyHttpMessageHandler.java
[ { "identifier": "ProxyConfig", "path": "src/main/java/burp/config/ProxyConfig.java", "snippet": "public class ProxyConfig {\n public static final HighlightColor DEFAULT_HIGHLIGHT_COLOR = GREEN;\n\n private static final String BURP_PROXY_COMMENT_TEMPLATE = Utils.getResourceString(\"burp_proxy_comment\");\n\n @Expose\n private boolean highlightToken;\n @Expose\n private HighlightColor highlightColor;\n\n public ProxyConfig() {\n this.highlightToken = true;\n this.highlightColor = DEFAULT_HIGHLIGHT_COLOR;\n }\n\n public boolean highlightToken() {\n return highlightToken;\n }\n\n public void setHighlightToken(boolean highlightToken) {\n this.highlightToken = highlightToken;\n }\n\n public HighlightColor highlightColor() {\n return highlightColor;\n }\n\n public void setHighlightColor(HighlightColor highlightColor) {\n this.highlightColor = highlightColor == null ? DEFAULT_HIGHLIGHT_COLOR : highlightColor;\n }\n\n public String comment(int count) {\n return String.format(BURP_PROXY_COMMENT_TEMPLATE, count);\n }\n}" }, { "identifier": "SignerConfig", "path": "src/main/java/burp/config/SignerConfig.java", "snippet": "public class SignerConfig {\n @Expose\n private boolean enableDangerous;\n @Expose\n private boolean enableExpress;\n @Expose\n private boolean enableOAuth;\n @Expose\n private boolean enableTornado;\n @Expose\n private boolean enableUnknown;\n\n public SignerConfig() {\n this.enableDangerous = true;\n this.enableExpress = true;\n this.enableOAuth = false;\n this.enableTornado = true;\n this.enableUnknown = false;\n }\n\n public boolean isEnableDangerous() {\n return enableDangerous;\n }\n\n public void setEnableDangerous(boolean enableDangerous) {\n this.enableDangerous = enableDangerous;\n }\n\n public boolean isEnableExpress() {\n return enableExpress;\n }\n\n public void setEnableExpress(boolean enableExpress) {\n this.enableExpress = enableExpress;\n }\n\n public boolean isEnableOAuth() {\n return enableOAuth;\n }\n\n public void setEnableOAuth(boolean enableOAuth) {\n this.enableOAuth = enableOAuth;\n }\n\n public boolean isEnableTornado() {\n return enableTornado;\n }\n\n public void setEnableTornado(boolean enableTornado) {\n this.enableTornado = enableTornado;\n }\n\n public boolean isEnableUnknown() {\n return enableUnknown;\n }\n\n public void setEnableUnknown(boolean enableUnknown) {\n this.enableUnknown = enableUnknown;\n }\n}" } ]
import burp.api.montoya.proxy.http.*; import burp.api.montoya.utilities.ByteUtils; import burp.config.ProxyConfig; import burp.config.SignerConfig;
717
package burp.proxy; public class ProxyHttpMessageHandler implements ProxyRequestHandler, ProxyResponseHandler { private final AnnotationsModifier annotationsModifier;
package burp.proxy; public class ProxyHttpMessageHandler implements ProxyRequestHandler, ProxyResponseHandler { private final AnnotationsModifier annotationsModifier;
public ProxyHttpMessageHandler(ProxyConfig proxyConfig, SignerConfig signerConfig, ByteUtils byteUtils) {
0
2023-10-30 09:12:06+00:00
2k
ballerina-platform/module-ballerinax-ibm.ibmmq
native/src/main/java/io/ballerina/lib/ibm.ibmmq/headers/MQRFHHeader.java
[ { "identifier": "createError", "path": "native/src/main/java/io/ballerina/lib/ibm.ibmmq/CommonUtils.java", "snippet": "public static BError createError(String errorType, String message, Throwable throwable) {\n BError cause = ErrorCreator.createError(throwable);\n BMap<BString, Object> errorDetails = ValueCreator.createRecordValue(getModule(), ERROR_DETAILS);\n if (throwable instanceof MQException exception) {\n errorDetails.put(ERROR_REASON_CODE, exception.getReason());\n errorDetails.put(ERROR_ERROR_CODE, StringUtils.fromString(exception.getErrorCode()));\n errorDetails.put(ERROR_COMPLETION_CODE, exception.getCompCode());\n }\n return ErrorCreator.createError(\n ModuleUtils.getModule(), errorType, StringUtils.fromString(message), cause, errorDetails);\n}" }, { "identifier": "getModule", "path": "native/src/main/java/io/ballerina/lib/ibm.ibmmq/ModuleUtils.java", "snippet": "public static Module getModule() {\n return module;\n}" } ]
import com.ibm.mq.MQMessage; import com.ibm.mq.headers.MQDataException; import com.ibm.mq.headers.MQRFH; import io.ballerina.runtime.api.Runtime; import io.ballerina.runtime.api.creators.ValueCreator; import io.ballerina.runtime.api.utils.StringUtils; import io.ballerina.runtime.api.values.BMap; import io.ballerina.runtime.api.values.BString; import java.io.IOException; import java.util.ArrayList; import java.util.List; import static io.ballerina.lib.ibm.ibmmq.CommonUtils.createError; import static io.ballerina.lib.ibm.ibmmq.Constants.CODED_CHARSET_ID_FIELD; import static io.ballerina.lib.ibm.ibmmq.Constants.ENCODING_FIELD; import static io.ballerina.lib.ibm.ibmmq.Constants.FLAGS_FIELD; import static io.ballerina.lib.ibm.ibmmq.Constants.FORMAT_FIELD; import static io.ballerina.lib.ibm.ibmmq.Constants.IBMMQ_ERROR; import static io.ballerina.lib.ibm.ibmmq.Constants.MQRFH_RECORD_NAME; import static io.ballerina.lib.ibm.ibmmq.Constants.STRUC_ID_FIELD; import static io.ballerina.lib.ibm.ibmmq.Constants.STRUC_LENGTH_FIELD; import static io.ballerina.lib.ibm.ibmmq.Constants.VERSION_FIELD; import static io.ballerina.lib.ibm.ibmmq.ModuleUtils.getModule;
1,058
/* * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.org) All Rights Reserved. * * 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.lib.ibm.ibmmq.headers; /** * Header class with util methods for handling MQRFH headers. */ public class MQRFHHeader { private static final BString NAME_VALUE_PAIRS_FIELD = StringUtils.fromString("nameValuePairs"); private MQRFHHeader() {} public static void decodeHeader(Runtime runtime, MQMessage msg, ArrayList<BMap<BString, Object>> headers) throws IOException { MQRFH mqrfh = new MQRFH(); int dataOffset = msg.getDataOffset(); try { mqrfh.read(msg); headers.add(getBHeaderFromMQRFH(mqrfh)); MQRFH2Header.decodeHeader(runtime, msg, headers); } catch (MQDataException e) { msg.seek(dataOffset); MQCIHHeader.decodeHeader(runtime, msg, headers); } } public static MQRFH createMQRFHHeaderFromBHeader(BMap<BString, Object> bHeader) { MQRFH header = new MQRFH(); header.setFlags(bHeader.getIntValue(FLAGS_FIELD).intValue()); if (bHeader.getIntValue(ENCODING_FIELD).intValue() != 0) { header.setEncoding(bHeader.getIntValue(ENCODING_FIELD).intValue()); } header.setCodedCharSetId(bHeader.getIntValue(CODED_CHARSET_ID_FIELD).intValue()); header.setFormat(bHeader.getStringValue(FORMAT_FIELD).getValue()); BMap<BString, Object> nameValuePairsMap = (BMap<BString, Object>) bHeader.getMapValue(NAME_VALUE_PAIRS_FIELD); for (BString key : nameValuePairsMap.getKeys()) { try { header.addNameValuePair(key.getValue(), nameValuePairsMap.getStringValue(key).getValue()); } catch (IOException e) {
/* * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.org) All Rights Reserved. * * 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.lib.ibm.ibmmq.headers; /** * Header class with util methods for handling MQRFH headers. */ public class MQRFHHeader { private static final BString NAME_VALUE_PAIRS_FIELD = StringUtils.fromString("nameValuePairs"); private MQRFHHeader() {} public static void decodeHeader(Runtime runtime, MQMessage msg, ArrayList<BMap<BString, Object>> headers) throws IOException { MQRFH mqrfh = new MQRFH(); int dataOffset = msg.getDataOffset(); try { mqrfh.read(msg); headers.add(getBHeaderFromMQRFH(mqrfh)); MQRFH2Header.decodeHeader(runtime, msg, headers); } catch (MQDataException e) { msg.seek(dataOffset); MQCIHHeader.decodeHeader(runtime, msg, headers); } } public static MQRFH createMQRFHHeaderFromBHeader(BMap<BString, Object> bHeader) { MQRFH header = new MQRFH(); header.setFlags(bHeader.getIntValue(FLAGS_FIELD).intValue()); if (bHeader.getIntValue(ENCODING_FIELD).intValue() != 0) { header.setEncoding(bHeader.getIntValue(ENCODING_FIELD).intValue()); } header.setCodedCharSetId(bHeader.getIntValue(CODED_CHARSET_ID_FIELD).intValue()); header.setFormat(bHeader.getStringValue(FORMAT_FIELD).getValue()); BMap<BString, Object> nameValuePairsMap = (BMap<BString, Object>) bHeader.getMapValue(NAME_VALUE_PAIRS_FIELD); for (BString key : nameValuePairsMap.getKeys()) { try { header.addNameValuePair(key.getValue(), nameValuePairsMap.getStringValue(key).getValue()); } catch (IOException e) {
throw createError(IBMMQ_ERROR, String
0
2023-10-27 05:54:44+00:00
2k
LEAWIND/Third-Person
forge/src/main/java/net/leawind/mc/thirdperson/forge/ThirdPersonForge.java
[ { "identifier": "ThirdPerson", "path": "common/src/main/java/net/leawind/mc/thirdperson/ThirdPerson.java", "snippet": "public class ThirdPerson {\n\tpublic static final Logger LOGGER = LoggerFactory.getLogger(ModConstants.MOD_ID);\n\tprivate static final ConfigManager CONFIG_MANAGER = ConfigManager.create();\n\tpublic static float lastPartialTick = 1;\n\tpublic static double lastCameraSetupTimeStamp = 0;\n\n\tpublic static void init () {\n\t\tCONFIG_MANAGER.tryLoad();\n\t\tThirdPersonKeys.register();\n\t\tThirdPersonEvents.register();\n\t}\n\n\tpublic static @NotNull ConfigManager getConfigManager () {\n\t\treturn CONFIG_MANAGER;\n\t}\n\n\tpublic static @NotNull Config getConfig () {\n\t\treturn CONFIG_MANAGER.getConfig();\n\t}\n}" }, { "identifier": "ModConstants", "path": "common/src/main/java/net/leawind/mc/thirdperson/api/ModConstants.java", "snippet": "public interface ModConstants {\n\tString MOD_ID = \"leawind_third_person\";\n\tString KEY_CATEGORY = \"key.categories.\" + MOD_ID;\n\tFile CONFIG_FILE = Minecraft.getInstance().gameDirectory.toPath().resolve(\"config/\" + MOD_ID + \".json\").toFile();\n\tdouble EYE_POSITIOIN_SMOOTH_WEIGHT = 8;\n\tdouble DISTANCE_TO_EYE_SMOOTH_WEIGHT = 4;\n\tdouble OFFSET_RATIO_SMOOTH_WEIGHT = 12;\n\t/**\n\t * 成像平面到相机的距离,这是一个固定值,硬编码在Minecraft源码中。\n\t * <p>\n\t * 取自 {@link net.minecraft.client.Camera#getNearPlane()}\n\t */\n\tdouble NEAR_PLANE_DISTANCE = 0.050;\n\tdouble CAMERA_PITCH_DEGREE_LIMIT = 89.800;\n\tdouble CAMERA_THROUGH_WALL_DETECTION = 0.180;\n\tList<String> BUILDIN_AIM_ITEM_RULES = List.of(\"crossbow{Charged:1b}\", \"ender_pearl\", \"snowball\", \"egg\", \"splash_potion\", \"lingering_potion\", \"experience_bottle\");\n\tList<String> BUILDIN_USE_AIM_ITEM_RULES = List.of(\"bow\", \"trident\");\n}" } ]
import dev.architectury.platform.forge.EventBuses; import net.leawind.mc.thirdperson.ThirdPerson; import net.leawind.mc.thirdperson.api.ModConstants; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.client.ConfigScreenHandler; import net.minecraftforge.fml.DistExecutor; import net.minecraftforge.fml.ModLoadingContext; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
727
package net.leawind.mc.thirdperson.forge; @Mod(ModConstants.MOD_ID) public class ThirdPersonForge { public ThirdPersonForge () { // 仅在客户端运行 ThreadGroup tg = Thread.currentThread().getThreadGroup(); DistExecutor.unsafeRunWhenOn(Dist.CLIENT, () -> () -> { EventBuses.registerModEventBus(ModConstants.MOD_ID, FMLJavaModLoadingContext.get().getModEventBus());
package net.leawind.mc.thirdperson.forge; @Mod(ModConstants.MOD_ID) public class ThirdPersonForge { public ThirdPersonForge () { // 仅在客户端运行 ThreadGroup tg = Thread.currentThread().getThreadGroup(); DistExecutor.unsafeRunWhenOn(Dist.CLIENT, () -> () -> { EventBuses.registerModEventBus(ModConstants.MOD_ID, FMLJavaModLoadingContext.get().getModEventBus());
ThirdPerson.init();
0
2023-10-31 05:52:36+00:00
2k
kandybaby/S3mediaArchival
backend/src/test/java/com/example/mediaarchival/controllers/UserControllerTest.java
[ { "identifier": "UserModel", "path": "backend/src/main/java/com/example/mediaarchival/models/UserModel.java", "snippet": "@Entity\n@Table(name = \"users\")\npublic class UserModel {\n\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private Long id;\n\n @Column(unique = true, nullable = false)\n private String username;\n\n @Column(nullable = false)\n private String password;\n\n @Column(nullable = true)\n private String refreshToken;\n\n @Column private Date refreshExpiry;\n\n /**\n * Default constructor for JPA.\n */\n public UserModel() {}\n\n /**\n * Constructs a new UserModel with the specified username and password.\n *\n * @param username the username for the new user.\n * @param password the password for the new user.\n */\n public UserModel(String username, String password) {\n this.username = username;\n this.password = password;\n }\n\n /**\n * Gets the unique identifier for the user.\n *\n * @return the user ID.\n */\n public Long getId() {\n return id;\n }\n\n /**\n * Sets the unique identifier for the user.\n *\n * @param id the ID to set for the user.\n */\n public void setId(Long id) {\n this.id = id;\n }\n\n /**\n * Gets the username for the user.\n *\n * @return the username.\n */\n public String getUsername() {\n return username;\n }\n\n /**\n * Sets the username for the user. The username is unique and cannot be null.\n *\n * @param username the username to set.\n */\n public void setUsername(String username) {\n this.username = username;\n }\n\n /**\n * Gets the password for the user.\n *\n * @return the password.\n */\n public String getPassword() {\n return password;\n }\n\n /**\n * Sets the password for the user. The password cannot be null.\n *\n * @param password the password to set.\n */\n public void setPassword(String password) {\n this.password = password;\n }\n\n /**\n * Gets the refresh token for the user. This token is used to refresh authentication\n * when the current token expires.\n *\n * @return the refresh token, or null if it hasn't been set.\n */\n public String getRefreshToken() {\n return refreshToken;\n }\n\n /**\n * Sets the refresh token for the user.\n *\n * @param refreshToken the token to set for refreshing authentication.\n */\n public void setRefreshToken(String refreshToken) {\n this.refreshToken = refreshToken;\n }\n\n /**\n * Gets the expiry date for the refresh token.\n *\n * @return the refresh token expiry date, or null if the token hasn't been set or expired.\n */\n public Date getRefreshExpiry() {\n return refreshExpiry;\n }\n\n /**\n * Sets the expiry date for the refresh token.\n *\n * @param refreshExpiry the expiry date to set for the refresh token.\n */\n public void setRefreshExpiry(Date refreshExpiry) {\n this.refreshExpiry = refreshExpiry;\n }\n\n}" }, { "identifier": "UserRepository", "path": "backend/src/main/java/com/example/mediaarchival/repositories/UserRepository.java", "snippet": "@Repository\npublic interface UserRepository extends JpaRepository<UserModel, Long> {\n\n /**\n * Retrieves a user by their username.\n *\n * @param username the username to search for\n * @return the user with the specified username, or null if no such user exists\n */\n UserModel findByUsername(String username);\n\n /**\n * Retrieves a user by their refresh token.\n *\n * @param refreshToken the refresh token to search for\n * @return the user with the specified refresh token, or null if no such user exists\n */\n UserModel findByRefreshToken(String refreshToken);\n}" } ]
import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.*; import com.example.mediaarchival.models.UserModel; import com.example.mediaarchival.repositories.UserRepository; import jakarta.servlet.http.Cookie; import java.util.Collections; import java.util.Date; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.RequestBuilder; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.setup.MockMvcBuilders;
1,151
package com.example.mediaarchival.controllers; public class UserControllerTest { private MockMvc mockMvc;
package com.example.mediaarchival.controllers; public class UserControllerTest { private MockMvc mockMvc;
@Mock private UserRepository userRepository;
1
2023-10-27 01:54:57+00:00
2k
siam1026/siam-cloud
siam-util/util-provider/src/main/java/com/siam/package_util/controller/admin/AdminUploadController.java
[ { "identifier": "BasicResult", "path": "siam-common/src/main/java/com/siam/package_common/entity/BasicResult.java", "snippet": "@Data\npublic class BasicResult<T> {\n\n public static final Integer CODE_DEFAULT_SUCCESS = 200;\n public static final Integer CODE_DEFAULT_ERROR = 500;\n\n public static final String MESSAGE_DEFAULT_SUCCESS = \"请求成功\";\n public static final String MESSAGE_DEFAULT_ERROR = \"网络异常\";\n\n private Boolean success;\n\n private Integer code;\n\n private String message;\n\n private T data;\n\n public BasicResult() {\n }\n\n public BasicResult(Boolean success, Integer code, String message, T data) {\n this.success = success;\n this.code = code;\n this.message = message;\n this.data = data;\n }\n\n public static BasicResult success() {\n return new BasicResult(true, CODE_DEFAULT_SUCCESS, MESSAGE_DEFAULT_SUCCESS, null);\n }\n\n public static <T> BasicResult success(T data) {\n return new BasicResult(true, CODE_DEFAULT_SUCCESS, MESSAGE_DEFAULT_SUCCESS, data);\n }\n\n public static BasicResult error(String message) {\n return new BasicResult(false, CODE_DEFAULT_ERROR, message, null);\n }\n}" }, { "identifier": "StoneCustomerException", "path": "siam-common/src/main/java/com/siam/package_common/exception/StoneCustomerException.java", "snippet": "public class StoneCustomerException extends RuntimeException{\n // 结果码\n private Integer code = BasicResultCode.ERR;\n\n // 结果码描述\n private String message;\n\n public StoneCustomerException() {\n }\n\n public StoneCustomerException(String message) {\n this.message = message;\n }\n\n public StoneCustomerException(Integer code, String message) {\n this.code = code;\n this.message = message;\n }\n\n public Integer getCode() {\n return code;\n }\n\n public void setCode(Integer code) {\n this.code = code;\n }\n\n @Override\n public String getMessage() {\n return message;\n }\n\n public void setMessage(String message) {\n this.message = message;\n }\n}" }, { "identifier": "OSSUtils", "path": "siam-common/src/main/java/com/siam/package_common/util/OSSUtils.java", "snippet": "@Slf4j\n@Component\npublic class OSSUtils {\n\n @Autowired\n private AliyunOss aliyunOSS;\n\n /**\n * 上传图片--前端文件上传交互\n *\n * @param file 文件对象\n * @param path 模块名称\n * @param id 表唯一标识主键id,如:用户id、商品id;类型应该定义成Object,因为mongodb数据表主键id为字符串类型\n * @return\n **/\n public String uploadImage(MultipartFile file, String path, Object id){\n log.debug(\"name: \" + file.getName());\n log.debug(\"originalFilename: \" + file.getOriginalFilename());\n String objectName = null;\n try {\n InputStream inputStream = file.getInputStream();\n\n // 文件名处理\n String fileName = file.getOriginalFilename();\n fileName = \"siam_\" + new Date().getTime() + fileName.substring(fileName.lastIndexOf(\".\"));\n\n // 根据模块名称、用户id作为文件夹命名\n objectName = \"data/images/\" + path + \"/\" + id + \"/\" + fileName;\n\n aliyunOSS.uploadFile(inputStream, objectName);\n } catch (IOException e) {\n //e.printStackTrace();\n throw new RuntimeException(\"图片上传失败\");\n }\n return objectName;\n }\n\n /**\n * 上传图片--逻辑处理时上传文件\n *\n * @return\n **/\n public void uploadImage(InputStream inputStream, String savePath){\n try {\n aliyunOSS.uploadFile(inputStream, savePath);\n } catch (IOException e) {\n //e.printStackTrace();\n throw new RuntimeException(\"图片上传失败\");\n }\n }\n\n /**\n * 判断文件是否存在\n * @param remoteFileName\n * @return\n */\n public Boolean doesObjectExist(String remoteFileName) {\n return aliyunOSS.doesObjectExist(remoteFileName);\n }\n}" } ]
import com.siam.package_common.entity.BasicResult; import com.siam.package_common.exception.StoneCustomerException; import com.siam.package_common.util.OSSUtils; import io.swagger.annotations.Api; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Transactional; 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 java.util.List;
1,241
package com.siam.package_util.controller.admin; @RestController @RequestMapping(value = "/rest/admin") @Transactional(rollbackFor = Exception.class) @Api(tags = "后台上传图片模块相关接口", description = "AdminUploadController") public class AdminUploadController { @Autowired private OSSUtils ossUtils; /** * 后台商家账号上传单张图片 * * @author 暹罗 */ @PostMapping(value = "/uploadSingleImage")
package com.siam.package_util.controller.admin; @RestController @RequestMapping(value = "/rest/admin") @Transactional(rollbackFor = Exception.class) @Api(tags = "后台上传图片模块相关接口", description = "AdminUploadController") public class AdminUploadController { @Autowired private OSSUtils ossUtils; /** * 后台商家账号上传单张图片 * * @author 暹罗 */ @PostMapping(value = "/uploadSingleImage")
public BasicResult uploadSingleImage(@RequestParam("file") MultipartFile file) {
0
2023-10-26 10:45:10+00:00
2k
elizagamedev/android-libre-japanese-input
app/src/main/java/sh/eliza/japaneseinput/keyboard/Keyboard.java
[ { "identifier": "KeyboardSpecificationName", "path": "app/src/main/java/sh/eliza/japaneseinput/KeyboardSpecificationName.java", "snippet": "public class KeyboardSpecificationName {\n\n public final String baseName;\n public final int major;\n public final int minor;\n public final int revision;\n\n public KeyboardSpecificationName(String baseName, int major, int minor, int revision) {\n this.baseName = Preconditions.checkNotNull(baseName);\n this.major = major;\n this.minor = minor;\n this.revision = revision;\n }\n\n /**\n * Get formatted keyboard name based on given parameters.\n *\n * <p>The main purpose of the formatted name is collecting usage stats.\n */\n public String formattedKeyboardName(Configuration configuration) {\n Preconditions.checkNotNull(configuration);\n return baseName\n + '-'\n + major\n + '.'\n + minor\n + '.'\n + revision\n + '-'\n + getDeviceOrientationString(configuration);\n }\n\n /** Returns *Canonical* orientation string, which is used as a part of keyboard name. */\n // SQUARE orientation is deprecated, but we should still handle the case here.\n @SuppressWarnings(\"deprecation\")\n public static String getDeviceOrientationString(Configuration configuration) {\n Preconditions.checkNotNull(configuration);\n switch (configuration.orientation) {\n case Configuration.ORIENTATION_PORTRAIT:\n return \"PORTRAIT\";\n case Configuration.ORIENTATION_LANDSCAPE:\n return \"LANDSCAPE\";\n case Configuration.ORIENTATION_SQUARE:\n return \"SQUARE\";\n case Configuration.ORIENTATION_UNDEFINED:\n return \"UNDEFINED\";\n }\n // If none of above is matched to the orientation, we return \"UNKNOWN\".\n return \"UNKNOWN\";\n }\n}" }, { "identifier": "Direction", "path": "app/src/main/java/sh/eliza/japaneseinput/keyboard/Flick.java", "snippet": "public enum Direction {\n CENTER(0),\n LEFT(1),\n RIGHT(2),\n UP(3),\n DOWN(4);\n\n // An index also defined in res/values/attr.xml.\n final int index;\n\n Direction(int index) {\n this.index = index;\n }\n\n public static Direction valueOf(int index) {\n for (Direction direction : values()) {\n if (direction.index == index) {\n return direction;\n }\n }\n throw new IllegalArgumentException(\"Corresponding Direction is not found: \" + index);\n }\n}" } ]
import com.google.common.base.Optional; import com.google.common.base.Preconditions; import java.util.Collections; import java.util.List; import org.mozc.android.inputmethod.japanese.protobuf.ProtoCommands.CompositionMode; import org.mozc.android.inputmethod.japanese.protobuf.ProtoCommands.Request.CrossingEdgeBehavior; import org.mozc.android.inputmethod.japanese.protobuf.ProtoCommands.Request.SpaceOnAlphanumeric; import org.mozc.android.inputmethod.japanese.protobuf.ProtoCommands.Request.SpecialRomanjiTable; import sh.eliza.japaneseinput.KeyboardSpecificationName; import sh.eliza.japaneseinput.R; import sh.eliza.japaneseinput.keyboard.Flick.Direction; import android.util.SparseIntArray;
1,126
// Copyright 2010-2018, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package sh.eliza.japaneseinput.keyboard; /** A simple model class of a keyboard. A keyboard can contain a sequence of {@code Row}s. */ public class Keyboard { /** * Each keyboard has its own specification. * * <p>For example, some keyboards use a special Romanji table. */ public enum KeyboardSpecification { // 12 keys. TWELVE_KEY_TOGGLE_KANA(
// Copyright 2010-2018, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package sh.eliza.japaneseinput.keyboard; /** A simple model class of a keyboard. A keyboard can contain a sequence of {@code Row}s. */ public class Keyboard { /** * Each keyboard has its own specification. * * <p>For example, some keyboards use a special Romanji table. */ public enum KeyboardSpecification { // 12 keys. TWELVE_KEY_TOGGLE_KANA(
new KeyboardSpecificationName("TWELVE_KEY_TOGGLE_KANA", 0, 2, 0),
0
2023-10-25 07:33:25+00:00
2k
ewolff/microservice-dapr
microservice-dapr-demo/microservice-dapr-order/src/main/java/com/ewolff/microservice/order/logic/OrderRestController.java
[ { "identifier": "OrderFeed", "path": "microservice-dapr-demo/microservice-dapr-order/src/main/java/com/ewolff/microservice/order/OrderFeed.java", "snippet": "public class OrderFeed {\r\n\r\n private Date updated;\r\n\r\n private List<OrderFeedEntry> orders;\r\n\r\n public OrderFeed() {\r\n super();\r\n }\r\n\r\n public OrderFeed(Date updated) {\r\n super();\r\n this.updated = updated;\r\n orders = new ArrayList<OrderFeedEntry>();\r\n }\r\n\r\n public Date getUpdated() {\r\n return updated;\r\n }\r\n\r\n public void setUpdated(Date updated) {\r\n this.updated = updated;\r\n }\r\n\r\n public List<OrderFeedEntry> getOrders() {\r\n return orders;\r\n }\r\n\r\n public void setOrders(List<OrderFeedEntry> orders) {\r\n this.orders = orders;\r\n }\r\n\r\n @Override\r\n\tpublic int hashCode() {\r\n\t\tfinal int prime = 31;\r\n\t\tint result = 1;\r\n\t\tresult = prime * result + ((orders == null) ? 0 : orders.hashCode());\r\n\t\tresult = prime * result + ((updated == null) ? 0 : updated.hashCode());\r\n\t\treturn result;\r\n\t}\r\n\r\n @Override\r\n\tpublic boolean equals(Object obj) {\r\n\t\tif (this == obj)\r\n\t\t\treturn true;\r\n\t\tif (obj == null)\r\n\t\t\treturn false;\r\n\t\tif (getClass() != obj.getClass())\r\n\t\t\treturn false;\r\n\t\tOrderFeed other = (OrderFeed) obj;\r\n\t\tif (orders == null) {\r\n\t\t\tif (other.orders != null)\r\n\t\t\t\treturn false;\r\n\t\t} else if (!orders.equals(other.orders))\r\n\t\t\treturn false;\r\n\t\tif (updated == null) {\r\n\t\t\tif (other.updated != null)\r\n\t\t\t\treturn false;\r\n\t\t} else if (!updated.equals(other.updated))\r\n\t\t\treturn false;\r\n\t\treturn true;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic String toString() {\r\n\t\treturn \"OrderFeed [updated=\" + updated + \", orders=\" + orders + \"]\";\r\n\t}\r\n\r\n \r\n \r\n}" }, { "identifier": "OrderFeedEntry", "path": "microservice-dapr-demo/microservice-dapr-order/src/main/java/com/ewolff/microservice/order/OrderFeedEntry.java", "snippet": "public class OrderFeedEntry {\r\n\r\n private long id;\r\n\r\n private String link;\r\n\r\n private Date updated;\r\n\r\n public OrderFeedEntry() {\r\n }\r\n\r\n public OrderFeedEntry(long id, String link, Date updated) {\r\n this.id = id;\r\n this.link = link;\r\n this.updated = updated;\r\n }\r\n\r\n public long getId() {\r\n return id;\r\n }\r\n\r\n public void setId(long id) {\r\n this.id = id;\r\n }\r\n\r\n public String getLink() {\r\n return link;\r\n }\r\n\r\n public void setLink(String link) {\r\n this.link = link;\r\n }\r\n\r\n public Date getUpdated() {\r\n return updated;\r\n }\r\n\r\n public void setUpdated(Date updated) {\r\n this.updated = updated;\r\n }\r\n\r\n\t@Override\r\n\tpublic int hashCode() {\r\n\t\tfinal int prime = 31;\r\n\t\tint result = 1;\r\n\t\tresult = prime * result + (int) (id ^ (id >>> 32));\r\n\t\tresult = prime * result + ((link == null) ? 0 : link.hashCode());\r\n\t\tresult = prime * result + ((updated == null) ? 0 : updated.hashCode());\r\n\t\treturn result;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic boolean equals(Object obj) {\r\n\t\tif (this == obj)\r\n\t\t\treturn true;\r\n\t\tif (obj == null)\r\n\t\t\treturn false;\r\n\t\tif (getClass() != obj.getClass())\r\n\t\t\treturn false;\r\n\t\tOrderFeedEntry other = (OrderFeedEntry) obj;\r\n\t\tif (id != other.id)\r\n\t\t\treturn false;\r\n\t\tif (link == null) {\r\n\t\t\tif (other.link != null)\r\n\t\t\t\treturn false;\r\n\t\t} else if (!link.equals(other.link))\r\n\t\t\treturn false;\r\n\t\tif (updated == null) {\r\n\t\t\tif (other.updated != null)\r\n\t\t\t\treturn false;\r\n\t\t} else if (!updated.equals(other.updated))\r\n\t\t\treturn false;\r\n\t\treturn true;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic String toString() {\r\n\t\treturn \"OrderFeedEntry [id=\" + id + \", link=\" + link + \", updated=\" + updated + \"]\";\r\n\t}\r\n\r\n\r\n \r\n \r\n}" } ]
import java.util.ArrayList; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpHeaders; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.context.request.WebRequest; import com.ewolff.microservice.order.OrderFeed; import com.ewolff.microservice.order.OrderFeedEntry; import jakarta.servlet.http.HttpServletRequest;
1,357
package com.ewolff.microservice.order.logic; @RestController public class OrderRestController { private final Logger log = LoggerFactory.getLogger(OrderRestController.class); private String baseUrl = null; private OrderRepository orderRepository; public OrderRestController(OrderRepository orderRepository, @Value("${baseUrl}") String baseUrl) { this.orderRepository = orderRepository; this.baseUrl = baseUrl; } @RequestMapping(value = "/feed", produces = "application/json") public OrderFeed orderFeed(WebRequest webRequest, HttpServletRequest httpRequest) { if ((orderRepository.lastUpdate() != null) && (webRequest.checkNotModified(orderRepository.lastUpdate().getTime()))) { log.trace("Not Modified returned - request with If-Modified-Since {}", webRequest.getHeader(HttpHeaders.IF_MODIFIED_SINCE)); return null; } log.trace("Returned Feed");
package com.ewolff.microservice.order.logic; @RestController public class OrderRestController { private final Logger log = LoggerFactory.getLogger(OrderRestController.class); private String baseUrl = null; private OrderRepository orderRepository; public OrderRestController(OrderRepository orderRepository, @Value("${baseUrl}") String baseUrl) { this.orderRepository = orderRepository; this.baseUrl = baseUrl; } @RequestMapping(value = "/feed", produces = "application/json") public OrderFeed orderFeed(WebRequest webRequest, HttpServletRequest httpRequest) { if ((orderRepository.lastUpdate() != null) && (webRequest.checkNotModified(orderRepository.lastUpdate().getTime()))) { log.trace("Not Modified returned - request with If-Modified-Since {}", webRequest.getHeader(HttpHeaders.IF_MODIFIED_SINCE)); return null; } log.trace("Returned Feed");
List<OrderFeedEntry> orderFeedEntries = new ArrayList<OrderFeedEntry>();
1
2023-10-25 09:22:16+00:00
2k
gongxuanzhang/EasyByte
easyByte-core/src/test/java/org/gongxuanzhang/easybyte/core/environment/MapConvertRegisterTest.java
[ { "identifier": "ReadConverter", "path": "easyByte-core/src/main/java/org/gongxuanzhang/easybyte/core/ReadConverter.java", "snippet": "@FunctionalInterface\npublic interface ReadConverter<V> {\n\n /**\n * convert object from byte array\n *\n * @param bytes from buffer,if length less zero bytes is null.\n * @param length general length is bytes length but sometime the length have special meaning\n * @return maybe null\n **/\n V toObject(byte[] bytes, int length);\n\n\n}" }, { "identifier": "WriteConverter", "path": "easyByte-core/src/main/java/org/gongxuanzhang/easybyte/core/WriteConverter.java", "snippet": "@FunctionalInterface\npublic interface WriteConverter<V> {\n\n /**\n * convert sth to byte array\n *\n * @param v can convert value\n * @return byte array ,may be length is zero. if the length less zero has special meaning return null\n **/\n byte[] toBytes(V v);\n\n\n}" }, { "identifier": "ConvertDuplicationException", "path": "easyByte-core/src/main/java/org/gongxuanzhang/easybyte/core/exception/ConvertDuplicationException.java", "snippet": "public class ConvertDuplicationException extends RuntimeException {\n\n\n public ConvertDuplicationException(ConvertRegister convertRegister, WriteConverter<?> convert) {\n super(convertRegister.getClass().getSimpleName() + \" has been register \" + convert.getClass().getSimpleName());\n }\n\n public ConvertDuplicationException(ConvertRegister convertRegister, ReadConverter<?> convert) {\n super(convertRegister.getClass().getSimpleName() + \" has been register \" + convert.getClass().getSimpleName());\n }\n}" }, { "identifier": "GenericNotFoundException", "path": "easyByte-core/src/main/java/org/gongxuanzhang/easybyte/core/exception/GenericNotFoundException.java", "snippet": "public class GenericNotFoundException extends RuntimeException {\n\n private static final String ANONYMOUS_NAME_ITEM = \"$$\";\n\n private static String maybeAnonymousMessage(Class<?> type) {\n if (!type.getName().contains(ANONYMOUS_NAME_ITEM)) {\n return \"\";\n }\n return \"register converter not allow anonymous object\";\n\n }\n\n public GenericNotFoundException(Class<?> type) {\n super(type.getSimpleName() + \"generic does not exists \" + maybeAnonymousMessage(type));\n }\n}" } ]
import org.gongxuanzhang.easybyte.core.ReadConverter; import org.gongxuanzhang.easybyte.core.WriteConverter; import org.gongxuanzhang.easybyte.core.exception.ConvertDuplicationException; import org.gongxuanzhang.easybyte.core.exception.GenericNotFoundException; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertThrowsExactly;
724
package org.gongxuanzhang.easybyte.core.environment; class MapConvertRegisterTest { @Test void testRegisterRead() { MapConvertRegister mapConvertRegister = new MapConvertRegister(); assertNull(mapConvertRegister.findReadConverter(TestRead.class)); TestRead testRead = new TestRead(); mapConvertRegister.registerReadConverter(testRead); assertSame(testRead, mapConvertRegister.findReadConverter(TestRead.class)); }
package org.gongxuanzhang.easybyte.core.environment; class MapConvertRegisterTest { @Test void testRegisterRead() { MapConvertRegister mapConvertRegister = new MapConvertRegister(); assertNull(mapConvertRegister.findReadConverter(TestRead.class)); TestRead testRead = new TestRead(); mapConvertRegister.registerReadConverter(testRead); assertSame(testRead, mapConvertRegister.findReadConverter(TestRead.class)); }
static class TestRead implements ReadConverter<TestRead> {
0
2023-10-31 10:11:54+00:00
2k
Lyn4ever29/halo-plugin-export-md
src/main/java/cn/lyn4ever/export2md/service/impl/ImportServiceV2.java
[ { "identifier": "PostRequest", "path": "src/main/java/cn/lyn4ever/export2md/halo/PostRequest.java", "snippet": "@Data\npublic class PostRequest {\n\n\n private Post post;\n private Content content;\n\n public PostRequest(Post post, Content content) {\n this.post = post;\n this.content = content;\n }\n\n public ContentRequest contentRequest() {\n Ref subjectRef = Ref.of(post);\n return new ContentRequest(subjectRef, post.getSpec().getHeadSnapshot(), content.getRaw(),\n content.getContent(), content.getRawType());\n }\n}" }, { "identifier": "ImportLogSchema", "path": "src/main/java/cn/lyn4ever/export2md/schema/ImportLogSchema.java", "snippet": "@Data\n@ToString\n@EqualsAndHashCode(callSuper = true)\n@GVK(kind = \"ImportLog\", group = \"cn.lyn4ever.export2doc\",\n version = \"v1alpha1\", singular = \"importLog\", plural = \"importLogs\")\npublic class ImportLogSchema extends AbstractExtension {\n @Schema\n private String name = LocalDateTime.now().toString();\n @Schema\n private Date createTime = new Date();\n @Schema\n private Long costSeconds;\n @Schema\n private String title;\n /**\n * 文章name\n */\n @Schema\n private String postName;\n\n /**\n * 状态\n * a-失败\n * b-导出中\n * c-成功\n */\n @Schema\n private String status;\n}" }, { "identifier": "ImportService", "path": "src/main/java/cn/lyn4ever/export2md/service/ImportService.java", "snippet": "public interface ImportService {\n\n\n /**\n * 运行导出任务\n *\n * @param filePart\n */\n Mono<Post> runTask(File file);\n\n}" }, { "identifier": "PostService", "path": "src/main/java/cn/lyn4ever/export2md/service/PostService.java", "snippet": "public interface PostService {\n Mono<Post> draftPost(PostRequest postRequest);\n\n Mono<Post> updatePost(PostRequest postRequest);\n\n Mono<Post> updateBy(@NonNull Post post);\n\n Mono<ContentWrapper> getHeadContent(String postName);\n\n Mono<ContentWrapper> getHeadContent(Post post);\n\n Mono<ContentWrapper> getReleaseContent(String postName);\n\n Mono<ContentWrapper> getReleaseContent(Post post);\n\n Mono<Post> publish(Post post);\n\n Mono<Post> unpublish(Post post);\n\n Mono<Post> getByUsername(String postName, String username);\n\n PostRequest formatPost(File file);\n}" } ]
import cn.hutool.core.lang.UUID; import cn.lyn4ever.export2md.halo.PostRequest; import cn.lyn4ever.export2md.schema.ImportLogSchema; import cn.lyn4ever.export2md.service.ImportService; import cn.lyn4ever.export2md.service.PostService; import java.io.File; import java.security.Principal; import java.util.Date; import lombok.RequiredArgsConstructor; import org.springframework.security.core.context.ReactiveSecurityContextHolder; import org.springframework.security.core.context.SecurityContext; import org.springframework.stereotype.Service; import reactor.core.publisher.Mono; import run.halo.app.core.extension.content.Post; import run.halo.app.extension.Metadata; import run.halo.app.extension.ReactiveExtensionClient;
838
package cn.lyn4ever.export2md.service.impl; /** * @author Lyn4ever29 * @url https://jhacker.cn * @date 2023/12/5 */ @Service @RequiredArgsConstructor public class ImportServiceV2 implements ImportService {
package cn.lyn4ever.export2md.service.impl; /** * @author Lyn4ever29 * @url https://jhacker.cn * @date 2023/12/5 */ @Service @RequiredArgsConstructor public class ImportServiceV2 implements ImportService {
private final PostService postService;
3
2023-10-29 16:01:45+00:00
2k
PhilipPanda/Temple-Client
src/main/java/xyz/templecheats/templeclient/impl/modules/misc/Blink.java
[ { "identifier": "EventStageable", "path": "src/main/java/xyz/templecheats/templeclient/api/event/EventStageable.java", "snippet": "public class EventStageable {\n\n private EventStage stage;\n\n public EventStageable() {\n\n }\n\n public EventStageable(EventStage stage) {\n this.stage = stage;\n }\n\n public EventStage getStage() {\n return stage;\n }\n\n public void setStage(EventStage stage) {\n this.stage = stage;\n }\n\n public enum EventStage {\n PRE, POST\n }\n\n}" }, { "identifier": "PacketEvent", "path": "src/main/java/xyz/templecheats/templeclient/api/event/events/network/PacketEvent.java", "snippet": "public class PacketEvent extends EventCancellable {\n\n private final Packet packet;\n\n public PacketEvent(Packet packet) {\n this.packet = packet;\n }\n\n public Packet getPacket() {\n return packet;\n }\n\n public static class Receive extends PacketEvent {\n public Receive(Packet packet) {\n super(packet);\n }\n }\n\n public static class Send extends PacketEvent {\n public Send(Packet packet) {\n super(packet);\n }\n }\n}" }, { "identifier": "Module", "path": "src/main/java/xyz/templecheats/templeclient/impl/modules/Module.java", "snippet": "public class Module {\n public String name;\n public boolean toggled;\n public int KeyCode;\n public Category category;\n public static Minecraft mc = Minecraft.getMinecraft();\n private boolean queueEnable;\n\n public Module(String name, int keyCode, Category c) {\n this.name = name;\n this.KeyCode = keyCode;\n this.category = c;\n }\n\n public boolean isEnabled() {\n return toggled;\n }\n\n public int getKey() {\n return KeyCode;\n }\n\n //do not override\n public final void onUpdateInternal() {\n if(mc.player != null) {\n if(this.queueEnable) {\n this.queueEnable = false;\n this.onEnable();\n }\n\n if(this.isToggled()) {\n this.onUpdate();\n }\n }\n\n this.onUpdateConstant();\n }\n\n public void onUpdate() {}\n\n public void onUpdateConstant() {}\n\n public void onEnable() {}\n\n public void onDisable() {}\n\n public void enable() {\n this.toggled = true;\n MinecraftForge.EVENT_BUS.register(this);\n TempleClient.eventBus.addEventListener(this);\n\n if(mc.player != null) {\n this.onEnable();\n } else {\n this.queueEnable = true;\n }\n }\n\n public void disable() {\n this.toggled = false;\n MinecraftForge.EVENT_BUS.unregister(this);\n TempleClient.eventBus.removeEventListener(this);\n\n if(mc.player != null) {\n this.onDisable();\n }\n }\n\n public void toggle() {\n this.setToggled(!this.isToggled());\n }\n\n public void setToggled(boolean toggled) {\n //dont do anything if the toggled state is the same\n if(toggled == this.toggled) return;\n\n if(toggled) {\n this.enable();\n } else {\n this.disable();\n }\n }\n\n public boolean isToggled() {\n return toggled;\n }\n\n public void setKey(int key) {\n this.KeyCode = key;\n }\n\n public Category getCategory() {\n return category;\n }\n\n public String getName() {\n return this.name;\n }\n\n public enum Category {\n CHAT,\n COMBAT,\n MISC,\n MOVEMENT,\n RENDER,\n WORLD,\n CLIENT;\n }\n}" } ]
import xyz.templecheats.templeclient.api.event.EventStageable; import xyz.templecheats.templeclient.api.event.events.network.PacketEvent; import net.minecraft.client.Minecraft; import net.minecraft.client.entity.EntityOtherPlayerMP; import net.minecraft.network.Packet; import net.minecraft.network.play.client.*; import org.lwjgl.input.Keyboard; import team.stiff.pomelo.impl.annotated.handler.annotation.Listener; import xyz.templecheats.templeclient.impl.modules.Module; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue;
1,223
package xyz.templecheats.templeclient.impl.modules.misc; public final class Blink extends Module { private final Queue<Packet> packets = new ConcurrentLinkedQueue(); private EntityOtherPlayerMP entity; public Blink() { super("Blink", Keyboard.KEY_NONE, Category.MISC); } @Override public void onEnable() { super.onEnable(); final Minecraft mc = Minecraft.getMinecraft(); if (mc.world != null) { this.entity = new EntityOtherPlayerMP(mc.world, mc.getSession().getProfile()); this.entity.copyLocationAndAnglesFrom(mc.player); this.entity.rotationYaw = mc.player.rotationYaw; this.entity.rotationYawHead = mc.player.rotationYawHead; this.entity.inventory.copyInventory(mc.player.inventory); mc.world.addEntityToWorld(6942069, this.entity); } } @Listener
package xyz.templecheats.templeclient.impl.modules.misc; public final class Blink extends Module { private final Queue<Packet> packets = new ConcurrentLinkedQueue(); private EntityOtherPlayerMP entity; public Blink() { super("Blink", Keyboard.KEY_NONE, Category.MISC); } @Override public void onEnable() { super.onEnable(); final Minecraft mc = Minecraft.getMinecraft(); if (mc.world != null) { this.entity = new EntityOtherPlayerMP(mc.world, mc.getSession().getProfile()); this.entity.copyLocationAndAnglesFrom(mc.player); this.entity.rotationYaw = mc.player.rotationYaw; this.entity.rotationYawHead = mc.player.rotationYawHead; this.entity.inventory.copyInventory(mc.player.inventory); mc.world.addEntityToWorld(6942069, this.entity); } } @Listener
public void sendPacket(PacketEvent.Send event) {
1
2023-10-28 12:03:50+00:00
2k
PlayReissLP/Continuity
src/main/java/me/pepperbell/continuity/client/processor/simple/RepeatSpriteProvider.java
[ { "identifier": "ProcessingDataProvider", "path": "src/main/java/me/pepperbell/continuity/api/client/ProcessingDataProvider.java", "snippet": "public interface ProcessingDataProvider {\n\t<T> T getData(ProcessingDataKey<T> key);\n}" }, { "identifier": "Symmetry", "path": "src/main/java/me/pepperbell/continuity/client/processor/Symmetry.java", "snippet": "public enum Symmetry {\n\tNONE,\n\tOPPOSITE,\n\tALL;\n\n\tpublic Direction getActualFace(Direction face) {\n\t\tif (this == Symmetry.OPPOSITE) {\n\t\t\tif (face.getDirection() == Direction.AxisDirection.POSITIVE) {\n\t\t\t\tface = face.getOpposite();\n\t\t\t}\n\t\t} else if (this == Symmetry.ALL) {\n\t\t\tface = Direction.DOWN;\n\t\t}\n\t\treturn face;\n\t}\n}" }, { "identifier": "RepeatCTMProperties", "path": "src/main/java/me/pepperbell/continuity/client/properties/RepeatCTMProperties.java", "snippet": "public class RepeatCTMProperties extends BaseCTMProperties {\n\tprotected int width;\n\tprotected int height;\n\tprotected Symmetry symmetry = Symmetry.NONE;\n\n\tpublic RepeatCTMProperties(Properties properties, Identifier id, String packName, int packPriority, String method) {\n\t\tsuper(properties, id, packName, packPriority, method);\n\t}\n\n\t@Override\n\tpublic void init() {\n\t\tsuper.init();\n\t\tparseWidth();\n\t\tparseHeight();\n\t\tparseSymmetry();\n\t}\n\n\tprotected void parseWidth() {\n\t\tString widthStr = properties.getProperty(\"width\");\n\t\tif (widthStr != null) {\n\t\t\twidthStr = widthStr.trim();\n\t\t\ttry {\n\t\t\t\tint width = Integer.parseInt(widthStr);\n\t\t\t\tif (width > 0) {\n\t\t\t\t\tthis.width = width;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t} catch (NumberFormatException e) {\n\t\t\t\t//\n\t\t\t}\n\t\t\tContinuityClient.LOGGER.error(\"Invalid 'width' value '\" + widthStr + \"' in file '\" + id + \"' in pack '\" + packName + \"'\");\n\t\t\tvalid = false;\n\t\t}\n\t}\n\n\tprotected void parseHeight() {\n\t\tString heightStr = properties.getProperty(\"height\");\n\t\tif (heightStr != null) {\n\t\t\theightStr = heightStr.trim();\n\t\t\ttry {\n\t\t\t\tint height = Integer.parseInt(heightStr);\n\t\t\t\tif (height > 0) {\n\t\t\t\t\tthis.height = height;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t} catch (NumberFormatException e) {\n\t\t\t\t//\n\t\t\t}\n\t\t\tContinuityClient.LOGGER.error(\"Invalid 'height' value '\" + heightStr + \"' in file '\" + id + \"' in pack '\" + packName + \"'\");\n\t\t\tvalid = false;\n\t\t}\n\t}\n\n\tprotected void parseSymmetry() {\n\t\tSymmetry symmetry = PropertiesParsingHelper.parseSymmetry(properties, \"symmetry\", id, packName);\n\t\tif (symmetry != null) {\n\t\t\tthis.symmetry = symmetry;\n\t\t}\n\t}\n\n\tpublic int getWidth() {\n\t\treturn width;\n\t}\n\n\tpublic int getHeight() {\n\t\treturn height;\n\t}\n\n\tpublic Symmetry getSymmetry() {\n\t\treturn symmetry;\n\t}\n}" } ]
import java.util.Random; import java.util.function.Supplier; import me.pepperbell.continuity.api.client.ProcessingDataProvider; import me.pepperbell.continuity.client.processor.Symmetry; import me.pepperbell.continuity.client.properties.RepeatCTMProperties; import net.fabricmc.fabric.api.renderer.v1.mesh.QuadView; import net.minecraft.block.BlockState; import net.minecraft.client.texture.Sprite; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Direction; import net.minecraft.world.BlockRenderView;
1,312
package me.pepperbell.continuity.client.processor.simple; public class RepeatSpriteProvider implements SpriteProvider { protected Sprite[] sprites; protected int width; protected int height; protected Symmetry symmetry; public RepeatSpriteProvider(Sprite[] sprites, int width, int height, Symmetry symmetry) { this.sprites = sprites; this.width = width; this.height = height; this.symmetry = symmetry; } @Override public Sprite getSprite(QuadView quad, Sprite sprite, BlockRenderView blockView, BlockState state, BlockPos pos, Supplier<Random> randomSupplier, ProcessingDataProvider dataProvider) { Direction face = symmetry.getActualFace(quad.lightFace()); int x = pos.getX(); int y = pos.getY(); int z = pos.getZ(); int spriteX; int spriteY; switch (face) { case DOWN: // MCPatcher uses a different formula for the down face. // It is not used here to maintain Optifine parity. // spriteX = -x; // spriteY = -z; spriteX = x; spriteY = -z - 1; break; case UP: spriteX = x; spriteY = z; break; case NORTH: spriteX = -x - 1; spriteY = -y; break; case SOUTH: spriteX = x; spriteY = -y; break; case WEST: spriteX = z; spriteY = -y; break; case EAST: spriteX = -z - 1; spriteY = -y; break; default: spriteX = 0; spriteY = 0; break; } spriteX %= width; if (spriteX < 0) { spriteX += width; } spriteY %= height; if (spriteY < 0) { spriteY += height; } return sprites[width * spriteY + spriteX]; }
package me.pepperbell.continuity.client.processor.simple; public class RepeatSpriteProvider implements SpriteProvider { protected Sprite[] sprites; protected int width; protected int height; protected Symmetry symmetry; public RepeatSpriteProvider(Sprite[] sprites, int width, int height, Symmetry symmetry) { this.sprites = sprites; this.width = width; this.height = height; this.symmetry = symmetry; } @Override public Sprite getSprite(QuadView quad, Sprite sprite, BlockRenderView blockView, BlockState state, BlockPos pos, Supplier<Random> randomSupplier, ProcessingDataProvider dataProvider) { Direction face = symmetry.getActualFace(quad.lightFace()); int x = pos.getX(); int y = pos.getY(); int z = pos.getZ(); int spriteX; int spriteY; switch (face) { case DOWN: // MCPatcher uses a different formula for the down face. // It is not used here to maintain Optifine parity. // spriteX = -x; // spriteY = -z; spriteX = x; spriteY = -z - 1; break; case UP: spriteX = x; spriteY = z; break; case NORTH: spriteX = -x - 1; spriteY = -y; break; case SOUTH: spriteX = x; spriteY = -y; break; case WEST: spriteX = z; spriteY = -y; break; case EAST: spriteX = -z - 1; spriteY = -y; break; default: spriteX = 0; spriteY = 0; break; } spriteX %= width; if (spriteX < 0) { spriteX += width; } spriteY %= height; if (spriteY < 0) { spriteY += height; } return sprites[width * spriteY + spriteX]; }
public static class Factory implements SpriteProvider.Factory<RepeatCTMProperties> {
2
2023-10-29 00:08:50+00:00
2k
BBMQyyds/Bright-Light-Building-Dreams
children/src/main/java/com/blbd/children/controller/ChatLinkController.java
[ { "identifier": "HttpResponseEntity", "path": "children/src/main/java/com/blbd/children/beans/HttpResponseEntity.java", "snippet": "@Repository\npublic class HttpResponseEntity {\n private String code;//状态码\n private Object data;//数据\n private String message;//消息\n\n public HttpResponseEntity() {\n }\n\n public HttpResponseEntity(String code, Object data, String message) {\n this.code = code;\n this.data = data;\n this.message = message;\n }\n\n @Override\n public String toString() {\n return \"HttpResponseEntity{\" +\n \"code='\" + code + '\\'' +\n \", data=\" + data +\n \", message='\" + message + '\\'' +\n '}';\n }\n\n public String getCode() {\n return code;\n }\n\n public void setCode(String code) {\n this.code = code;\n }\n\n public Object getData() {\n return data;\n }\n\n public void setData(Object data) {\n this.data = data;\n }\n\n public String getMessage() {\n return message;\n }\n\n public void setMessage(String message) {\n this.message = message;\n }\n}" }, { "identifier": "ChatLink", "path": "children/src/main/java/com/blbd/children/dao/entity/ChatLink.java", "snippet": "@Data\npublic class ChatLink {\n private String linkId;\n private String senderId;\n private String receiverId;\n private Date creatTime;\n}" }, { "identifier": "Child", "path": "children/src/main/java/com/blbd/children/dao/entity/Child.java", "snippet": "@Data\r\n@EqualsAndHashCode(callSuper = false)\r\n@Accessors(chain = true)\r\n@TableName(\"child\")\r\n@AllArgsConstructor\r\n//@ApiModel(value=\"Child对象\", description=\"\")\r\npublic class Child {\r\n @TableId(value = \"id\", type = IdType.ASSIGN_UUID)\r\n private String id;\r\n @TableField(\"username\")\r\n private String username;\r\n @TableField(\"score\")\r\n private Integer score;\r\n @TableField(\"password\")\r\n private String password;\r\n @TableField(\"name\")\r\n private String name;\r\n @TableField(\"grade\")\r\n private String grade;\r\n @TableField(\"locate\")\r\n private String locate;\r\n @TableField(\"duty\")\r\n private Integer duty;\r\n @TableField(\"completed_tasks\")\r\n private Integer completedTasks;\r\n @TableField(\"volunteer_id\")\r\n private String volunteerId;\r\n public Child(String id, String username, Integer score) {\r\n this.id = id;\r\n this.username = username;\r\n this.score = score;\r\n }\r\n\r\n public Child() {\r\n\r\n }\r\n}\r" }, { "identifier": "ChildMapper", "path": "children/src/main/java/com/blbd/children/mapper/ChildMapper.java", "snippet": "@Repository //表示是持久层dao\npublic interface ChildMapper extends BaseMapper<Child> {\n\n}" }, { "identifier": "ChatLinkService", "path": "children/src/main/java/com/blbd/children/service/ChatLinkService.java", "snippet": "public interface ChatLinkService extends IService<ChatLink> {\n// IService<TaskChild>\n}" } ]
import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.blbd.children.beans.HttpResponseEntity; import com.blbd.children.dao.entity.ChatLink; import com.blbd.children.dao.entity.Child; import com.blbd.children.mapper.ChildMapper; import com.blbd.children.service.ChatLinkService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import java.util.HashMap; import java.util.Map;
861
package com.blbd.children.controller; @Controller @RequestMapping("/children/video") public class ChatLinkController { @Autowired
package com.blbd.children.controller; @Controller @RequestMapping("/children/video") public class ChatLinkController { @Autowired
ChildMapper childMapper;
3
2023-10-30 12:49:28+00:00
2k
sancar/kafkaDDS
src/main/java/io/github/sancar/kafkadds/linearizable/ReplicatedMap.java
[ { "identifier": "Records", "path": "src/main/java/io/github/sancar/kafkadds/totalorderbrodacast/Records.java", "snippet": "public class Records {\n\n public static final String HEADER_KEY_OPERATION = \"OPERATION\";\n\n public static class HeaderValues {\n public static final String WAIT_KEY = \"WAIT_KEY\";\n public static final String WRITE_ATTEMPT = \"WRITE_ATTEMPT\";\n }\n\n // Wait Key. Value of WaitKey is \"true\"\n public record WaitKey(String waitKey) { private static final String keyType = \"WAIT_KEY\";}\n\n public record WriteAttemptKey(String key) { private static final String keyType = \"WRITE_ATTEMPT\";}\n\n public record WriteAttemptValue(int version, String value) {\n }\n\n}" }, { "identifier": "TotalOrderBroadcast", "path": "src/main/java/io/github/sancar/kafkadds/totalorderbrodacast/TotalOrderBroadcast.java", "snippet": "public interface TotalOrderBroadcast {\n\n long offer(String key, String value, String header);\n\n Collection<Message> consume();\n}" }, { "identifier": "ValueBarrier", "path": "src/main/java/io/github/sancar/kafkadds/util/ValueBarrier.java", "snippet": "public class ValueBarrier {\n private final Lock mutex = new ReentrantLock();\n private final Condition cond = mutex.newCondition();\n private final AtomicLong sharedLong = new AtomicLong(-1);\n\n /**\n * Updates the shared long value to be the maximum of its current\n * value and the specified value. If the specified value is less\n * than or equal to the current value, the method does nothing.\n *\n * @param newValue the new value to set, if it is greater than\n * the current value\n */\n public void setIfBigger(long newValue) {\n try {\n mutex.lock();\n if (newValue > sharedLong.get()) {\n sharedLong.set(newValue);\n cond.signalAll();\n }\n } finally {\n mutex.unlock();\n }\n }\n\n /**\n * Waits until the shared long value is greater than or equal to\n * the target value. If the target value is already met, the\n * method returns immediately. Otherwise, the calling coroutine\n * blocks until another coroutine updates the shared long value to\n * be greater than or equal to the target value.\n *\n * @param targetValue the target value to wait for\n * @param timeout the maximum time to wait\n * @param unit the time unit of the timeout argument\n * @return true if the shared long value was updated to be greater\n * than or equal to the target value before the timeout,\n * false otherwise\n */\n public boolean await(long targetValue, int timeout, TimeUnit unit) throws InterruptedException {\n if (sharedLong.get() >= targetValue) {\n return true;\n }\n try {\n mutex.lock();\n long deadLineInMillis = System.currentTimeMillis() + unit.toMillis(timeout);\n while (sharedLong.get() < targetValue) {\n long sleepTime = deadLineInMillis - System.currentTimeMillis();\n if (sleepTime <= 0) {\n return false;\n }\n cond.await(sleepTime, TimeUnit.MILLISECONDS);\n }\n } finally {\n mutex.unlock();\n }\n return true;\n }\n}" }, { "identifier": "toJson", "path": "src/main/java/io/github/sancar/kafkadds/util/Json.java", "snippet": "public static String toJson(Object object) {\n try {\n return mapper.writeValueAsString(object);\n } catch (JsonProcessingException e) {\n throw new RuntimeException(e);\n }\n}" }, { "identifier": "toObject", "path": "src/main/java/io/github/sancar/kafkadds/util/Json.java", "snippet": "public static <T> T toObject(String jsonStr, Class<T> valueType) {\n try {\n return mapper.readValue(jsonStr, valueType);\n } catch (JsonProcessingException e) {\n throw new RuntimeException(e);\n }\n}" } ]
import io.github.sancar.kafkadds.totalorderbrodacast.Message; import io.github.sancar.kafkadds.totalorderbrodacast.Records; import io.github.sancar.kafkadds.totalorderbrodacast.TotalOrderBroadcast; import io.github.sancar.kafkadds.util.ValueBarrier; import org.jetbrains.annotations.NotNull; import java.io.Closeable; import java.util.*; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import java.util.stream.Collectors; import static io.github.sancar.kafkadds.util.Json.toJson; import static io.github.sancar.kafkadds.util.Json.toObject;
1,198
package io.github.sancar.kafkadds.linearizable; public class ReplicatedMap implements ConcurrentMap<String, String>, Closeable { public record VersionedValue(int version, String value) { } private final AtomicBoolean isRunning = new AtomicBoolean(true); // This lock is make sure that the data map and wait map is updated/read atomically private final Lock lock = new ReentrantLock(); private final ValueBarrier lastUpdateBarrier = new ValueBarrier();
package io.github.sancar.kafkadds.linearizable; public class ReplicatedMap implements ConcurrentMap<String, String>, Closeable { public record VersionedValue(int version, String value) { } private final AtomicBoolean isRunning = new AtomicBoolean(true); // This lock is make sure that the data map and wait map is updated/read atomically private final Lock lock = new ReentrantLock(); private final ValueBarrier lastUpdateBarrier = new ValueBarrier();
private final TotalOrderBroadcast totalOrderBroadcast;
1
2023-10-26 11:24:37+00:00
2k
dockyu/VoronoiDiagram
source/src/main/java/dev/dockyu/voronoidiagram/Model.java
[ { "identifier": "VoronoiDiagram", "path": "source/src/main/java/dev/dockyu/voronoidiagram/datastruct/VoronoiDiagram.java", "snippet": "public class VoronoiDiagram {\n // generator point\n public LinkedList<GeneratorPoint> generatorPoints;\n // winged-edge data struct\n public LinkedList<Polygon> polygons;\n public LinkedList<Vertex> vertexs;\n public LinkedList<Edge> edges;\n // convex hull\n public ConvexHull convexHull;\n\n public VoronoiDiagram() {\n this.generatorPoints = new LinkedList<>();\n this.polygons = new LinkedList<>();\n this.vertexs = new LinkedList<>();\n this.edges = new LinkedList<>();\n this.convexHull = new ConvexHull();\n }\n\n public LinkedList<Integer> edgesAroundPolygon(int polygonIndex) {\n // polygon周圍的edge,按順時針方式排列\n// System.out.println(\"edgesAroundPolygon start\");\n LinkedList<Integer> edges = new LinkedList<Integer>();\n\n int edgeIndex = this.polygons.get(polygonIndex).edge_around_polygon;\n int edgeStart = edgeIndex;\n\n do {\n// System.out.println(\"edgesAroundPolygon test\");\n edges.add(edgeIndex);\n if (polygonIndex == this.edges.get(edgeIndex).left_polygon) {\n // polygon在edge左邊\n edgeIndex = this.edges.get(edgeIndex).ccw_predecessor;\n } else {\n // polygon在edge右邊\n edgeIndex = this.edges.get(edgeIndex).ccw_successor;\n }\n } while (edgeIndex!=edgeStart);\n// System.out.println(\"edgesAroundPolygon end\");\n\n return edges;\n }\n\n public LinkedList<Integer> vertexsAroundPolygon(int polygonIndex) {\n // polygon周圍的vertex,按順時針方式排列\n LinkedList<Integer> vertexs = new LinkedList<Integer>();\n\n int edgeIndex = this.polygons.get(polygonIndex).edge_around_polygon;\n int edgeStart = edgeIndex;\n\n do {\n if (polygonIndex == this.edges.get(edgeIndex).left_polygon) {\n // polygon在edge左邊\n vertexs.add(this.edges.get(edgeIndex).start_vertex);\n edgeIndex = this.edges.get(edgeIndex).ccw_predecessor;\n } else {\n // polygon在edge右邊\n vertexs.add(this.edges.get(edgeIndex).end_vertex);\n edgeIndex = this.edges.get(edgeIndex).ccw_successor;\n }\n } while (edgeIndex!=edgeStart);\n\n return vertexs;\n }\n\n public LinkedList<Integer> edgesAroundVertex(int vertexIndex) {\n // vertex周圍的edge,按順時針方式排列\n LinkedList<Integer> edges = new LinkedList<Integer>();\n\n int edgeIndex = this.vertexs.get(vertexIndex).edge_around_vertex;\n int edgeStart = edgeIndex;\n\n do {\n edges.add(edgeIndex);\n if (vertexIndex == this.edges.get(edgeIndex).start_vertex) {\n // polygon在edge左邊\n edgeIndex = this.edges.get(edgeIndex).cw_predecessor;\n } else {\n // polygon在edge右邊\n edgeIndex = this.edges.get(edgeIndex).cw_successor;\n }\n } while (edgeIndex!=edgeStart);\n\n return edges;\n }\n\n}" }, { "identifier": "GeneratorPoint", "path": "source/src/main/java/dev/dockyu/voronoidiagram/datastruct/GeneratorPoint.java", "snippet": "public class GeneratorPoint {\n float x; // x座標\n float y; // y座標\n\n public GeneratorPoint(float clickedX, float clickedY) {\n this.x = clickedX;\n this.y = clickedY;\n }\n\n public GeneratorPoint(GeneratorPoint other) {\n this.x = other.x;\n this.y = other.y;\n }\n\n public float getX() { return this.x;}\n public float getY() { return this.y;}\n}" } ]
import dev.dockyu.voronoidiagram.datastruct.VoronoiDiagram; // 導入VoronoiDiagram資料結構 import dev.dockyu.voronoidiagram.datastruct.GeneratorPoint; import java.util.LinkedList; // LinkedList實現Queue
1,090
package dev.dockyu.voronoidiagram; public class Model { LinkedList<LinkedList<GeneratorPoint>> tasks; // 未來所有任務的 生成點 點集 LinkedList<GeneratorPoint> taskPoints; // 目前任務的 生成點 點集
package dev.dockyu.voronoidiagram; public class Model { LinkedList<LinkedList<GeneratorPoint>> tasks; // 未來所有任務的 生成點 點集 LinkedList<GeneratorPoint> taskPoints; // 目前任務的 生成點 點集
LinkedList<VoronoiDiagram> taskState; // 目前任務狀態,Queue
0
2023-10-26 07:24:43+00:00
2k
oghenevovwerho/yaa
src/main/java/yaa/semantic/passes/fs2/F2BlockClz.java
[ { "identifier": "OverBlock", "path": "src/main/java/yaa/ast/OverBlock.java", "snippet": "public class OverBlock extends Stmt {\r\n public ObjectType type;\r\n public Map<String, List<NewFun>> methods;\r\n public boolean isClass;\r\n\r\n public OverBlock(ObjectType type, Map<String, List<NewFun>> methods) {\r\n this.methods = methods;\r\n this.type = type;\r\n }\r\n\r\n @Override\r\n public YaaInfo visit(FileState fs) {\r\n return fs.$blockInClz();\r\n }\r\n\r\n @Override\r\n public String toString() {\r\n return type + \"{...}\";\r\n }\r\n}\r" }, { "identifier": "NewFun", "path": "src/main/java/yaa/ast/NewFun.java", "snippet": "public class NewFun extends Stmt {\r\n public MtdIsWhat itIsWhat = MtdIsWhat.stmtMtd;\r\n public YaaToken name;\r\n public List<Parameter> parameters;\r\n public Stmt stmt;\r\n public ObjectType type;\r\n public List<TypeParam> typeParams = new ArrayList<>(1);\r\n public List<YaaMetaCall> metaCalls;\r\n public int privacy;\r\n\r\n public NewFun() {\r\n }\r\n\r\n @Override\r\n public YaaInfo visit(FileState fs) {\r\n return fs.$function(this);\r\n }\r\n\r\n public NewFun(List<Parameter> ps, ObjectType type, Stmt ss) {\r\n this.parameters = ps;\r\n this.stmt = ss;\r\n this.type = type;\r\n }\r\n\r\n @Override\r\n public String toString() {\r\n var ob = new StringBuilder();\r\n ob.append(name.content);\r\n if (typeParams.size() == 1) {\r\n ob.append('<').append(typeParams.get(0)).append(\">\");\r\n } else if (typeParams.size() > 1) {\r\n ob.append(\"<\");\r\n ob.append(typeParams.get(0));\r\n for (int i = 1; i < typeParams.size(); i++) {\r\n ob.append(\", \").append(typeParams.get(i));\r\n }\r\n ob.append(\">\");\r\n }\r\n ob.append(\"(\");\r\n if (parameters.size() == 1) {\r\n ob.append(parameters.get(0));\r\n } else if (parameters.size() > 1) {\r\n ob.append(parameters.get(0));\r\n for (int i = 1; i < parameters.size(); i++) {\r\n ob.append(\", \").append(parameters.get(i));\r\n }\r\n }\r\n ob.append(\")\");\r\n if (type != null) {\r\n ob.append(type);\r\n }\r\n ob.append(\"{...}\");\r\n return ob.toString();\r\n }\r\n}\r" }, { "identifier": "fs2", "path": "src/main/java/yaa/pojos/GlobalData.java", "snippet": "public static F2 fs2;\r" } ]
import yaa.ast.OverBlock; import yaa.ast.NewFun; import yaa.pojos.*; import static yaa.pojos.GlobalData.fs2;
834
package yaa.semantic.passes.fs2; public class F2BlockClz { public static void f2BlockInClz(OverBlock block) { fs2.pushTable(block); for (var parent$mtd$pack : block.methods.values()) { for (var parent$mtd : parent$mtd$pack) { overriddenMtd(parent$mtd); } } fs2.popTable(); } //I am handling this here so that the overridden methods of //an enclosing class (which might also act as the parent), //can be overridden with a "method shadow error" being thrown //It prevents some redundant tests like if a method is top //level or not.
package yaa.semantic.passes.fs2; public class F2BlockClz { public static void f2BlockInClz(OverBlock block) { fs2.pushTable(block); for (var parent$mtd$pack : block.methods.values()) { for (var parent$mtd : parent$mtd$pack) { overriddenMtd(parent$mtd); } } fs2.popTable(); } //I am handling this here so that the overridden methods of //an enclosing class (which might also act as the parent), //can be overridden with a "method shadow error" being thrown //It prevents some redundant tests like if a method is top //level or not.
private static void overriddenMtd(NewFun newFun) {
1
2023-10-26 17:41:13+00:00
2k
echcz/web-service
src/main/java/cn/echcz/webservice/config/WebExceptionHandler.java
[ { "identifier": "AuthorizationException", "path": "src/main/java/cn/echcz/webservice/exception/AuthorizationException.java", "snippet": "public class AuthorizationException extends ClientException {\n\n public AuthorizationException(String message, Throwable cause) {\n super(new ErrorInfo(ErrorCode.ILLEGAL_ACCESS, message), cause);\n }\n\n public AuthorizationException(String message) {\n this(message, null);\n }\n\n public AuthorizationException(Throwable cause) {\n super(new ErrorInfo(ErrorCode.ILLEGAL_ACCESS), cause);\n }\n\n public AuthorizationException() {\n this((Throwable) null);\n }\n}" }, { "identifier": "ClientException", "path": "src/main/java/cn/echcz/webservice/exception/ClientException.java", "snippet": "public class ClientException extends ApplicationException {\n\n public ClientException(ErrorInfo errorInfo, String message, Throwable cause) {\n super(errorInfo, message, cause);\n }\n\n public ClientException(ErrorInfo errorInfo, String message) {\n super(errorInfo, message);\n }\n\n public ClientException(ErrorInfo errorInfo, Throwable cause) {\n super(errorInfo, cause);\n }\n\n public ClientException(ErrorInfo errorInfo) {\n super(errorInfo);\n }\n}" }, { "identifier": "ApplicationException", "path": "src/main/java/cn/echcz/webservice/exception/ApplicationException.java", "snippet": "public class ApplicationException extends RuntimeException {\n /**\n * 错误数据体\n */\n @Getter\n private final ErrorInfo errorInfo;\n\n public ApplicationException(ErrorInfo errorInfo, String message, Throwable cause) {\n super(message, cause);\n this.errorInfo = errorInfo;\n }\n\n public ApplicationException(ErrorInfo errorInfo, String message) {\n this(errorInfo, message, null);\n }\n\n public ApplicationException(ErrorInfo errorInfo, Throwable cause) {\n this(errorInfo, errorInfo.code().name() + \": \" + errorInfo.message(), cause);\n }\n\n public ApplicationException(ErrorInfo errorInfo) {\n this(errorInfo, (Throwable) null);\n }\n}" }, { "identifier": "AuthenticationException", "path": "src/main/java/cn/echcz/webservice/exception/AuthenticationException.java", "snippet": "public class AuthenticationException extends ClientException {\n\n public AuthenticationException(String message, Throwable cause) {\n super(new ErrorInfo(ErrorCode.ILLEGAL_ACCESS, message), cause);\n }\n\n public AuthenticationException(String message) {\n this(message, null);\n }\n\n public AuthenticationException(Throwable cause) {\n super(new ErrorInfo(ErrorCode.ILLEGAL_ACCESS), cause);\n }\n\n public AuthenticationException() {\n this((Throwable) null);\n }\n}" }, { "identifier": "ErrorCode", "path": "src/main/java/cn/echcz/webservice/exception/ErrorCode.java", "snippet": "public enum ErrorCode {\n SERVER_FAULT(\"服务异常\"),\n SERVER_INCOMPLETE(\"服务未完成\"),\n BAD_REQUEST(\"错误的请求\"),\n UNSUPPORTED(\"不支持的操作\"),\n ILLEGAL_ACCESS(\"非法访问\"),\n ILLEGAL_ARGUMENT(\"非法的参数\"),\n NOT_FOUND(\"数据不存在\"),\n DATA_DUPLICATE(\"数据已存在\"),\n /* 请根据自己的实际请问添加更多状态码 */\n ;\n\n /**\n * 错误消息\n */\n @Getter\n private final String message;\n\n ErrorCode(String message) {\n this.message = message;\n }\n}" }, { "identifier": "ServerException", "path": "src/main/java/cn/echcz/webservice/exception/ServerException.java", "snippet": "public class ServerException extends ApplicationException {\n\n public ServerException(ErrorInfo errorInfo, String message, Throwable cause) {\n super(errorInfo, message, cause);\n }\n\n public ServerException(ErrorInfo errorInfo, String message) {\n super(errorInfo, message);\n }\n\n public ServerException(ErrorInfo errorInfo, Throwable cause) {\n super(errorInfo, cause);\n }\n\n public ServerException(ErrorInfo errorInfo) {\n super(errorInfo);\n }\n}" } ]
import cn.echcz.webservice.exception.AuthorizationException; import cn.echcz.webservice.exception.ClientException; import cn.echcz.webservice.exception.ErrorInfo; import lombok.extern.slf4j.Slf4j; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.http.converter.HttpMessageNotReadableException; import org.springframework.validation.BindException; import org.springframework.validation.ObjectError; import org.springframework.web.HttpMediaTypeException; import org.springframework.web.HttpMediaTypeNotAcceptableException; import org.springframework.web.HttpRequestMethodNotSupportedException; import org.springframework.web.bind.ServletRequestBindingException; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException; import cn.echcz.webservice.exception.ApplicationException; import cn.echcz.webservice.exception.AuthenticationException; import cn.echcz.webservice.exception.ErrorCode; import cn.echcz.webservice.exception.ServerException; import javax.validation.ConstraintViolation; import javax.validation.ConstraintViolationException; import java.util.List; import java.util.Objects;
1,329
package cn.echcz.webservice.config; /** * 全局异常处理 */ @Slf4j @RestControllerAdvice public class WebExceptionHandler { @ExceptionHandler(AuthenticationException.class) public ResponseEntity<ErrorInfo> handleAuthenticationException(AuthenticationException e) { log.info("用户认证失败: {}", e.toString()); return new ResponseEntity<>(e.getErrorInfo(), HttpStatus.UNAUTHORIZED); } @ExceptionHandler(AuthorizationException.class) public ResponseEntity<ErrorInfo> handleAuthorizationException(AuthorizationException e) { log.info("用户授权失败: {}", e.toString()); return new ResponseEntity<>(e.getErrorInfo(), HttpStatus.FORBIDDEN); } @ExceptionHandler(ClientException.class) public ResponseEntity<ErrorInfo> handleClientException(ClientException e) { log.info("用户请求错误: {}", e.toString()); return new ResponseEntity<>(e.getErrorInfo(), HttpStatus.BAD_REQUEST); }
package cn.echcz.webservice.config; /** * 全局异常处理 */ @Slf4j @RestControllerAdvice public class WebExceptionHandler { @ExceptionHandler(AuthenticationException.class) public ResponseEntity<ErrorInfo> handleAuthenticationException(AuthenticationException e) { log.info("用户认证失败: {}", e.toString()); return new ResponseEntity<>(e.getErrorInfo(), HttpStatus.UNAUTHORIZED); } @ExceptionHandler(AuthorizationException.class) public ResponseEntity<ErrorInfo> handleAuthorizationException(AuthorizationException e) { log.info("用户授权失败: {}", e.toString()); return new ResponseEntity<>(e.getErrorInfo(), HttpStatus.FORBIDDEN); } @ExceptionHandler(ClientException.class) public ResponseEntity<ErrorInfo> handleClientException(ClientException e) { log.info("用户请求错误: {}", e.toString()); return new ResponseEntity<>(e.getErrorInfo(), HttpStatus.BAD_REQUEST); }
@ExceptionHandler(ServerException.class)
5
2023-10-30 18:55:49+00:00
2k
tom5454/Toms-Peripherals
Forge/src/main/java/com/tom/peripherals/platform/Platform.java
[ { "identifier": "Content", "path": "Forge/src/platform-shared/java/com/tom/peripherals/Content.java", "snippet": "public class Content {\n\tpublic static final GameObject<GPUBlock> gpu = blockWithItem(\"gpu\", GPUBlock::new);\n\tpublic static final GameObject<MonitorBlock> monitor = blockWithItem(\"monitor\", MonitorBlock::new);\n\tpublic static final GameObject<WatchDogTimerBlock> wdt = blockWithItem(\"wdt\", WatchDogTimerBlock::new);\n\tpublic static final GameObject<RedstonePortBlock> redstonePort = blockWithItem(\"redstone_port\", RedstonePortBlock::new);\n\n\tpublic static final GameObject<Item> gpuChip = item(\"gpu_chip\", () -> new Item(new Item.Properties()));\n\tpublic static final GameObject<Item> gpuChipRaw = item(\"gpu_chip_raw\", () -> new Item(new Item.Properties()));\n\n\tpublic static final GameObjectBlockEntity<GPUBlockEntity> gpuBE = blockEntity(\"gpu\", GPUBlockEntity::new, gpu);\n\tpublic static final GameObjectBlockEntity<MonitorBlockEntity> monitorBE = blockEntity(\"monitor\", MonitorBlockEntity::new, monitor);\n\tpublic static final GameObjectBlockEntity<WatchDogTimerBlockEntity> wdtBE = blockEntity(\"wdt\", WatchDogTimerBlockEntity::new, wdt);\n\tpublic static final GameObjectBlockEntity<RedstonePortBlockEntity> redstonePortBE = blockEntity(\"redstone_port\", RedstonePortBlockEntity::new, redstonePort);\n\n\tprivate static <B extends Block> GameObject<B> blockWithItem(String name, Supplier<B> create) {\n\t\treturn blockWithItem(name, create, b -> new BlockItem(b, new Item.Properties()));\n\t}\n\n\tprivate static <B extends Block, I extends Item> GameObject<B> blockWithItem(String name, Supplier<B> create, Function<Block, I> createItem) {\n\t\tGameObject<B> re = Platform.BLOCKS.register(name, create);\n\t\titem(name, () -> createItem.apply(re.get()));\n\t\treturn re;\n\t}\n\n\tprivate static <I extends Item> GameObject<I> item(String name, Supplier<I> fact) {\n\t\treturn Platform.ITEMS.register(name, () -> Platform.addItemToTab(fact.get()));\n\t}\n\n\t@SuppressWarnings(\"unchecked\")\n\t@SafeVarargs\n\tprivate static <BE extends BlockEntity> GameObjectBlockEntity<BE> blockEntity(String name, BlockEntityFactory<? extends BE> create, GameObject<? extends Block>... blocks) {\n\t\treturn (GameObjectBlockEntity<BE>) Platform.BLOCK_ENTITY.registerBE(name, create, blocks);\n\t}\n\n\tpublic static void init() {\n\t}\n}" }, { "identifier": "PeripheralsMod", "path": "Fabric/src/main/java/com/tom/peripherals/PeripheralsMod.java", "snippet": "public class PeripheralsMod implements ModInitializer {\n\tpublic static final String ID = \"toms_peripherals\";\n\tpublic static final Logger LOGGER = LogUtils.getLogger();\n\n\t@Override\n\tpublic void onInitialize() {\n\t\tContent.init();\n\t\tPlatform.register();\n\n\t\tForgeConfigRegistry.INSTANCE.register(ID, ModConfig.Type.COMMON, Config.commonSpec);\n\t\tForgeConfigRegistry.INSTANCE.register(ID, ModConfig.Type.SERVER, Config.serverSpec);\n\n\t\tModConfigEvents.loading(ID).register(c -> {\n\t\t\tLOGGER.info(\"Loaded Tom's Peripherals config file {}\", c.getFileName());\n\t\t\tConfig.load(c);\n\t\t});\n\t\tModConfigEvents.reloading(ID).register(c -> {\n\t\t\tLOGGER.info(\"Tom's Peripherals config just got changed on the file system!\");\n\t\t\tConfig.load(c);\n\t\t});\n\n\t\tPeripheralLookup.get().registerForBlockEntities((b, side) -> {\n\t\t\tif (b instanceof AbstractPeripheralBlockEntity be)\n\t\t\t\treturn be.getCCPeripheral();\n\t\t\treturn null;\n\t\t}, Content.gpuBE.get(), Content.redstonePortBE.get(), Content.wdtBE.get());\n\t}\n\n}" }, { "identifier": "GameRegistry", "path": "Fabric/src/main/java/com/tom/peripherals/platform/GameObject.java", "snippet": "public static class GameRegistry<T> {\n\tprotected final Registry<T> registry;\n\n\tpublic GameRegistry(Registry<T> registry) {\n\t\tthis.registry = registry;\n\t}\n\n\tpublic <I extends T> GameObject<I> register(final String name, final Supplier<? extends I> sup) {\n\t\tI obj = sup.get();\n\t\tRegistry.register(registry, new ResourceLocation(PeripheralsMod.ID, name), obj);\n\t\treturn new GameObject<>(obj);\n\t}\n}" }, { "identifier": "GameRegistryBE", "path": "Fabric/src/main/java/com/tom/peripherals/platform/GameObject.java", "snippet": "public static class GameRegistryBE extends GameRegistry<BlockEntityType<?>> {\n\tprivate List<GameObjectBlockEntity<?>> blockEntities = new ArrayList<>();\n\n\tpublic GameRegistryBE(Registry<BlockEntityType<?>> registry) {\n\t\tsuper(registry);\n\t}\n\n\t@SuppressWarnings(\"unchecked\")\n\tpublic <BE extends BlockEntity, I extends BlockEntityType<BE>> GameObjectBlockEntity<BE> registerBE(String name, BlockEntityFactory<BE> sup, GameObject<? extends Block>... blocks) {\n\t\tGameObjectBlockEntity<BE> e = new GameObjectBlockEntity<>(this, name, new ArrayList<>(Arrays.asList(blocks)), sup);\n\t\tblockEntities.add(e);\n\t\treturn e;\n\t}\n\n\tpublic void register() {\n\t\tblockEntities.forEach(GameObjectBlockEntity::register);\n\t}\n\n\tpublic static interface BlockEntityFactory<T extends BlockEntity> {\n\t\tT create(BlockEntityType<T> type, BlockPos pos, BlockState state);\n\t}\n}" } ]
import java.util.ArrayList; import java.util.List; import net.minecraft.core.registries.Registries; import net.minecraft.network.chat.Component; import net.minecraft.server.MinecraftServer; import net.minecraft.world.item.CreativeModeTab; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.block.Block; import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext; import net.minecraftforge.registries.DeferredRegister; import net.minecraftforge.registries.ForgeRegistries; import net.minecraftforge.registries.RegistryObject; import net.minecraftforge.server.ServerLifecycleHooks; import com.tom.peripherals.Content; import com.tom.peripherals.PeripheralsMod; import com.tom.peripherals.platform.GameObject.GameRegistry; import com.tom.peripherals.platform.GameObject.GameRegistryBE;
1,476
package com.tom.peripherals.platform; public class Platform { public static final GameRegistry<Item> ITEMS = new GameRegistry<>(ForgeRegistries.ITEMS); public static final GameRegistry<Block> BLOCKS = new GameRegistry<>(ForgeRegistries.BLOCKS); public static final GameRegistryBE BLOCK_ENTITY = new GameRegistryBE();
package com.tom.peripherals.platform; public class Platform { public static final GameRegistry<Item> ITEMS = new GameRegistry<>(ForgeRegistries.ITEMS); public static final GameRegistry<Block> BLOCKS = new GameRegistry<>(ForgeRegistries.BLOCKS); public static final GameRegistryBE BLOCK_ENTITY = new GameRegistryBE();
public static final DeferredRegister<CreativeModeTab> TAB = DeferredRegister.create(Registries.CREATIVE_MODE_TAB, PeripheralsMod.ID);
1
2023-10-30 17:05:11+00:00
2k
quentin452/DangerRPG-Continuation
src/main/java/mixac1/dangerrpg/capability/data/RPGDataRegister.java
[ { "identifier": "ElementData", "path": "src/main/java/mixac1/dangerrpg/capability/data/RPGDataRegister.java", "snippet": "public static abstract class ElementData<Key, TransferData> {\n\n public boolean isActivated;\n public boolean isSupported;\n\n public abstract TransferData getTransferData(Key key);\n\n public abstract void unpackTransferData(TransferData data);\n}" }, { "identifier": "Pair", "path": "src/main/java/mixac1/dangerrpg/util/Tuple.java", "snippet": "public static class Pair<T1, T2> extends Stub<T1> {\n\n public T2 value2;\n\n public Pair(T1 value1, T2 value2) {\n super(value1);\n this.value2 = value2;\n }\n\n public static <T1, T2> Pair<T1, T2> create(T1 value1, T2 value2) {\n return new Pair<T1, T2>(value1, value2);\n }\n}" }, { "identifier": "Utils", "path": "src/main/java/mixac1/dangerrpg/util/Utils.java", "snippet": "public abstract class Utils {\n\n public static Random rand = new Random();\n\n public static <T> Iterable<T> safe(Iterable<T> iterable) {\n return iterable == null ? Collections.<T>emptyList() : iterable;\n }\n\n public static float alignment(float value, float min, float max) {\n if (value < min) {\n return min;\n } else if (value > max) {\n return max;\n }\n return value;\n }\n\n public static double invert(double value) {\n return -value;\n }\n\n public static double invert(double value, boolean isInvert) {\n return isInvert ? invert(value) : value;\n }\n\n public static String toString(Object... objs) {\n StringBuilder buf = new StringBuilder();\n for (Object obj : objs) {\n buf.append(obj != null ? obj.toString() : \"(null)\");\n }\n return buf.toString();\n }\n\n public static double getDiagonal(double x, double y) {\n return Math.sqrt(x * x + y * y);\n }\n\n public static double getDiagonal(double x, double y, double z) {\n return Math.sqrt(x * x + y * y + z * z);\n }\n\n public static int randInt(Random rand, int bound, boolean isAroundZero) {\n if (isAroundZero) {\n return rand.nextInt(bound * 2) - bound;\n } else {\n return rand.nextInt(bound);\n }\n }\n\n public static int randInt(int bound, boolean isAroundZero) {\n return randInt(rand, bound, isAroundZero);\n }\n\n /**\n * @param accuracy - count of zero after dot\n */\n public static double randDouble(Random rand, double bound, int accuracy, boolean isAroundZero) {\n accuracy = (int) Math.pow(10, accuracy);\n return randInt(rand, (int) (accuracy * bound), isAroundZero) / accuracy;\n }\n\n public static double randDouble(double bound, int accuracy, boolean isAroundZero) {\n return randDouble(rand, bound, accuracy, isAroundZero);\n }\n\n public static <Type> byte[] serialize(Type obj) {\n ByteArrayOutputStream bos = new ByteArrayOutputStream();\n ObjectOutput out = null;\n byte[] ret = null;\n try {\n out = new ObjectOutputStream(bos);\n out.writeObject(obj);\n out.flush();\n ret = bos.toByteArray();\n bos.close();\n } catch (Exception e) {\n e.printStackTrace();\n }\n return ret;\n }\n\n public static <Type> Type deserialize(byte[] obj) {\n ByteArrayInputStream bis = new ByteArrayInputStream(obj);\n ObjectInput in = null;\n Type ret = null;\n try {\n in = new ObjectInputStream(bis);\n ret = (Type) in.readObject();\n in.close();\n } catch (Exception e) {\n e.printStackTrace();\n }\n return ret;\n }\n}" } ]
import mixac1.dangerrpg.capability.data.RPGDataRegister.ElementData; import mixac1.dangerrpg.util.Tuple.Pair; import mixac1.dangerrpg.util.Utils; import java.util.HashMap; import java.util.LinkedList; import java.util.Map;
1,332
package mixac1.dangerrpg.capability.data; public abstract class RPGDataRegister<Key, Data extends ElementData<Key, TransferData>, TransferKey, TransferData> extends HashMap<Key, Data> { private byte[] transferData; public boolean isActivated(Key key) { return containsKey(key) && get(key).isActivated; } public boolean isSupported(Key key) { return containsKey(key) && get(key).isSupported; } public Map<Key, Data> getActiveElements() { HashMap<Key, Data> map = new HashMap<Key, Data>(); for (Entry<Key, Data> entry : entrySet()) { if (entry.getValue().isActivated) { map.put(entry.getKey(), entry.getValue()); } } return map; } protected abstract TransferKey codingKey(Key key); protected abstract Key decodingKey(TransferKey key); public void createTransferData() { LinkedList<Pair<TransferKey, TransferData>> list = new LinkedList<Pair<TransferKey, TransferData>>(); for (Entry<Key, Data> entry : getActiveElements().entrySet()) { TransferKey key = codingKey(entry.getKey()); if (key != null) { list.add( new Pair<TransferKey, TransferData>( key, entry.getValue() != null ? entry.getValue() .getTransferData(entry.getKey()) : null)); } }
package mixac1.dangerrpg.capability.data; public abstract class RPGDataRegister<Key, Data extends ElementData<Key, TransferData>, TransferKey, TransferData> extends HashMap<Key, Data> { private byte[] transferData; public boolean isActivated(Key key) { return containsKey(key) && get(key).isActivated; } public boolean isSupported(Key key) { return containsKey(key) && get(key).isSupported; } public Map<Key, Data> getActiveElements() { HashMap<Key, Data> map = new HashMap<Key, Data>(); for (Entry<Key, Data> entry : entrySet()) { if (entry.getValue().isActivated) { map.put(entry.getKey(), entry.getValue()); } } return map; } protected abstract TransferKey codingKey(Key key); protected abstract Key decodingKey(TransferKey key); public void createTransferData() { LinkedList<Pair<TransferKey, TransferData>> list = new LinkedList<Pair<TransferKey, TransferData>>(); for (Entry<Key, Data> entry : getActiveElements().entrySet()) { TransferKey key = codingKey(entry.getKey()); if (key != null) { list.add( new Pair<TransferKey, TransferData>( key, entry.getValue() != null ? entry.getValue() .getTransferData(entry.getKey()) : null)); } }
transferData = Utils.serialize(list);
2
2023-10-31 21:00:14+00:00
2k
Tamiflu233/DingVideo
dingvideobackend/src/main/java/com/dataispower/dingvideobackend/mapper/UserMapper.java
[ { "identifier": "UserIndexResponse", "path": "dingvideobackend/src/main/java/com/dataispower/dingvideobackend/dto/UserIndexResponse.java", "snippet": "@Data\npublic class UserIndexResponse extends UserResponse{\n private Long id;\n private Integer follows;\n private Integer fans;\n private Integer videoCnts;\n\n// public UserIndexResponse(UserResponse userResponse, Integer id, Integer follows, Integer fans, Integer videoCnts) {\n// super(userResponse); // 调用父类的构造函数\n// // 复制父类的属性\n// this.id = id;\n// this.follows = follows;\n// this.fans = fans;\n// this.videoCnts = videoCnts;\n// }\n}" }, { "identifier": "UserResponse", "path": "dingvideobackend/src/main/java/com/dataispower/dingvideobackend/dto/UserResponse.java", "snippet": "@Data\npublic class UserResponse {\n private Long id;\n private String username;\n\n private String nickname;\n\n private String gender;\n @Email\n private String email;\n\n private String phone;\n\n private String avatar;\n}" }, { "identifier": "User", "path": "dingvideobackend/src/main/java/com/dataispower/dingvideobackend/entity/User.java", "snippet": "@Entity\n@Data\n@Table(name = com.dataispower.dingvideobackend.common.TableColumns.USER)\npublic class User extends CommonEntity implements UserDetails {\n @Id\n @Column(name = USER_ID, unique = true)\n private Long id;\n @Column(name = USERNAME, unique = true)\n private String username;\n @Column(name = NICKNAME)\n private String nickname;\n @Column(name = PHONE)\n private String phone;\n @Column(name = PASSWORD)\n private String password;\n @Column(name = EMAIL)\n private String email;\n @Column(name = AGE)\n private String age;\n @Column(name = FOLLOWS)\n private Long follows;\n @Column(name = GENDER)\n @Enumerated(EnumType.STRING)\n private Gender gender;\n @Column(name = AVATAR, columnDefinition = \"text\")\n private String avatar;\n @OneToMany(mappedBy = \"user\", fetch=FetchType.EAGER)\n @JsonIgnore\n private List<Video> videos;\n\n @Override\n public Collection<? extends GrantedAuthority> getAuthorities() {\n return null;\n }\n\n @Override\n public boolean isAccountNonExpired() {\n return false;\n }\n\n @Override\n public boolean isAccountNonLocked() {\n return false;\n }\n\n @Override\n public boolean isCredentialsNonExpired() {\n return false;\n }\n\n @Override\n public boolean isEnabled() {\n return false;\n }\n}" } ]
import com.dataispower.dingvideobackend.dto.UserIndexResponse; import com.dataispower.dingvideobackend.dto.UserResponse; import com.dataispower.dingvideobackend.entity.User; import org.mapstruct.Mapper; import org.mapstruct.factory.Mappers;
823
package com.dataispower.dingvideobackend.mapper; /** * author:heroding * date:2023/11/1 14:31 * description:用户相关信息类自动转换 **/ @Mapper(componentModel = "spring") public interface UserMapper { UserMapper INSTANCE = Mappers.getMapper(UserMapper.class);
package com.dataispower.dingvideobackend.mapper; /** * author:heroding * date:2023/11/1 14:31 * description:用户相关信息类自动转换 **/ @Mapper(componentModel = "spring") public interface UserMapper { UserMapper INSTANCE = Mappers.getMapper(UserMapper.class);
UserResponse userToUserResponse(User user);
2
2023-10-25 07:16:43+00:00
2k
MiguelPereiraDantas/E-commerce-Java
src/main/java/br/com/fourstore/model/Product.java
[ { "identifier": "CategoryEnum", "path": "src/main/java/br/com/fourstore/enums/CategoryEnum.java", "snippet": "public enum CategoryEnum {\n\tCASUAL(\"RCA\"),\n\tCLASSICA(\"RCL\"),\n\tESPORTIVA(\"RES\"),\n\tSOCIAL(\"RSO\");\n\t\n\tprivate String code;\n\tprivate static final Map<String, CategoryEnum>getCategory = new HashMap<>();\n\t\n\tCategoryEnum(String code) {\n\t\tthis.code = code;\n\t}\n\t\n\tpublic String getCode() {\n\t\treturn code;\n\t}\n\t\n\tstatic {\n\t\tfor(CategoryEnum category: CategoryEnum.values()) {\n\t\t\tgetCategory.put(category.getCode(), category);\n\t\t}\n\t}\n\t\n\tpublic static CategoryEnum getCategoryEnum(String code) {\n\t\treturn getCategory.get(code);\n\t}\n}" }, { "identifier": "ColorEnum", "path": "src/main/java/br/com/fourstore/enums/ColorEnum.java", "snippet": "public enum ColorEnum {\n\tPRETO(1),\n\tBRANCO(2),\n\tAZUL(3),\n\tVERMELHO(4),\n\tAMARELO(5),\n\tVERDE(6),\n\tLARANJA(7),\n\tVIOLETA(8);\n\t\n\tprivate Integer code;\n\tprivate static final Map<Integer, ColorEnum>getColor = new HashMap<>();\n\t\n\tColorEnum(Integer code) {\n\t\tthis.code = code;\n\t}\n\t\n\tpublic Integer getCode() {\n\t\treturn code;\n\t}\n\t\n\tstatic {\n\t\tfor(ColorEnum color: ColorEnum.values()) {\n\t\t\tgetColor.put(color.getCode(), color);\n\t\t}\n\t}\n\t\n\tpublic static ColorEnum getColorEnum(Integer code) {\n\t\treturn getColor.get(code);\n\t}\n}" }, { "identifier": "DepartmentEnum", "path": "src/main/java/br/com/fourstore/enums/DepartmentEnum.java", "snippet": "public enum DepartmentEnum {\n\tMASCULINO(\"MA\"),\n\tFEMININO(\"FE\"),\n\tINFANTIL(\"IN\");\n\t\n\tprivate String code;\n\tprivate static final Map<String, DepartmentEnum>getDepartment = new HashMap<>();\n\t\n\tDepartmentEnum(String code) {\n\t\tthis.code = code;\n\t}\n\t\n\tpublic String getCode() {\n\t\treturn code;\n\t}\n\t\n\tstatic {\n\t\tfor(DepartmentEnum department: DepartmentEnum.values()) {\n\t\t\tgetDepartment.put(department.getCode(), department);\n\t\t}\n\t}\n\t\n\tpublic static DepartmentEnum getDepartmentEnum(String code) {\n\t\treturn getDepartment.get(code);\n\t}\n}" }, { "identifier": "SizeEnum", "path": "src/main/java/br/com/fourstore/enums/SizeEnum.java", "snippet": "public enum SizeEnum {\n\tPP(1),\n\tP(2),\n\tM(3),\n\tG(4),\n\tGG(5),\n\tXGG(6);\n\t\n\tprivate Integer code;\n\tprivate static final Map<Integer, SizeEnum>getSize = new HashMap<>();\n\t\n\tSizeEnum(Integer code) {\n\t\tthis.code = code;\n\t}\n\t\n\tpublic Integer getSize() {\n\t\treturn code;\n\t}\n\t\n\tstatic {\n\t\tfor(SizeEnum size: SizeEnum.values()) {\n\t\t\tgetSize.put(size.getSize(), size);\n\t\t}\n\t}\n\t\n\tpublic static SizeEnum getSizeEnum(Integer code) {\n\t\treturn getSize.get(code);\n\t}\n}" }, { "identifier": "TypeEnum", "path": "src/main/java/br/com/fourstore/enums/TypeEnum.java", "snippet": "public enum TypeEnum {\n\tCAMISA(\"CAM\"),\n\tCAMISETA(\"CAT\"),\n\tCALCA(\"CAL\"),\n\tSHORT(\"SHO\"),\n\tBLUSA(\"BLU\"),\n\tBONE(\"BON\"),\n\tCHAPEU(\"CHA\"),\n\tSAIA(\"SAI\"),\n\tVESTIDO(\"VES\");\n\t\n\tprivate String code;\n\tprivate static final Map<String, TypeEnum>getType = new HashMap<>();\n\t\n\tTypeEnum(String code) {\n\t\tthis.code = code;\n\t}\n\t\n\tpublic String getCode() {\n\t\treturn code;\n\t}\n\t\n\tstatic {\n\t\tfor(TypeEnum type: TypeEnum.values()) {\n\t\t\tgetType.put(type.getCode(), type);\n\t\t}\n\t}\n\t\n\tpublic static TypeEnum getTypeEnum(String code) {\n\t\treturn getType.get(code);\n\t}\n}" } ]
import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; import br.com.fourstore.enums.CategoryEnum; import br.com.fourstore.enums.ColorEnum; import br.com.fourstore.enums.DepartmentEnum; import br.com.fourstore.enums.SizeEnum; import br.com.fourstore.enums.TypeEnum;
1,153
package br.com.fourstore.model; @Document(collection = "inventory") public class Product { @Id private String id; private String sku; private String description; private Integer theAmount; private Double price; private TypeEnum type; private ColorEnum color;
package br.com.fourstore.model; @Document(collection = "inventory") public class Product { @Id private String id; private String sku; private String description; private Integer theAmount; private Double price; private TypeEnum type; private ColorEnum color;
private DepartmentEnum department;
2
2023-10-26 15:48:53+00:00
2k
thinhunan/wonder8-promotion-rule
java/src/main/java/com/github/thinhunan/wonder8/promotion/rule/model/builder/SameRangeRuleBuilder.java
[ { "identifier": "P", "path": "java/src/main/java/com/github/thinhunan/wonder8/promotion/rule/model/P.java", "snippet": "public enum P {\n /**\n * 计算总价\n */\n SUM,\n\n /**\n * 计算有几个类别\n */\n COUNT_CATEGORY,\n\n /**\n * 计算有几种SPU\n */\n COUNT_SPU,\n\n /*\n * 计算有几种SKU\n */\n COUNT_SKU,\n\n /**\n * 计算item的数量\n */\n COUNT,\n\n /**\n * 任一SKU的数量达标\n */\n ONE_SKU_COUNT,\n\n /**\n * 任一SKU的总价达标\n */\n ONE_SKU_SUM,\n\n /**\n * 相邻座位的套商品\n */\n ADJACENT_SEAT;\n\n static String errorMessage = \"expected sum or count or countCate/SPU or oneSKU or oneSKUSum or adjacentSeat\";\n\n @Override\n public String toString() {\n switch (this){\n case SUM:return \"sum\";\n case COUNT:return \"count\";\n case COUNT_CATEGORY:return \"countCate\";\n case COUNT_SPU:return \"countSPU\";\n case COUNT_SKU:return \"countSKU\";\n case ONE_SKU_COUNT:return \"oneSKU\";\n case ONE_SKU_SUM:return \"oneSKUSum\";\n case ADJACENT_SEAT:return \"adjacentSeat\";\n default:\n throw new IllegalStateException(errorMessage);\n }\n }\n\n public static P parseString(String s){\n switch (s){\n case \"sum\":return P.SUM;\n case \"count\": return P.COUNT;\n case \"countSPU\": return P.COUNT_SPU;\n case \"countSKU\": return P.COUNT_SKU;\n case \"countCate\": return P.COUNT_CATEGORY;\n case \"oneSKU\": return P.ONE_SKU_COUNT;\n case \"oneSKUSum\": return P.ONE_SKU_SUM;\n case \"adjacentSeat\": return P.ADJACENT_SEAT;\n default:\n throw new IllegalStateException(errorMessage);\n }\n }\n}" }, { "identifier": "RuleRangeCollection", "path": "java/src/main/java/com/github/thinhunan/wonder8/promotion/rule/model/RuleRangeCollection.java", "snippet": "public class RuleRangeCollection extends ArrayList<RuleRange> {\n\n public RuleRangeCollection addRuleRange(RuleRange range){\n this.add(range);\n return this;\n }\n\n String toRuleString() {\n StringBuilder sb = new StringBuilder(\"[\");\n for (RuleRange r:this) {\n if(r.type == R.ALL){\n return \"$\";\n }else {\n sb.append(\"#\");\n sb.append(r.type.toString());\n sb.append(r.id);\n }\n }\n sb.append(\"]\");\n return sb.toString();\n }\n\n @Override\n public String toString() {\n return this.toRuleString();\n }\n\n public static RuleRangeCollection parseString(String s){\n if(\"$\".equals(s)){\n return new RuleRangeCollection().addRuleRange(new RuleRange(R.ALL,null));\n } else {\n String[] parts = s.replaceAll(\"[\\\\[\\\\]]\",\"\").split(\"#\");\n RuleRangeCollection rules = new RuleRangeCollection();\n for(int i = 1; i < parts.length ; i++){\n RuleRange range = new RuleRange(R.parseString(parts[i].substring(0,1)),\n parts[i].substring(1));\n rules.addRuleRange(range);\n }\n return rules;\n }\n }\n}" }, { "identifier": "SameRangeRule", "path": "java/src/main/java/com/github/thinhunan/wonder8/promotion/rule/model/SameRangeRule.java", "snippet": "public class SameRangeRule extends SimplexRule{\n\n @Override\n public String toString() {\n return String.format(\"%s.%s(%d)\",\"~\", predict,expected);\n }\n}" }, { "identifier": "SameRangePredictPart", "path": "java/src/main/java/com/github/thinhunan/wonder8/promotion/rule/model/builder/part/SameRangePredictPart.java", "snippet": "public class SameRangePredictPart {\n protected SameRangeRuleBuilder _builder;\n public SameRangePredictPart(SameRangeRuleBuilder builder) {\n this._builder = builder;\n }\n\n public SameRangeRuleBuilder expected(int expected) {\n _builder.setExpected(expected);\n return _builder;\n }\n}" } ]
import com.github.thinhunan.wonder8.promotion.rule.model.P; import com.github.thinhunan.wonder8.promotion.rule.model.RuleRangeCollection; import com.github.thinhunan.wonder8.promotion.rule.model.SameRangeRule; import com.github.thinhunan.wonder8.promotion.rule.model.builder.part.SameRangePredictPart;
1,269
package com.github.thinhunan.wonder8.promotion.rule.model.builder; public class SameRangeRuleBuilder extends SingleRuleBuilder{ protected SameRangeRuleBuilder(ConditionBuilder ruleBuilder, RuleRangeCollection refRanges) { super(ruleBuilder); _refRange = refRanges; } RuleRangeCollection _refRange; public RuleRangeCollection getRanges(){ return _refRange; } public SameRangePredictPart predict(P predict){ this.setPredict(predict); return new SameRangePredictPart(this); } @Override
package com.github.thinhunan.wonder8.promotion.rule.model.builder; public class SameRangeRuleBuilder extends SingleRuleBuilder{ protected SameRangeRuleBuilder(ConditionBuilder ruleBuilder, RuleRangeCollection refRanges) { super(ruleBuilder); _refRange = refRanges; } RuleRangeCollection _refRange; public RuleRangeCollection getRanges(){ return _refRange; } public SameRangePredictPart predict(P predict){ this.setPredict(predict); return new SameRangePredictPart(this); } @Override
public SameRangeRule build() {
2
2023-10-28 09:03:45+00:00
2k
Angular2Guy/AIDocumentLibraryChat
backend/src/main/java/ch/xxx/aidoclibchat/adapter/repository/ArtistRepositoryBean.java
[ { "identifier": "Artist", "path": "backend/src/main/java/ch/xxx/aidoclibchat/domain/model/entity/Artist.java", "snippet": "@Entity\npublic class Artist {\n\t@Id\n\tprivate Long id;\n\tprivate String fullName;\n\tprivate String firstName;\n\tprivate String middleName;\n\tprivate String lastName;\n\tprivate String nationality;\n\tprivate String style;\n\tprivate Integer birth;\n\tprivate Integer death;\n\t\n\tpublic Long getId() {\n\t\treturn id;\n\t}\n\tpublic void setId(Long id) {\n\t\tthis.id = id;\n\t}\n\tpublic String getFullName() {\n\t\treturn fullName;\n\t}\n\tpublic void setFullName(String fullName) {\n\t\tthis.fullName = fullName;\n\t}\n\tpublic String getFirstName() {\n\t\treturn firstName;\n\t}\n\tpublic void setFirstName(String firstName) {\n\t\tthis.firstName = firstName;\n\t}\n\tpublic String getMiddleName() {\n\t\treturn middleName;\n\t}\n\tpublic void setMiddleName(String middleName) {\n\t\tthis.middleName = middleName;\n\t}\n\tpublic String getLastName() {\n\t\treturn lastName;\n\t}\n\tpublic void setLastName(String lastName) {\n\t\tthis.lastName = lastName;\n\t}\n\tpublic String getNationality() {\n\t\treturn nationality;\n\t}\n\tpublic void setNationality(String nationality) {\n\t\tthis.nationality = nationality;\n\t}\n\tpublic String getStyle() {\n\t\treturn style;\n\t}\n\tpublic void setStyle(String style) {\n\t\tthis.style = style;\n\t}\n\tpublic Integer getBirth() {\n\t\treturn birth;\n\t}\n\tpublic void setBirth(Integer birth) {\n\t\tthis.birth = birth;\n\t}\n\tpublic Integer getDeath() {\n\t\treturn death;\n\t}\n\tpublic void setDeath(Integer death) {\n\t\tthis.death = death;\n\t}\t\n\t\t\n}" }, { "identifier": "ArtistRepository", "path": "backend/src/main/java/ch/xxx/aidoclibchat/domain/model/entity/ArtistRepository.java", "snippet": "public interface ArtistRepository {\n\tList<Artist> saveAll(Iterable<Artist> entites);\n\tvoid deleteAll();\n}" } ]
import org.springframework.stereotype.Repository; import ch.xxx.aidoclibchat.domain.model.entity.Artist; import ch.xxx.aidoclibchat.domain.model.entity.ArtistRepository; import java.util.List;
765
/** * Copyright 2023 Sven Loesekann Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package ch.xxx.aidoclibchat.adapter.repository; @Repository public class ArtistRepositoryBean implements ArtistRepository { private final JpaArtistRepository jpaAmazonProductRepository; public ArtistRepositoryBean(JpaArtistRepository jpaAmazonProductRepository) { this.jpaAmazonProductRepository = jpaAmazonProductRepository; } @Override
/** * Copyright 2023 Sven Loesekann Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package ch.xxx.aidoclibchat.adapter.repository; @Repository public class ArtistRepositoryBean implements ArtistRepository { private final JpaArtistRepository jpaAmazonProductRepository; public ArtistRepositoryBean(JpaArtistRepository jpaAmazonProductRepository) { this.jpaAmazonProductRepository = jpaAmazonProductRepository; } @Override
public List<Artist> saveAll(Iterable<Artist> entites) {
0
2023-10-25 19:05:07+00:00
2k
Fusion-Flux/Portal-Cubed-Rewrite
src/main/java/io/github/fusionflux/portalcubed/mixin/client/MinecraftMixin.java
[ { "identifier": "DirectClickItem", "path": "src/main/java/io/github/fusionflux/portalcubed/framework/item/DirectClickItem.java", "snippet": "public interface DirectClickItem {\n\t/**\n\t * @return DEFAULT to fall back to vanilla, FALSE to cancel, TRUE to continue to server / cancel\n\t */\n\tTriState onAttack(Level level, Player player, ItemStack stack);\n\n\t/**\n\t * @return DEFAULT to fall back to vanilla, FALSE to cancel, TRUE to continue to server / cancel\n\t */\n\tTriState onUse(Level level, Player player, ItemStack stack, InteractionHand hand);\n}" }, { "identifier": "PortalCubedPackets", "path": "src/main/java/io/github/fusionflux/portalcubed/packet/PortalCubedPackets.java", "snippet": "public class PortalCubedPackets {\n\t// clientbound\n\tpublic static final PacketType<CreatePortalPacket> CREATE_PORTAL = clientbound(\"create_portal\", CreatePortalPacket::new);\n\t// serverbound\n\tpublic static final PacketType<DirectClickItemPacket> DIRECT_CLICK_ITEM = serverbound(\"direct_click_item\", DirectClickItemPacket::new);\n\n\tpublic static void init() {\n\t}\n\n\tprivate static <T extends ClientboundPacket> PacketType<T> clientbound(String name, Function<FriendlyByteBuf, T> factory) {\n\t\tPacketType<T> type = PacketType.create(PortalCubed.id(name), factory);\n\t\tif (MinecraftQuiltLoader.getEnvironmentType() == EnvType.CLIENT) {\n\t\t\tregisterClientReceiver(type);\n\t\t}\n\t\treturn type;\n\t}\n\n\tprivate static <T extends ServerboundPacket> PacketType<T> serverbound(String name, Function<FriendlyByteBuf, T> factory) {\n\t\tPacketType<T> type = PacketType.create(PortalCubed.id(name), factory);\n\t\tServerPlayNetworking.registerGlobalReceiver(type, ServerboundPacket::handle);\n\t\treturn type;\n\t}\n\n\tprivate static <T extends ClientboundPacket> void registerClientReceiver(PacketType<T> type) {\n\t\tClientPlayNetworking.registerGlobalReceiver(type, ClientboundPacket::handle);\n\t}\n\n\tpublic static <T extends FabricPacket> void sendToClient(ServerPlayer player, T packet) {\n\t\tServerPlayNetworking.send(player, packet);\n\t}\n\n\t@ClientOnly\n\tpublic static <T extends FabricPacket> void sendToServer(T packet) {\n\t\tClientPlayNetworking.send(packet);\n\t}\n}" }, { "identifier": "DirectClickItemPacket", "path": "src/main/java/io/github/fusionflux/portalcubed/packet/serverbound/DirectClickItemPacket.java", "snippet": "public class DirectClickItemPacket implements ServerboundPacket {\n\tprivate final boolean attack;\n\tprivate final InteractionHand hand;\n\n\tpublic DirectClickItemPacket(boolean attack, InteractionHand hand) {\n\t\tthis.attack = attack;\n\t\tthis.hand = hand;\n\t}\n\n\tpublic DirectClickItemPacket(FriendlyByteBuf buf) {\n\t\tthis.attack = buf.readBoolean();\n\t\tthis.hand = buf.readEnum(InteractionHand.class);\n\t}\n\n\t@Override\n\tpublic void write(FriendlyByteBuf buf) {\n\t\tbuf.writeBoolean(attack);\n\t\tbuf.writeEnum(hand);\n\t}\n\n\t@Override\n\tpublic PacketType<?> getType() {\n\t\treturn PortalCubedPackets.DIRECT_CLICK_ITEM;\n\t}\n\n\t@Override\n\tpublic void handle(ServerPlayer player, PacketSender responder) {\n\t\tItemStack stack = player.getItemInHand(hand);\n\t\tif (stack.getItem() instanceof DirectClickItem direct) {\n\t\t\tif (this.attack) {\n\t\t\t\tdirect.onAttack(player.level(), player, stack);\n\t\t\t} else {\n\t\t\t\tdirect.onUse(player.level(), player, stack, hand);\n\t\t\t}\n\t\t}\n\t}\n}" } ]
import io.github.fusionflux.portalcubed.framework.item.DirectClickItem; import io.github.fusionflux.portalcubed.packet.PortalCubedPackets; import io.github.fusionflux.portalcubed.packet.serverbound.DirectClickItemPacket; import net.minecraft.client.Minecraft; import net.minecraft.client.multiplayer.ClientLevel; import net.minecraft.client.player.LocalPlayer; import net.minecraft.world.InteractionHand; import net.minecraft.world.item.ItemStack; import org.jetbrains.annotations.Nullable; import org.quiltmc.qsl.base.api.util.TriState; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; 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; import org.spongepowered.asm.mixin.injection.callback.LocalCapture;
1,260
package io.github.fusionflux.portalcubed.mixin.client; @Mixin(Minecraft.class) public class MinecraftMixin { @Shadow @Nullable public ClientLevel level; @Shadow @Nullable public LocalPlayer player; @Inject( method = "startAttack", at = @At( value = "INVOKE", target = "Lnet/minecraft/world/phys/HitResult;getType()Lnet/minecraft/world/phys/HitResult$Type;" ), locals = LocalCapture.CAPTURE_FAILHARD, cancellable = true ) private void onAttack(CallbackInfoReturnable<Boolean> cir, ItemStack stack) { if (stack.getItem() instanceof DirectClickItem direct) { TriState result = direct.onAttack(level, player, stack); if (result != TriState.DEFAULT) { if (result == TriState.TRUE) {
package io.github.fusionflux.portalcubed.mixin.client; @Mixin(Minecraft.class) public class MinecraftMixin { @Shadow @Nullable public ClientLevel level; @Shadow @Nullable public LocalPlayer player; @Inject( method = "startAttack", at = @At( value = "INVOKE", target = "Lnet/minecraft/world/phys/HitResult;getType()Lnet/minecraft/world/phys/HitResult$Type;" ), locals = LocalCapture.CAPTURE_FAILHARD, cancellable = true ) private void onAttack(CallbackInfoReturnable<Boolean> cir, ItemStack stack) { if (stack.getItem() instanceof DirectClickItem direct) { TriState result = direct.onAttack(level, player, stack); if (result != TriState.DEFAULT) { if (result == TriState.TRUE) {
PortalCubedPackets.sendToServer(new DirectClickItemPacket(true, InteractionHand.MAIN_HAND));
2
2023-10-25 05:32:39+00:00
2k
tridium/code-samples
taggingSamples/taggingSamples-rt/srcTest/test/com/tridiumSamples/taggingSamples/tagImpliedFromAnotherTag/BTagImpliedFromAnotherTagTest.java
[ { "identifier": "BCountryRule", "path": "taggingSamples/taggingSamples-rt/src/com/tridiumSamples/taggingSamples/tagImpliedFromAnotherTag/BCountryRule.java", "snippet": "@NiagaraType\npublic class BCountryRule\n extends BTagRule\n{\n//region /*+ ------------ BEGIN BAJA AUTO GENERATED CODE ------------ +*/\n//@formatter:off\n/*@ $com.tridiumSamples.taggingSamples.tagImpliedFromAnotherTag.BCountryRule(2979906276)1.0$ @*/\n/* Generated Wed Oct 04 15:05:59 BST 2023 by Slot-o-Matic (c) Tridium, Inc. 2012-2023 */\n\n //region Type\n\n @Override\n public Type getType() { return TYPE; }\n public static final Type TYPE = Sys.loadType(BCountryRule.class);\n\n //endregion Type\n\n//@formatter:on\n//endregion /*+ ------------ END BAJA AUTO GENERATED CODE -------------- +*/\n\n public BCountryRule()\n {\n setCondition(new BHasTownTagCondition());\n\n getTagList().add(\"countryTag\", new BCountryTag());\n }\n}" }, { "identifier": "BTownTag", "path": "taggingSamples/taggingSamples-rt/src/com/tridiumSamples/taggingSamples/tagImpliedFromAnotherTag/BTownTag.java", "snippet": "@NiagaraType\npublic final class BTownTag\n extends BSimpleTagInfo\n{\n//region /*+ ------------ BEGIN BAJA AUTO GENERATED CODE ------------ +*/\n//@formatter:off\n/*@ $com.tridiumSamples.taggingSamples.tagImpliedFromAnotherTag.BTownTag(2979906276)1.0$ @*/\n/* Generated Wed Oct 04 15:05:59 BST 2023 by Slot-o-Matic (c) Tridium, Inc. 2012-2023 */\n\n //region Type\n\n @Override\n public Type getType() { return TYPE; }\n public static final Type TYPE = Sys.loadType(BTownTag.class);\n\n //endregion Type\n\n//@formatter:on\n//endregion /*+ ------------ END BAJA AUTO GENERATED CODE -------------- +*/\n\n @Override\n public BIDataValue getDefaultValue()\n {\n return BString.make(\"default town\");\n }\n\n public static final String TAG_NAME = \"townTag\";\n}" } ]
import static org.testng.Assert.assertEquals; import javax.baja.data.BIDataValue; import javax.baja.nre.annotations.NiagaraType; import javax.baja.sys.BComponent; import javax.baja.sys.BStation; import javax.baja.sys.BString; import javax.baja.sys.Sys; import javax.baja.sys.Type; import javax.baja.tag.Id; import javax.baja.tagdictionary.BSmartTagDictionary; import javax.baja.tagdictionary.BTagDictionaryService; import javax.baja.util.BServiceContainer; import com.tridiumSamples.taggingSamples.tagImpliedFromAnotherTag.BCountryRule; import com.tridiumSamples.taggingSamples.tagImpliedFromAnotherTag.BTownTag; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import com.tridium.testng.BStationTestBase;
1,079
/* * Copyright 2023 Tridium, Inc. All Rights Reserved. */ package test.com.tridiumSamples.taggingSamples.tagImpliedFromAnotherTag; @NiagaraType public class BTagImpliedFromAnotherTagTest extends BStationTestBase { //region /*+ ------------ BEGIN BAJA AUTO GENERATED CODE ------------ +*/ //@formatter:off /*@ $test.com.tridiumSamples.taggingSamples.tagImpliedFromAnotherTag.BTagImpliedFromAnotherTagTest(2979906276)1.0$ @*/ /* Generated Wed Oct 04 15:05:59 BST 2023 by Slot-o-Matic (c) Tridium, Inc. 2012-2023 */ //region Type @Override public Type getType() { return TYPE; } public static final Type TYPE = Sys.loadType(BTagImpliedFromAnotherTagTest.class); //endregion Type //@formatter:on //endregion /*+ ------------ END BAJA AUTO GENERATED CODE -------------- +*/ @Override protected void configureTestStation(BStation station, String stationName, int webPort, int foxPort) throws Exception { super.configureTestStation(station, stationName, webPort, foxPort); BServiceContainer services = station.getServices(); BTagDictionaryService tagDictionaryService = (BTagDictionaryService) services.get("TagDictionaryService"); if (tagDictionaryService == null) { tagDictionaryService = new BTagDictionaryService(); } BSmartTagDictionary smartDictionary = new BSmartTagDictionary(DICTIONARY_NAMESPACE);
/* * Copyright 2023 Tridium, Inc. All Rights Reserved. */ package test.com.tridiumSamples.taggingSamples.tagImpliedFromAnotherTag; @NiagaraType public class BTagImpliedFromAnotherTagTest extends BStationTestBase { //region /*+ ------------ BEGIN BAJA AUTO GENERATED CODE ------------ +*/ //@formatter:off /*@ $test.com.tridiumSamples.taggingSamples.tagImpliedFromAnotherTag.BTagImpliedFromAnotherTagTest(2979906276)1.0$ @*/ /* Generated Wed Oct 04 15:05:59 BST 2023 by Slot-o-Matic (c) Tridium, Inc. 2012-2023 */ //region Type @Override public Type getType() { return TYPE; } public static final Type TYPE = Sys.loadType(BTagImpliedFromAnotherTagTest.class); //endregion Type //@formatter:on //endregion /*+ ------------ END BAJA AUTO GENERATED CODE -------------- +*/ @Override protected void configureTestStation(BStation station, String stationName, int webPort, int foxPort) throws Exception { super.configureTestStation(station, stationName, webPort, foxPort); BServiceContainer services = station.getServices(); BTagDictionaryService tagDictionaryService = (BTagDictionaryService) services.get("TagDictionaryService"); if (tagDictionaryService == null) { tagDictionaryService = new BTagDictionaryService(); } BSmartTagDictionary smartDictionary = new BSmartTagDictionary(DICTIONARY_NAMESPACE);
smartDictionary.getTagDefinitions().add(BTownTag.TAG_NAME, new BTownTag());
1
2023-10-30 15:25:35+00:00
2k
RomySaputraSihananda/alquranapi
src/main/java/org/alquranapi/controller/AlquranController.java
[ { "identifier": "SuratDTO", "path": "src/main/java/org/alquranapi/model/DTO/SuratDTO.java", "snippet": "@Data\n@NoArgsConstructor\n@EqualsAndHashCode(callSuper = true)\npublic class SuratDTO extends SuratPrevNextDTO {\n private String tempatTurun;\n private String arti;\n private String deskripsi;\n private Map<String, String> audioFull;\n\n public SuratDTO(SuratDAO suratDAO) {\n super(suratDAO);\n this.tempatTurun = suratDAO.getTempatTurun();\n this.arti = suratDAO.getArti();\n this.deskripsi = suratDAO.getDeskripsi();\n this.audioFull = suratDAO.getAudioFull();\n }\n}" }, { "identifier": "SuratDetailDTO", "path": "src/main/java/org/alquranapi/model/DTO/SuratDetailDTO.java", "snippet": "@Data\n@EqualsAndHashCode(callSuper = true)\n@NoArgsConstructor\npublic class SuratDetailDTO extends SuratDTO {\n private ArrayList<AyatDTO> ayat;\n private SuratPrevNextDTO suratSelanjutnya;\n private SuratPrevNextDTO suratSebelumnya;\n\n public SuratDetailDTO(SuratDAO suratDAO) {\n super(suratDAO);\n this.ayat = suratDAO.getAyat();\n this.suratSelanjutnya = suratDAO.getSuratSelanjutnya();\n this.suratSebelumnya = suratDAO.getSuratSebelumnya();\n }\n}" }, { "identifier": "SuratPrevNextDTO", "path": "src/main/java/org/alquranapi/model/DTO/SuratPrevNextDTO.java", "snippet": "@Data\n@NoArgsConstructor\npublic class SuratPrevNextDTO {\n private int nomor;\n private String nama;\n private String namaLatin;\n private int jumlahAyat;\n\n public SuratPrevNextDTO(SuratDAO surat) {\n this.nomor = surat.getNomor();\n this.nama = surat.getNama();\n this.namaLatin = surat.getNamaLatin();\n this.jumlahAyat = surat.getJumlahAyat();\n }\n}" }, { "identifier": "SuratTafsirDTO", "path": "src/main/java/org/alquranapi/model/DTO/SuratTafsirDTO.java", "snippet": "@Data\n@EqualsAndHashCode(callSuper = true)\n@NoArgsConstructor\npublic class SuratTafsirDTO extends SuratDTO {\n private ArrayList<TafsirDTO> tafsir;\n private SuratPrevNextDTO suratSelanjutnya;\n private SuratPrevNextDTO suratSebelumnya;\n\n public SuratTafsirDTO(SuratDAO suratDAO) {\n super(suratDAO);\n this.tafsir = suratDAO.getTafsir();\n this.suratSelanjutnya = suratDAO.getSuratSelanjutnya();\n this.suratSebelumnya = suratDAO.getSuratSebelumnya();\n }\n}" }, { "identifier": "AlquranService", "path": "src/main/java/org/alquranapi/service/AlquranService.java", "snippet": "@Service\npublic class AlquranService {\n @Autowired\n private ElasticsearchClient client;\n\n @Value(\"${service.elastic.index}\")\n private String index;\n\n public ArrayList<ElasticHit<SuratDTO>> getAll() throws IOException {\n SearchResponse<SuratDAO> response = this.client.search(search -> search.index(this.index).size(114),\n SuratDAO.class);\n\n return new ArrayList<>(response.hits().hits().stream()\n .map(surat -> new ElasticHit<SuratDTO>(surat.id(), surat.index(),\n new SuratDTO(surat.source())))\n .collect(Collectors.toList()));\n }\n\n public ArrayList<ElasticHit<SuratDetailDTO>> getDetail(int nomor) throws IOException {\n GetResponse<SuratDAO> response = this.client.get(\n get -> get.index(this.index).id(Integer.toString(nomor)),\n SuratDAO.class);\n if (!response.found())\n throw new AlquranException(\"surat not found\");\n\n return new ArrayList<>(List.of(new ElasticHit<SuratDetailDTO>(response.id(), response.index(),\n new SuratDetailDTO(response.source()))));\n }\n\n public ArrayList<ElasticHit<SuratTafsirDTO>> getTafsir(int nomor) throws IOException {\n GetResponse<SuratDAO> response = this.client.get(\n get -> get.index(this.index).id(Integer.toString(nomor)),\n SuratDAO.class);\n if (!response.found())\n throw new AlquranException(\"surat not found\");\n\n return new ArrayList<>(List.of(\n new ElasticHit<SuratTafsirDTO>(response.id(), response.index(),\n new SuratTafsirDTO(response.source()))));\n }\n\n public ArrayList<ElasticHit<SuratPrevNextDTO>> searchByName(String value) throws IOException {\n return this.search(\"namaLatin\", value);\n }\n\n public ArrayList<ElasticHit<SuratPrevNextDTO>> searchByTempatTurun(String value) throws IOException {\n return this.search(\"tempatTurun\", value);\n }\n\n private ArrayList<ElasticHit<SuratPrevNextDTO>> search(String field, String value) throws IOException {\n SearchResponse<SuratDAO> response = this.client.search(search -> search\n .index(this.index)\n .query(query -> query\n .bool(bool -> bool\n .must(must -> must\n .match(match -> match\n .field(field)\n .query(value)))))\n .size(114),\n SuratDAO.class);\n\n if (response.hits().maxScore().isNaN())\n throw new AlquranException(\"surat not found\");\n\n return new ArrayList<>(response.hits().hits().stream()\n .map(surat -> new ElasticHit<SuratPrevNextDTO>(surat.id(), surat.index(),\n new SuratPrevNextDTO(surat.source())))\n .collect(Collectors.toList()));\n }\n}" } ]
import java.io.IOException; import org.alquranapi.model.DTO.SuratDTO; import org.alquranapi.model.DTO.SuratDetailDTO; import org.alquranapi.model.DTO.SuratPrevNextDTO; import org.alquranapi.model.DTO.SuratTafsirDTO; import org.alquranapi.payload.hit.ElasticHit; import org.alquranapi.payload.response.BodyResponse; import org.alquranapi.service.AlquranService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; 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 io.swagger.v3.oas.annotations.Operation;
1,562
package org.alquranapi.controller; @RestController @RequestMapping("/api/v1/alquran") public class AlquranController { @Autowired
package org.alquranapi.controller; @RestController @RequestMapping("/api/v1/alquran") public class AlquranController { @Autowired
private AlquranService alquranService;
4
2023-10-28 13:09:26+00:00
2k
iagoroque/Kiwii
src/main/java/com/uu/kiwii/controller/HomeController.java
[ { "identifier": "Link", "path": "src/main/java/com/uu/kiwii/model/Link.java", "snippet": "@Entity\n@Data\n@NoArgsConstructor\n@AllArgsConstructor\npublic class Link {\n\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private Long id;\n\n private String url;\n\n @ManyToOne\n @JoinColumn(name = \"rm_id\")\n private Rm rm;\n\n @ManyToOne\n @JoinColumn(name = \"subject_id\")\n private Subject subject;\n\n}" }, { "identifier": "LinkService", "path": "src/main/java/com/uu/kiwii/service/LinkService.java", "snippet": "@Service\npublic class LinkService {\n\n @Autowired\n LinkRepository linkRepository;\n\n @Autowired\n SubjectRepository subjectRepository;\n\n public List<Link> findAll() {\n return linkRepository.findAll();\n }\n\n public List<Link> findAllById(String subject_id) {\n return linkRepository.findAllById(subject_id);\n }\n\n @Transactional\n public void save(String url, String rm, String subject) {\n linkRepository.save(url, rm, subject);\n }\n\n public boolean verifyUrl(String url) {\n try {\n new URL(url).toURI();\n } catch (MalformedURLException | URISyntaxException e) {\n return false;\n }\n \n try {\n Document document = Jsoup.connect(url).get();\n } catch (IOException | IllegalArgumentException e) {\n return false;\n }\n System.out.println(url);\n return true;\n }\n\n public boolean findByUrl(String rm, String url) {\n return linkRepository.findByUrl(rm, url);\n }\n\n public void deleteById(Long id) {\n linkRepository.deleteById(id);\n }\n\n public boolean isOwner(String currentRm, String subjectId, String linkRm) {\n if (currentRm.startsWith(\"1000\") && subjectRepository.verifyRmInSubject(currentRm, subjectId)\n || currentRm.equals(linkRm)) {\n return true;\n }\n\n return false;\n }\n\n}" }, { "identifier": "RmService", "path": "src/main/java/com/uu/kiwii/service/RmService.java", "snippet": "@Service\npublic class RmService {\n \n @Autowired\n private RmRepository rmRepository;\n\n public boolean verifyRm(String rm){\n return rmRepository.verifyRm(rm);\n }\n\n public Rm findById(String rm){\n return rmRepository.findById(rm).get();\n }\n}" }, { "identifier": "SubjectService", "path": "src/main/java/com/uu/kiwii/service/SubjectService.java", "snippet": "@Service\npublic class SubjectService {\n \n @Autowired\n private SubjectRepository subjectRepository;\n\n public void save(Subject subject) {\n subjectRepository.save(subject);\n }\n\n public Subject findById(String id) {\n Optional<Subject> optionalSubject = subjectRepository.findById(id);\n if (optionalSubject.isPresent()) {\n return optionalSubject.get();\n }\n return null;\n }\n\n public List<Subject> findAll(){\n return subjectRepository.findAll();\n }\n\n public boolean verifyRmInSubject(String currentRm, String subjectId) {\n return subjectRepository.verifyRmInSubject(currentRm, subjectId);\n }\n}" } ]
import java.util.ArrayList; import java.util.List; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; 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.RequestParam; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import com.uu.kiwii.dto.Scrap; import com.uu.kiwii.model.Link; import com.uu.kiwii.service.LinkService; import com.uu.kiwii.service.RmService; import com.uu.kiwii.service.SubjectService; import jakarta.servlet.http.HttpSession;
959
package com.uu.kiwii.controller; @Controller public class HomeController { @Autowired
package com.uu.kiwii.controller; @Controller public class HomeController { @Autowired
private SubjectService subjectService;
3
2023-10-31 18:44:38+00:00
2k
ansforge/SAMU-Hub-Modeles
src/test/java/com/hubsante/model/ValidatorTest.java
[ { "identifier": "ValidationException", "path": "src/main/java/com/hubsante/model/exception/ValidationException.java", "snippet": "public class ValidationException extends Exception {\n public ValidationException(String message) {\n super(message);\n }\n}" }, { "identifier": "getInvalidMessage", "path": "src/main/java/com/hubsante/model/TestMessagesHelper.java", "snippet": "public static String getInvalidMessage(String messagePath) throws IOException {\n String json;\n try (InputStream is = TestMessagesHelper.class.getClassLoader().getResourceAsStream(\"sample/failing/\" + messagePath)) {\n assert is != null;\n json = new String(ByteStreams.toByteArray(is), StandardCharsets.UTF_8);\n }\n return json;\n}" }, { "identifier": "Constants", "path": "src/main/java/com/hubsante/model/config/Constants.java", "snippet": "public class Constants {\n public static final String ENVELOPE_SCHEMA = \"EDXL-DE-envelope-only.schema.json\";\n public static final String ENVELOPE_XSD = \"EDXL-DE-envelope-only.xsd\";\n public static final String FULL_SCHEMA = \"EDXL-DE-full.schema.json\";\n public static final String FULL_XSD = \"EDXL-DE-full.xsd\";\n}" }, { "identifier": "wrapUseCaseMessage", "path": "src/test/java/com/hubsante/model/utils/EdxlWrapperUtils.java", "snippet": "public static String wrapUseCaseMessage(String useCaseMessage) throws JsonProcessingException {\n JsonNode contentMessage = mapper.readTree(useCaseMessage);\n contentMessage = addDistributionElementFields(contentMessage);\n JsonNode envelope = addEnvelope(contentMessage);\n\n return mapper.writeValueAsString(envelope);\n}" }, { "identifier": "getMessageString", "path": "src/test/java/com/hubsante/model/utils/TestFileUtils.java", "snippet": "public static String getMessageString(String schemaName) throws IOException {\n return getMessageString(schemaName, false);\n}" } ]
import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import com.hubsante.model.exception.ValidationException; import lombok.extern.slf4j.Slf4j; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.util.*; import java.util.concurrent.atomic.AtomicBoolean; import static com.hubsante.model.TestMessagesHelper.getInvalidMessage; import static com.hubsante.model.config.Constants.*; import static com.hubsante.model.utils.EdxlWrapperUtils.wrapUseCaseMessage; import static com.hubsante.model.utils.TestFileUtils.getMessageString; import static org.junit.jupiter.api.Assertions.*;
1,053
/** * Copyright © 2023-2024 Agence du Numerique en Sante (ANS) * * 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.hubsante.model; @Slf4j public class ValidatorTest { private static String TOO_MANY_SCHEMAS = "embeddedJsonContent: should be valid to one and only one schema, but"; private static String NO_SCHEMAS = "could not detect any schemas in the message, at least one is required"; private static String MISSING = "is missing but it is required"; static ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); private final Validator validator = new Validator(); private final ObjectMapper mapper = new ObjectMapper().registerModule(new JavaTimeModule()) .enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY) .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) .disable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE); /* * For now we chose to be a little verbose and test each message type separately, * to best identify eventual errors & postpone xsd validation * We could later use an array of UseCases and iterate over it in a single test * It will be relevant when first UseCases will be stable and we will be in an incremental development phase */ @Test @DisplayName("RC-EDA validation passes") public void jsonRcEdaValidationPasses() throws IOException { String input = getMessageString("RC-EDA"); assertDoesNotThrow(() -> validator.validateJSON(input, FULL_SCHEMA)); // TODO bbo: add XML validation } @Test @DisplayName("RC-EDA validation fails") public void jsonRcEdaValidationFails() throws IOException { String input = getMessageString("RC-EDA", false, false);
/** * Copyright © 2023-2024 Agence du Numerique en Sante (ANS) * * 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.hubsante.model; @Slf4j public class ValidatorTest { private static String TOO_MANY_SCHEMAS = "embeddedJsonContent: should be valid to one and only one schema, but"; private static String NO_SCHEMAS = "could not detect any schemas in the message, at least one is required"; private static String MISSING = "is missing but it is required"; static ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); private final Validator validator = new Validator(); private final ObjectMapper mapper = new ObjectMapper().registerModule(new JavaTimeModule()) .enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY) .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) .disable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE); /* * For now we chose to be a little verbose and test each message type separately, * to best identify eventual errors & postpone xsd validation * We could later use an array of UseCases and iterate over it in a single test * It will be relevant when first UseCases will be stable and we will be in an incremental development phase */ @Test @DisplayName("RC-EDA validation passes") public void jsonRcEdaValidationPasses() throws IOException { String input = getMessageString("RC-EDA"); assertDoesNotThrow(() -> validator.validateJSON(input, FULL_SCHEMA)); // TODO bbo: add XML validation } @Test @DisplayName("RC-EDA validation fails") public void jsonRcEdaValidationFails() throws IOException { String input = getMessageString("RC-EDA", false, false);
assertThrows(ValidationException.class, () -> validator.validateJSON(input, FULL_SCHEMA));
0
2023-10-25 14:24:31+00:00
2k
yaroslav318/shop-telegram-bot
telegram-bot/src/main/java/ua/ivanzaitsev/bot/handlers/commands/OrderStepCancelCommandHandler.java
[ { "identifier": "UpdateHandler", "path": "telegram-bot/src/main/java/ua/ivanzaitsev/bot/handlers/UpdateHandler.java", "snippet": "public interface UpdateHandler extends Handler {\n\n boolean canHandleUpdate(Update update);\n\n void handleUpdate(AbsSender absSender, Update update) throws TelegramApiException;\n\n}" }, { "identifier": "Button", "path": "telegram-bot/src/main/java/ua/ivanzaitsev/bot/models/domain/Button.java", "snippet": "public enum Button {\n\n START(\"/start\"),\n CATALOG(\"\\uD83D\\uDCE6 Catalog\"),\n CART(\"\\uD83D\\uDECD Cart\"),\n SEND_PHONE_NUMBER(\"\\uD83D\\uDCF1 Send Phone Number\"),\n ORDER_STEP_NEXT(\"\\u2714\\uFE0F Correct\"),\n ORDER_STEP_PREVIOUS(\"\\u25C0 Back\"),\n ORDER_STEP_CANCEL(\"\\u274C Cancel order\"),\n ORDER_CONFIRM(\"\\u2705 Confirm\");\n\n private final String alias;\n\n Button(String alias) {\n this.alias = alias;\n }\n\n public String getAlias() {\n return alias;\n }\n\n public static ReplyKeyboardMarkup createGeneralMenuKeyboard() {\n ReplyKeyboardMarkup.ReplyKeyboardMarkupBuilder keyboardBuilder = ReplyKeyboardMarkup.builder();\n keyboardBuilder.resizeKeyboard(true);\n keyboardBuilder.selective(true);\n\n keyboardBuilder.keyboardRow(new KeyboardRow(Arrays.asList(\n builder().text(CATALOG.getAlias()).build(),\n builder().text(CART.getAlias()).build()\n )));\n\n return keyboardBuilder.build();\n }\n\n}" }, { "identifier": "Command", "path": "telegram-bot/src/main/java/ua/ivanzaitsev/bot/models/domain/Command.java", "snippet": "public enum Command {\n\n START,\n CATALOG,\n CART,\n ENTER_NAME,\n ENTER_PHONE_NUMBER,\n ENTER_CITY,\n ENTER_ADDRESS,\n ORDER_STEP_CANCEL,\n ORDER_STEP_PREVIOUS,\n ORDER_CONFIRM;\n\n}" }, { "identifier": "ClientActionRepository", "path": "telegram-bot/src/main/java/ua/ivanzaitsev/bot/repositories/ClientActionRepository.java", "snippet": "public interface ClientActionRepository {\n\n ClientAction findByChatId(Long chatId);\n\n void updateByChatId(Long chatId, ClientAction clientAction);\n\n void deleteByChatId(Long chatId);\n\n}" }, { "identifier": "ClientCommandStateRepository", "path": "telegram-bot/src/main/java/ua/ivanzaitsev/bot/repositories/ClientCommandStateRepository.java", "snippet": "public interface ClientCommandStateRepository {\n\n void pushByChatId(Long chatId, Command command);\n\n Command popByChatId(Long chatId);\n\n void deleteAllByChatId(Long chatId);\n\n}" }, { "identifier": "ClientOrderStateRepository", "path": "telegram-bot/src/main/java/ua/ivanzaitsev/bot/repositories/ClientOrderStateRepository.java", "snippet": "public interface ClientOrderStateRepository {\n\n ClientOrder findByChatId(Long chatId);\n\n void updateByChatId(Long chatId, ClientOrder clientOrder);\n\n void deleteByChatId(Long chatId);\n\n}" } ]
import org.telegram.telegrambots.meta.api.methods.send.SendMessage; import org.telegram.telegrambots.meta.api.objects.Update; import org.telegram.telegrambots.meta.bots.AbsSender; import org.telegram.telegrambots.meta.exceptions.TelegramApiException; import ua.ivanzaitsev.bot.handlers.UpdateHandler; import ua.ivanzaitsev.bot.models.domain.Button; import ua.ivanzaitsev.bot.models.domain.Command; import ua.ivanzaitsev.bot.repositories.ClientActionRepository; import ua.ivanzaitsev.bot.repositories.ClientCommandStateRepository; import ua.ivanzaitsev.bot.repositories.ClientOrderStateRepository;
968
package ua.ivanzaitsev.bot.handlers.commands; public class OrderStepCancelCommandHandler implements UpdateHandler { private final ClientActionRepository clientActionRepository; private final ClientCommandStateRepository clientCommandStateRepository; private final ClientOrderStateRepository clientOrderStateRepository; public OrderStepCancelCommandHandler( ClientActionRepository clientActionRepository, ClientCommandStateRepository clientCommandStateRepository, ClientOrderStateRepository clientOrderStateRepository) { this.clientActionRepository = clientActionRepository; this.clientCommandStateRepository = clientCommandStateRepository; this.clientOrderStateRepository = clientOrderStateRepository; } @Override
package ua.ivanzaitsev.bot.handlers.commands; public class OrderStepCancelCommandHandler implements UpdateHandler { private final ClientActionRepository clientActionRepository; private final ClientCommandStateRepository clientCommandStateRepository; private final ClientOrderStateRepository clientOrderStateRepository; public OrderStepCancelCommandHandler( ClientActionRepository clientActionRepository, ClientCommandStateRepository clientCommandStateRepository, ClientOrderStateRepository clientOrderStateRepository) { this.clientActionRepository = clientActionRepository; this.clientCommandStateRepository = clientCommandStateRepository; this.clientOrderStateRepository = clientOrderStateRepository; } @Override
public Command getCommand() {
2
2023-10-29 15:49:41+00:00
2k
MikiP98/HumilityAFM
src/main/java/io/github/mikip98/helpers/PumpkinHelper.java
[ { "identifier": "JustHorizontalFacingBlock", "path": "src/main/java/io/github/mikip98/content/blocks/JustHorizontalFacingBlock.java", "snippet": "public class JustHorizontalFacingBlock extends HorizontalFacingBlock {\n @Override\n protected void appendProperties(StateManager.Builder<Block, BlockState> builder) {\n builder.add(Properties.HORIZONTAL_FACING);\n }\n\n public JustHorizontalFacingBlock(Settings settings) {\n super(settings);\n setDefaultState(getStateManager().getDefaultState()\n .with(Properties.HORIZONTAL_FACING, Direction.SOUTH));\n }\n\n @Override\n public BlockState getPlacementState(ItemPlacementContext ctx) {\n return this.getDefaultState()\n .with(Properties.HORIZONTAL_FACING, ctx.getHorizontalPlayerFacing().getOpposite());\n }\n}" }, { "identifier": "Torch", "path": "src/main/java/io/github/mikip98/helpers/data_types/Torch.java", "snippet": "public class Torch {\n public String type;\n public byte lightLevel;\n\n public Torch(String type, byte lightLevel) {\n this.type = type;\n this.lightLevel = lightLevel;\n }\n}" }, { "identifier": "MOD_ID", "path": "src/main/java/io/github/mikip98/HumilityAFM.java", "snippet": "public static final String MOD_ID = \"humility-afm\";" } ]
import io.github.mikip98.content.blocks.JustHorizontalFacingBlock; import io.github.mikip98.helpers.data_types.Torch; import net.fabricmc.fabric.api.item.v1.FabricItemSettings; import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; import net.minecraft.block.AbstractBlock.Settings; import net.minecraft.block.Block; import net.minecraft.block.Blocks; import net.minecraft.block.HorizontalFacingBlock; import net.minecraft.item.BlockItem; import net.minecraft.item.Item; import net.minecraft.registry.Registries; import net.minecraft.registry.Registry; import net.minecraft.util.Identifier; import static io.github.mikip98.HumilityAFM.MOD_ID;
649
package io.github.mikip98.helpers; public class PumpkinHelper { public PumpkinHelper() { throw new IllegalStateException("Utility class, do not instantiate!\nUse \"init()\" and \"registerPumpkins()\" instead!"); } private static final Torch[] torches = {new Torch("redstone", (byte) 7), new Torch("soul", (byte) 8)}; public static String[] PumpkinsNames = new String[torches.length]; public static Block[] PumpkinsVariants = new Block[torches.length]; public static Item[] PumpkinsItemVariants = new Item[torches.length]; public static void init() { Settings PumpkinSettings = FabricBlockSettings.copy(Blocks.JACK_O_LANTERN); for (int i = 0; i < torches.length; i++) { PumpkinsNames[i] = "jack_o_lantern_" + torches[i].type; int finalI = i; Settings currentSettings = PumpkinSettings.luminance(value -> torches[finalI].lightLevel);
package io.github.mikip98.helpers; public class PumpkinHelper { public PumpkinHelper() { throw new IllegalStateException("Utility class, do not instantiate!\nUse \"init()\" and \"registerPumpkins()\" instead!"); } private static final Torch[] torches = {new Torch("redstone", (byte) 7), new Torch("soul", (byte) 8)}; public static String[] PumpkinsNames = new String[torches.length]; public static Block[] PumpkinsVariants = new Block[torches.length]; public static Item[] PumpkinsItemVariants = new Item[torches.length]; public static void init() { Settings PumpkinSettings = FabricBlockSettings.copy(Blocks.JACK_O_LANTERN); for (int i = 0; i < torches.length; i++) { PumpkinsNames[i] = "jack_o_lantern_" + torches[i].type; int finalI = i; Settings currentSettings = PumpkinSettings.luminance(value -> torches[finalI].lightLevel);
PumpkinsVariants[i] = new JustHorizontalFacingBlock(currentSettings);
0
2023-10-30 12:11:22+00:00
2k
ewkchong/kafkaesque
src/main/java/brokers/DefaultBroker.java
[ { "identifier": "BadPartitionException", "path": "src/main/java/exceptions/BadPartitionException.java", "snippet": "public class BadPartitionException extends Exception {\n public BadPartitionException(String s) {\n super(s);\n }\n}" }, { "identifier": "NoPartitionFound", "path": "src/main/java/exceptions/NoPartitionFound.java", "snippet": "public class NoPartitionFound extends Exception {\n}" }, { "identifier": "Message", "path": "src/main/java/messages/Message.java", "snippet": "public class Message implements Record {\n public int identifier;\n public Topic topic;\n // content is json format\n // Depending on topic, attributes of content will differ\n // might need serializer/deserializer to get driver/rider id\n public String content;\n\n public Message(int identifier, Topic topic, String content) {\n this.identifier = identifier;\n this.topic = topic;\n this.content = content;\n }\n \n\tpublic int length() {\n\t\tint topicLength = topic.toString().getBytes().length;\n\t\treturn 4 + 4 + 4 + topicLength + content.getBytes().length;\n\t}\n\t\n\t/**\n\t * serializes the message into a byte array\n\t * @return the serialized message as a byte array\n\t */\n\tpublic byte[] serialize() {\n\t\ttry {\n\t\t\tbyte[] topicBytes = topic.toString().getBytes();\n\t\t\tint topicLength = topicBytes.length;\n\n\t\t\tbyte[] data = new byte[4 + 4 + 4 + topicLength + content.getBytes().length];\n\n\t\t\t// write length to byte array\n\t\t\tdata[0] = (byte) (length() >> 24);\n\t\t\tdata[1] = (byte) (length() >> 16);\n\t\t\tdata[2] = (byte) (length() >> 8);\n\t\t\tdata[3] = (byte) (length());\n\n\t\t\t// write int indentifier to byte array\n\t\t\tdata[4] = (byte) (identifier >> 24);\n\t\t\tdata[5] = (byte) (identifier >> 16);\n\t\t\tdata[6] = (byte) (identifier >> 8);\n\t\t\tdata[7] = (byte) (identifier);\n\n\t\t\t// write length of topic string to byte array\n\t\t\tdata[8] = (byte) (topicBytes.length >> 24);\n\t\t\tdata[9] = (byte) (topicBytes.length >> 16);\n\t\t\tdata[10] = (byte) (topicBytes.length >> 8);\n\t\t\tdata[11] = (byte) (topicBytes.length);\n\n\t\t\t// write topic string to byte array\n\t\t\tfor (int i = 0; i < topicBytes.length; i++) {\n\t\t\t\tdata[i + 12] = topicBytes[i];\n\t\t\t}\n\n\t\t\t// write the content to byte array\n\t\t\tbyte[] contentBytes = content.getBytes(\"UTF-8\");\n\t\t\tfor (int i = 0; i < contentBytes.length; i++) {\n\t\t\t\tdata[i + 4 + 4 + 4 + topicBytes.length] = contentBytes[i];\n\t\t\t}\n\n\t\t\treturn data;\n\t\t} catch (UnsupportedEncodingException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t\treturn null;\n\t}\n}" }, { "identifier": "CityPartition", "path": "src/main/java/partitions/CityPartition.java", "snippet": "public class CityPartition extends DefaultPartition {\n String city;\n public CityPartition(Topic topic, String city) throws BadPartitionException {\n super(topic);\n if (topic != Topic.RIDER_REQUESTS_RIDE) {\n throw new BadPartitionException(\"topic does not partition by city\");\n }\n this.city = city;\n }\n\n public String getCity() {\n return city;\n }\n @Override\n public boolean equals(Object obj) {\n\n if (!(obj instanceof CityPartition)) {\n return false;\n }\n CityPartition OtherPartition = (CityPartition) obj;\n\n return OtherPartition.city.equals(this.city) && OtherPartition.getTopic() == this.getTopic();\n }\n}" }, { "identifier": "IdPartition", "path": "src/main/java/partitions/IdPartition.java", "snippet": "public class IdPartition extends DefaultPartition {\n int id;\n\n public IdPartition(Topic topic, int id) throws BadPartitionException {\n super(topic);\n if (topic == Topic.RIDER_REQUESTS_RIDE) {\n throw new BadPartitionException(\"topic does not partition by id\");\n }\n this.id = id;\n }\n\n public int getId() {\n return id;\n }\n\n @Override\n public boolean equals(Object obj) {\n\n if (!(obj instanceof IdPartition)) {\n return false;\n }\n IdPartition OtherPartition = (IdPartition) obj;\n\n return OtherPartition.id == this.id && OtherPartition.getTopic() == this.getTopic();\n }\n}" }, { "identifier": "Partition", "path": "src/main/java/partitions/Partition.java", "snippet": "public interface Partition {\n public Topic getTopic();\n public void appendMessage(Message message);\n public Message readMessage(int offset);\n\n}" }, { "identifier": "Service", "path": "src/main/java/types/Service.java", "snippet": "public class Service {\n public String name;\n public int port;\n private int hashCode;\n\n public Service(String name, int port) {\n this.name = name;\n this.port = port;\n this.hashCode = Objects.hash(name, port);\n }\n\n @Override\n public boolean equals(Object obj) {\n\n if (!(obj instanceof Service)) {\n return false;\n }\n Service otherService = (Service) obj;\n\n return otherService.name.equals(this.name) && otherService.port == this.port;\n }\n\n @Override\n public int hashCode() {\n return this.hashCode;\n }\n}" }, { "identifier": "Topic", "path": "src/main/java/types/Topic.java", "snippet": "public enum Topic {\n DRIVER_DATA,\n RIDER_DATA,\n RIDER_REQUESTS_RIDE,\n DRIVER_REQUESTS_RIDE,\n RIDER_ACCEPTS_RIDE\n}" } ]
import exceptions.BadPartitionException; import exceptions.NoPartitionFound; import messages.Message; import org.json.JSONObject; import partitions.CityPartition; import partitions.IdPartition; import partitions.Partition; import types.Service; import types.Topic; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map;
1,592
package brokers; public class DefaultBroker implements Broker { List<Partition> partitions; public static final Map<Service, List<Partition>> brokersToPartitions = new HashMap<>(); public DefaultBroker(String name, int port) { // setup static brokers List<Partition> partitions_1 = new ArrayList<>(); List<Partition> partitions_2 = new ArrayList<>(); List<Partition> partitions_3 = new ArrayList<>(); List<Partition> partitions_4 = new ArrayList<>(); try { // TODO set these to other values. right now only broker "node-1" partitions_1.add(new IdPartition(Topic.DRIVER_DATA,1)); partitions_1.add(new IdPartition(Topic.RIDER_DATA,1));
package brokers; public class DefaultBroker implements Broker { List<Partition> partitions; public static final Map<Service, List<Partition>> brokersToPartitions = new HashMap<>(); public DefaultBroker(String name, int port) { // setup static brokers List<Partition> partitions_1 = new ArrayList<>(); List<Partition> partitions_2 = new ArrayList<>(); List<Partition> partitions_3 = new ArrayList<>(); List<Partition> partitions_4 = new ArrayList<>(); try { // TODO set these to other values. right now only broker "node-1" partitions_1.add(new IdPartition(Topic.DRIVER_DATA,1)); partitions_1.add(new IdPartition(Topic.RIDER_DATA,1));
partitions_1.add(new CityPartition(Topic.RIDER_REQUESTS_RIDE,"Vancouver"));
3
2023-10-30 21:20:16+00:00
2k
admin4j/admin4j-dict
dict-core/src/main/java/com/admin4j/dict/core/impl/DefaultDictProviderManager.java
[ { "identifier": "DictProvider", "path": "dict-core/src/main/java/com/admin4j/dict/core/DictProvider.java", "snippet": "public interface DictProvider extends StringProvider {\n\n /**\n * 根据dictCode获取字典显示值\n *\n * @param strategy 字典策略\n * @param field\n * @param dictType 字典分类\n * @return 获取字典显示值\n */\n String dictLabel(Field field, String dictType, Object dictCode);\n\n /**\n * 批量获取\n *\n * @return key 为dictCode,value 为 dictLabel\n */\n default Map<Object, String> dictLabels(Field field, String dictType, Collection<Object> dictCodes) {\n\n Map<Object, String> dictLabels = new HashMap<>(dictCodes.size());\n for (Object dictCode : dictCodes) {\n dictLabels.computeIfAbsent(dictCode, key -> dictLabel(field, dictType, dictCode));\n }\n return dictLabels;\n }\n\n /**\n * 根据dictLabel获取字典Code\n *\n * @param field\n * @param dictType 字典策略\n * @param dictLabel 字典分类\n * @return 获取字典显示值\n */\n Object dictCode(Field field, String dictType, String dictLabel);\n\n\n}" }, { "identifier": "DictProviderManager", "path": "dict-core/src/main/java/com/admin4j/dict/core/DictProviderManager.java", "snippet": "public interface DictProviderManager {\n\n /**\n * 根据dictCode获取字典显示值\n *\n * @param field 翻译字段\n * @param strategy 字典策略\n * @param dictType 字典分类\n * @return 获取字典显示值\n */\n String dictLabel(Field field, String strategy, String dictType, Object dictCode);\n\n /**\n * 批量获取\n */\n Map<Object, String> dictLabels(Field field, String strategy, String dictType, Collection<Object> dictCodes);\n\n /**\n * 根据dictLabel获取字典Code\n *\n * @param field\n * @param strategy 字典策略\n * @param dictType 字典分类\n * @return 获取字典显示值\n */\n Object dictCode(Field field, String strategy, String dictType, String dictLabel);\n}" } ]
import com.admin4j.dict.core.DictProvider; import com.admin4j.dict.core.DictProviderManager; import com.admin4j.spring.plugin.provider.manager.ProviderManager; import java.lang.reflect.Field; import java.util.Collection; import java.util.Map; import java.util.Objects;
813
package com.admin4j.dict.core.impl; /** * @author andanyang * @since 2022/7/20 14:15 */ public class DefaultDictProviderManager implements DictProviderManager { /** * 根据dictCode获取字典显示值 * * @param field 字段 * @param strategy 字典策略 * @param dictType 字典分类 * @param dictCode 字典code * @return 获取字典显示值 */ @Override public String dictLabel(Field field, String strategy, String dictType, Object dictCode) {
package com.admin4j.dict.core.impl; /** * @author andanyang * @since 2022/7/20 14:15 */ public class DefaultDictProviderManager implements DictProviderManager { /** * 根据dictCode获取字典显示值 * * @param field 字段 * @param strategy 字典策略 * @param dictType 字典分类 * @param dictCode 字典code * @return 获取字典显示值 */ @Override public String dictLabel(Field field, String strategy, String dictType, Object dictCode) {
DictProvider load = ProviderManager.load(DictProvider.class, strategy);
0
2023-10-26 08:36:17+00:00
2k
AzharRivaldi/Cerita-Dongeng
app/src/main/java/com/azhar/dongeng/activities/MainActivity.java
[ { "identifier": "MainAdapter", "path": "app/src/main/java/com/azhar/dongeng/adapter/MainAdapter.java", "snippet": "public class MainAdapter extends RecyclerView.Adapter<MainAdapter.MainViewHolder> implements Filterable {\r\n\r\n private Context context;\r\n private List<ModelMain> modelMainList;\r\n private List<ModelMain> modelMainFilterList;\r\n\r\n @Override\r\n public Filter getFilter() {\r\n return modelFilter;\r\n }\r\n\r\n private Filter modelFilter = new Filter() {\r\n @Override\r\n protected FilterResults performFiltering(CharSequence constraint) {\r\n List<ModelMain> filteredList = new ArrayList<>();\r\n if (constraint == null || constraint.length() == 0) {\r\n filteredList.addAll(modelMainFilterList);\r\n } else {\r\n String filterPattern = constraint.toString().toLowerCase().trim();\r\n for (ModelMain modelMainFilter : modelMainFilterList) {\r\n if (modelMainFilter.getStrJudul().toLowerCase().contains(filterPattern)) {\r\n filteredList.add(modelMainFilter);\r\n }\r\n }\r\n }\r\n FilterResults results = new FilterResults();\r\n results.values = filteredList;\r\n return results;\r\n }\r\n\r\n @Override\r\n protected void publishResults(CharSequence constraint, FilterResults results) {\r\n modelMainList.clear();\r\n modelMainList.addAll((List) results.values);\r\n notifyDataSetChanged();\r\n }\r\n };\r\n\r\n public MainAdapter(Context context, List<ModelMain> modelMain) {\r\n this.context = context;\r\n this.modelMainList = modelMain;\r\n this.modelMainFilterList = new ArrayList<>(modelMain);\r\n }\r\n\r\n @Override\r\n public MainViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {\r\n View view = LayoutInflater.from(parent.getContext())\r\n .inflate(R.layout.list_item_main, parent, false);\r\n return new MainViewHolder(view);\r\n }\r\n\r\n @Override\r\n public void onBindViewHolder(MainViewHolder holder, int position) {\r\n ModelMain item = modelMainList.get(position);\r\n\r\n holder.tvJudul.setText(item.getStrJudul());\r\n\r\n //send data to detail activity\r\n holder.cvDongeng.setOnClickListener(view -> {\r\n Intent intent = new Intent(context, DetailActivity.class);\r\n intent.putExtra(DetailActivity.DETAIL_DONGENG, modelMainList.get(position));\r\n context.startActivity(intent);\r\n });\r\n\r\n }\r\n\r\n @Override\r\n public int getItemCount() {\r\n return modelMainList.size();\r\n }\r\n\r\n public static class MainViewHolder extends RecyclerView.ViewHolder {\r\n\r\n CardView cvDongeng;\r\n TextView tvJudul;\r\n\r\n public MainViewHolder(View itemView) {\r\n super(itemView);\r\n cvDongeng = itemView.findViewById(R.id.cvDongeng);\r\n tvJudul = itemView.findViewById(R.id.tvJudul);\r\n }\r\n }\r\n\r\n}" }, { "identifier": "ModelMain", "path": "app/src/main/java/com/azhar/dongeng/model/ModelMain.java", "snippet": "public class ModelMain implements Serializable {\r\n\r\n String strJudul;\r\n String strCerita;\r\n\r\n public String getStrJudul() {\r\n return strJudul;\r\n }\r\n\r\n public void setStrJudul(String strJudul) {\r\n this.strJudul = strJudul;\r\n }\r\n\r\n public String getStrCerita() {\r\n return strCerita;\r\n }\r\n\r\n public void setStrCerita(String strCerita) {\r\n this.strCerita = strCerita;\r\n }\r\n\r\n public static Comparator<ModelMain> sortByAsc = new Comparator<ModelMain>() {\r\n @Override\r\n public int compare(ModelMain o1, ModelMain o2) {\r\n return o1.strJudul.compareTo(o2.strJudul);\r\n }\r\n };\r\n}\r" } ]
import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.app.Activity; import android.graphics.Color; import android.os.Build; import android.os.Bundle; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.view.inputmethod.EditorInfo; import android.widget.SearchView; import android.widget.Toast; import com.azhar.dongeng.R; import com.azhar.dongeng.adapter.MainAdapter; import com.azhar.dongeng.model.ModelMain; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Collections; import java.util.List;
1,063
package com.azhar.dongeng.activities; public class MainActivity extends AppCompatActivity { List<ModelMain> modelMain = new ArrayList<>();
package com.azhar.dongeng.activities; public class MainActivity extends AppCompatActivity { List<ModelMain> modelMain = new ArrayList<>();
MainAdapter mainAdapter;
0
2023-10-30 03:56:34+00:00
2k
Yellowstrawberrys/Commander
src/main/java/xyz/yellowstrawberry/commander/CommandHandler.java
[ { "identifier": "CommandEvent", "path": "src/main/java/xyz/yellowstrawberry/commander/enums/CommandEvent.java", "snippet": "public enum CommandEvent {\n COMMAND,\n TABCOMPLETE\n}" }, { "identifier": "CommandTarget", "path": "src/main/java/xyz/yellowstrawberry/commander/enums/CommandTarget.java", "snippet": "public enum CommandTarget {\n ALL,\n PLAYER\n}" }, { "identifier": "ParameterConverter", "path": "src/main/java/xyz/yellowstrawberry/commander/utils/ParameterConverter.java", "snippet": "public interface ParameterConverter<T> {\n T convert(String param);\n}" }, { "identifier": "ReturnComputer", "path": "src/main/java/xyz/yellowstrawberry/commander/utils/ReturnComputer.java", "snippet": "public interface ReturnComputer {\n <T> boolean compute(CommandSender sender, T t);\n}" } ]
import net.kyori.adventure.text.Component; import org.bukkit.Location; import org.bukkit.command.CommandSender; import org.bukkit.command.defaults.BukkitCommand; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import xyz.yellowstrawberry.commander.annotations.Command; import xyz.yellowstrawberry.commander.annotations.CommandListener; import xyz.yellowstrawberry.commander.annotations.SubCommand; import xyz.yellowstrawberry.commander.enums.CommandEvent; import xyz.yellowstrawberry.commander.enums.CommandTarget; import xyz.yellowstrawberry.commander.utils.ParameterConverter; import xyz.yellowstrawberry.commander.utils.ReturnComputer; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.*; import java.util.logging.Level; import java.util.logging.Logger;
790
package xyz.yellowstrawberry.commander; public class CommandHandler extends BukkitCommand { private final static Map<Class<?>, ReturnComputer> returnComputers = new HashMap<>(); private final static Map<Class<?>, ParameterConverter<?>> converters = new HashMap<>(); protected static void addReturnComputers(Class<?> target, ReturnComputer returnComputer) { returnComputers.put(target, returnComputer); } protected static void addParameterConverter(Class<?> target, ParameterConverter<?> converter) { converters.put(target, converter); } private final Object o; private final Map<CommandEvent, List<Method>> listeners = new HashMap<>(); private final Map<String, SubCommandHandler> subcommands = new HashMap<>(); public CommandHandler(Command command, Object o) { super(command.value(), command.description(), command.usageMessage(), Arrays.asList(command.aliases())); this.o = o; for(Method method : o.getClass().getDeclaredMethods()) { if(method.isAnnotationPresent(CommandListener.class)) { CommandListener commandListener = method.getAnnotation(CommandListener.class); method.setAccessible(true); if(!listeners.containsKey(commandListener.listeningTo())) listeners.put(commandListener.listeningTo(), new ArrayList<>()); listeners.get(commandListener.listeningTo()).add(method); }else if(method.isAnnotationPresent(SubCommand.class)) { SubCommand subCommand = method.getAnnotation(SubCommand.class); method.setAccessible(true); subcommands.put(subCommand.value(), new SubCommandHandler(subCommand, method, o)); } } } @Override public boolean execute(@NotNull CommandSender sender, @NotNull String commandLabel, @NotNull String[] args) { Object l = null; Class<?> returnType = null; if (args.length >= 1 && subcommands.containsKey(args[0])) { try { l = subcommands.get(args[0]).execute(sender, args); returnType = l!=null?l.getClass():null; } catch (InvocationTargetException | IllegalAccessException e) { throw new RuntimeException(e); } }else if(listeners.containsKey(CommandEvent.COMMAND)) { for (Method m : listeners.get(CommandEvent.COMMAND)) { try {
package xyz.yellowstrawberry.commander; public class CommandHandler extends BukkitCommand { private final static Map<Class<?>, ReturnComputer> returnComputers = new HashMap<>(); private final static Map<Class<?>, ParameterConverter<?>> converters = new HashMap<>(); protected static void addReturnComputers(Class<?> target, ReturnComputer returnComputer) { returnComputers.put(target, returnComputer); } protected static void addParameterConverter(Class<?> target, ParameterConverter<?> converter) { converters.put(target, converter); } private final Object o; private final Map<CommandEvent, List<Method>> listeners = new HashMap<>(); private final Map<String, SubCommandHandler> subcommands = new HashMap<>(); public CommandHandler(Command command, Object o) { super(command.value(), command.description(), command.usageMessage(), Arrays.asList(command.aliases())); this.o = o; for(Method method : o.getClass().getDeclaredMethods()) { if(method.isAnnotationPresent(CommandListener.class)) { CommandListener commandListener = method.getAnnotation(CommandListener.class); method.setAccessible(true); if(!listeners.containsKey(commandListener.listeningTo())) listeners.put(commandListener.listeningTo(), new ArrayList<>()); listeners.get(commandListener.listeningTo()).add(method); }else if(method.isAnnotationPresent(SubCommand.class)) { SubCommand subCommand = method.getAnnotation(SubCommand.class); method.setAccessible(true); subcommands.put(subCommand.value(), new SubCommandHandler(subCommand, method, o)); } } } @Override public boolean execute(@NotNull CommandSender sender, @NotNull String commandLabel, @NotNull String[] args) { Object l = null; Class<?> returnType = null; if (args.length >= 1 && subcommands.containsKey(args[0])) { try { l = subcommands.get(args[0]).execute(sender, args); returnType = l!=null?l.getClass():null; } catch (InvocationTargetException | IllegalAccessException e) { throw new RuntimeException(e); } }else if(listeners.containsKey(CommandEvent.COMMAND)) { for (Method m : listeners.get(CommandEvent.COMMAND)) { try {
if (m.getAnnotation(CommandListener.class).target() == CommandTarget.PLAYER && !(sender instanceof Player))
1
2023-10-28 14:01:23+00:00
2k
sanxiaoshitou/tower-boot
springboot-study-starter/src/main/java/com/hxl/starter/controller/RockerController.java
[ { "identifier": "RocketMsg", "path": "tower-boot-rockermq/src/main/java/com/hxl/rocker/model/RocketMsg.java", "snippet": "@Data\npublic class RocketMsg {\n\n private String key;\n\n private String body;\n}" }, { "identifier": "RocketMessageProducer", "path": "tower-boot-rockermq/src/main/java/com/hxl/rocker/producer/RocketMessageProducer.java", "snippet": "public interface RocketMessageProducer {\n\n /**\n * 普通消息\n *\n * @param topic topic\n * @param tag tag\n * @param rocketMsg 消息体信息\n * @return boolean\n */\n Boolean sendMessage(String topic, String tag, RocketMsg rocketMsg);\n\n /**\n * 顺序消息,指定消费组\n *\n * @param topic topic\n * @param tag tag\n * @param messageGroup 消费组\n * @param rocketMsg 消息体信息\n * @return boolean\n */\n Boolean sendMessage(String topic, String tag, String messageGroup, RocketMsg rocketMsg);\n\n /**\n * 普通延迟消息\n *\n * @param topic topic\n * @param tag tag\n * @param delayTime 延迟时间 单位:秒\n * @param rocketMsg 消息体信息\n * @return boolean\n */\n Boolean sendMessage(String topic, String tag, Long delayTime, RocketMsg rocketMsg);\n\n /**\n * 顺序延迟消息 指定消费组\n * @param topic topic\n * @param tag tag\n * @param messageGroup 消费组\n * @param delayTime 延迟时间 单位:秒\n * @param rocketMsg 消息体信息\n * @return boolean\n */\n Boolean sendMessage(String topic, String tag, String messageGroup, Long delayTime, RocketMsg rocketMsg);\n}" }, { "identifier": "ApiResult", "path": "springboot-study-starter/src/main/java/com/hxl/starter/model/ApiResult.java", "snippet": "@Getter\n@Setter\n@Accessors(chain = true)\npublic class ApiResult<T> {\n\n /*** 响应成功码 */\n private Boolean success;\n private String code;\n private String msg;\n private String traceId;\n private T data;\n\n public static <T> ApiResult<T> success() {\n ApiResult<T> apiResult = new ApiResult<T>();\n apiResult.setCode(\"200\");\n apiResult.setSuccess(true);\n return apiResult;\n }\n\n public static <T> ApiResult<T> success(T data) {\n ApiResult<T> response = success();\n response.setData(data);\n return response;\n }\n}" } ]
import com.hxl.rocker.model.RocketMsg; import com.hxl.rocker.producer.RocketMessageProducer; import com.hxl.starter.model.ApiResult; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.io.InputStream;
839
package com.hxl.starter.controller; /** * @Description TODO * @Author hxl * @Date 2023/11/24 0:24 */ @RestController @RequestMapping("/rocker") public class RockerController { @Autowired private RocketMessageProducer rocketMessageProducer; @GetMapping("/sendMessage") @ApiOperation(value = "sendMessage")
package com.hxl.starter.controller; /** * @Description TODO * @Author hxl * @Date 2023/11/24 0:24 */ @RestController @RequestMapping("/rocker") public class RockerController { @Autowired private RocketMessageProducer rocketMessageProducer; @GetMapping("/sendMessage") @ApiOperation(value = "sendMessage")
public ApiResult<String> sendMessage() {
2
2023-10-30 06:30:41+00:00
2k
lipinskipawel/maelstrom-java
src/main/java/com/github/lipinskipawel/maelstrom/api/framework/Server.java
[ { "identifier": "Event", "path": "src/main/java/com/github/lipinskipawel/maelstrom/api/protocol/Event.java", "snippet": "public final class Event<T extends BaseWorkload> {\n @JsonProperty(\"id\")\n public int id;\n @JsonProperty(\"src\")\n public String src;\n @JsonProperty(\"dest\")\n public String dst;\n @JsonProperty(\"body\")\n public T body;\n\n Event(T body) {\n this.body = body;\n }\n\n private Event(int id, String src, String dest, T body) {\n this.id = id;\n this.src = src;\n this.dst = dest;\n this.body = body;\n }\n\n public static <T extends BaseWorkload> Event<T> createEvent(int id, String src, String dest, T body) {\n return new Event<>(id, src, dest, body);\n }\n\n public <E extends EventType> Event<E> reply(E body) {\n final var response = new Event<>(body);\n response.id = this.id;\n response.src = this.dst;\n response.dst = this.src;\n response.body.inReplyTo = this.body.msgId();\n response.body.msgId = this.body.msgId() + 1;\n return response;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (o == null || getClass() != o.getClass()) return false;\n Event<?> event = (Event<?>) o;\n return id == event.id && Objects.equals(src, event.src) && Objects.equals(dst, event.dst) && Objects.equals(body, event.body);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(id, src, dst, body);\n }\n}" }, { "identifier": "EventType", "path": "src/main/java/com/github/lipinskipawel/maelstrom/api/protocol/EventType.java", "snippet": "public non-sealed class EventType implements BaseWorkload {\n public String type;\n @JsonProperty(\"msg_id\")\n public int msgId;\n @JsonProperty(\"in_reply_to\")\n public int inReplyTo;\n\n public EventType(String type) {\n this.type = type;\n }\n\n @Override\n public int msgId() {\n return msgId;\n }\n\n @Override\n public int inReplyTo() {\n return inReplyTo;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (o == null || getClass() != o.getClass()) return false;\n EventType eventType = (EventType) o;\n return msgId == eventType.msgId && inReplyTo == eventType.inReplyTo && Objects.equals(type, eventType.type);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(type, msgId, inReplyTo);\n }\n}" }, { "identifier": "Quit", "path": "src/main/java/com/github/lipinskipawel/maelstrom/api/protocol/Quit.java", "snippet": "public final class Quit extends EventType implements EchoWorkload, UniqueWorkload, BroadcastWorkload {\n public Quit() {\n super(\"quit\");\n }\n}" }, { "identifier": "createEvent", "path": "src/main/java/com/github/lipinskipawel/maelstrom/api/protocol/Event.java", "snippet": "public static <T extends BaseWorkload> Event<T> createEvent(int id, String src, String dest, T body) {\n return new Event<>(id, src, dest, body);\n}" }, { "identifier": "jsonSupportRegisterCustomTypes", "path": "src/main/java/com/github/lipinskipawel/maelstrom/internal/JsonSupport.java", "snippet": "public static void jsonSupportRegisterCustomTypes(Map<String, Class<? extends EventType>> customTypes) {\n POSSIBLE_TYPES.putAll(customTypes);\n staticMapper = createObjectMapper(POSSIBLE_TYPES);\n}" }, { "identifier": "readEvent", "path": "src/main/java/com/github/lipinskipawel/maelstrom/internal/JsonSupport.java", "snippet": "@SuppressWarnings(\"unchecked\")\npublic static <T extends BaseWorkload> Event<T> readEvent(String event) {\n try {\n return staticMapper.readValue(event, Event.class);\n } catch (JsonProcessingException e) {\n throw new RuntimeException(e);\n }\n}" } ]
import com.github.lipinskipawel.maelstrom.api.protocol.Event; import com.github.lipinskipawel.maelstrom.api.protocol.EventType; import com.github.lipinskipawel.maelstrom.api.protocol.Quit; import java.util.Map; import java.util.Scanner; import static com.github.lipinskipawel.maelstrom.api.protocol.Event.createEvent; import static com.github.lipinskipawel.maelstrom.internal.JsonSupport.jsonSupportRegisterCustomTypes; import static com.github.lipinskipawel.maelstrom.internal.JsonSupport.readEvent;
1,271
package com.github.lipinskipawel.maelstrom.api.framework; public final class Server { private final EventHandler<?> handler; private Server(EventHandler<?> handler, Map<String, Class<? extends EventType>> customTypes) { this.handler = handler; jsonSupportRegisterCustomTypes(customTypes); } public static Server workload(EventHandler<?> workload) { return workloadWithCustomEvent(workload, Map.of()); } public static Server workloadWithCustomEvent(EventHandler<?> workloadHandler, Map<String, Class<? extends EventType>> eventClass) { return new Server(workloadHandler, eventClass); } @SuppressWarnings("unchecked") public void loop() { try (var scanner = new Scanner(System.in)) { final var initEvent = scanner.nextLine();
package com.github.lipinskipawel.maelstrom.api.framework; public final class Server { private final EventHandler<?> handler; private Server(EventHandler<?> handler, Map<String, Class<? extends EventType>> customTypes) { this.handler = handler; jsonSupportRegisterCustomTypes(customTypes); } public static Server workload(EventHandler<?> workload) { return workloadWithCustomEvent(workload, Map.of()); } public static Server workloadWithCustomEvent(EventHandler<?> workloadHandler, Map<String, Class<? extends EventType>> eventClass) { return new Server(workloadHandler, eventClass); } @SuppressWarnings("unchecked") public void loop() { try (var scanner = new Scanner(System.in)) { final var initEvent = scanner.nextLine();
handler.handle(readEvent(initEvent));
5
2023-10-31 17:56:28+00:00
2k
sergei-nazarov/friend-s_letter
src/main/java/com/example/friendsletter/services/CustomUserDetailsService.java
[ { "identifier": "Role", "path": "src/main/java/com/example/friendsletter/data/Role.java", "snippet": "@Setter\n@Getter\n@NoArgsConstructor\n@AllArgsConstructor\n@Entity\n@Table(name = \"roles\")\npublic class Role {\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private Long id;\n\n @Column(nullable = false, unique = true)\n private String name;\n\n}" }, { "identifier": "User", "path": "src/main/java/com/example/friendsletter/data/User.java", "snippet": "@Getter\n@Setter\n@NoArgsConstructor\n@AllArgsConstructor\n@Entity\n@Table(name = \"users\")\n@ToString\npublic class User implements UserDetails {\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private Long id;\n\n @Column(nullable = false)\n private String username;\n\n @Column(nullable = false, unique = true)\n private String email;\n\n @Column(nullable = false)\n private String password;\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\n @OneToMany\n @JoinTable(\n name = \"users_letters\",\n joinColumns = {@JoinColumn(name = \"USER_ID\", referencedColumnName = \"ID\")},\n inverseJoinColumns = {@JoinColumn(name = \"LETTER_SHORT_CODE\", referencedColumnName = \"letterShortCode\")})\n @ToString.Exclude\n @Transient\n List<LetterMetadata> letters;\n\n @Override\n public Collection<? extends GrantedAuthority> getAuthorities() {\n return roles.stream()\n .map(role -> new SimpleGrantedAuthority(role.getName()))\n .collect(Collectors.toList());\n }\n\n @Override\n public boolean isAccountNonExpired() {\n return true;\n }\n\n @Override\n public boolean isAccountNonLocked() {\n return true;\n }\n\n @Override\n public boolean isCredentialsNonExpired() {\n return true;\n }\n\n @Override\n public boolean isEnabled() {\n return true;\n }\n\n public UserDto toUserDto() {\n return new UserDto(username, null, email);\n }\n}" }, { "identifier": "UserDto", "path": "src/main/java/com/example/friendsletter/data/UserDto.java", "snippet": "@Getter\n@Setter\n@NoArgsConstructor\n@AllArgsConstructor\n@ToString\npublic class UserDto {\n\n @NotNull(message = \"{registration.error.not_empty_username}\")\n @NotEmpty(message = \"{registration.error.not_empty_username}\")\n @Pattern(regexp = \"^(?=[a-zA-Z0-9._]{2,40}$)(?!.*[_.]{2})[^_.].*[^_.]$\",\n message = \"{registration.error.username_error}\")\n private String username;\n private String password;\n @NotNull(message = \"{registration.error.not_empty_email}\")\n @NotEmpty(message = \"{registration.error.not_empty_email}\")\n @Email(message = \"{registration.error.email_incorrect}\")\n private String email;\n\n}" }, { "identifier": "USER_ERRORS", "path": "src/main/java/com/example/friendsletter/errors/USER_ERRORS.java", "snippet": "public enum USER_ERRORS {\n EMAIL_ALREADY_REGISTERED,\n USERNAME_ALREADY_REGISTERED,\n USER_NOT_FOUND\n\n\n}" }, { "identifier": "UserErrorHolder", "path": "src/main/java/com/example/friendsletter/errors/UserErrorHolder.java", "snippet": "@AllArgsConstructor\n@Getter\n@ToString\npublic class UserErrorHolder {\n private USER_ERRORS error;\n private String usernameOrEmail;\n}" }, { "identifier": "UserUpdateException", "path": "src/main/java/com/example/friendsletter/errors/UserUpdateException.java", "snippet": "public class UserUpdateException extends Exception {\n\n List<UserErrorHolder> userErrors;\n\n public UserUpdateException(List<UserErrorHolder> userErrors) {\n this.userErrors = userErrors;\n }\n\n public List<UserErrorHolder> getUserErrors() {\n return userErrors;\n }\n}" }, { "identifier": "RoleRepository", "path": "src/main/java/com/example/friendsletter/repository/RoleRepository.java", "snippet": "public interface RoleRepository extends JpaRepository<Role, Long> {\n\n Role findByName(String name);\n}" }, { "identifier": "UserRepository", "path": "src/main/java/com/example/friendsletter/repository/UserRepository.java", "snippet": "public interface UserRepository extends JpaRepository<User, Long> {\n\n User findByEmail(String email);\n\n User findByUsername(String username);\n\n User findFirstByUsernameOrEmail(String username, String email);\n\n}" } ]
import com.example.friendsletter.data.Role; import com.example.friendsletter.data.User; import com.example.friendsletter.data.UserDto; import com.example.friendsletter.errors.USER_ERRORS; import com.example.friendsletter.errors.UserErrorHolder; import com.example.friendsletter.errors.UserUpdateException; import com.example.friendsletter.repository.RoleRepository; import com.example.friendsletter.repository.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.stream.Collectors;
1,240
package com.example.friendsletter.services; @Service public class CustomUserDetailsService implements UserDetailsService, IUserService { private final UserRepository userRepository;
package com.example.friendsletter.services; @Service public class CustomUserDetailsService implements UserDetailsService, IUserService { private final UserRepository userRepository;
private final RoleRepository roleRepository;
6
2023-10-31 09:53:27+00:00
2k
USSEndeavour/MultithreadedHarborSimulator
src/port/concurrent/DockClient.java
[ { "identifier": "AbstractDock", "path": "src/port/models/AbstractDock.java", "snippet": "public abstract class AbstractDock {\n private volatile boolean busy; // indicates if the dock is currently being used\n\n /**\n * Checks if the dock is busy.\n * @return true if the dock is in use, false otherwise.\n */\n public boolean isBusy() {\n return busy;\n }\n\n /**\n * Sets the dock's busy status.\n * @param busy the new busy status to be set.\n */\n public void setBusy(boolean busy) {\n this.busy = busy;\n }\n\n /**\n * An abstract method to be implemented by subclasses to define how a ship is handled\n * when it uses the dock. This method could involve unloading or loading containers,\n * refueling the ship, or any other process relevant to the dock's function.\n *\n * @param ship The ship to be handled at the dock.\n * @throws ContainerUnderflowException If the operation would result in fewer than zero containers.\n * @throws ContainerOverflowException If the operation would exceed the maximum number of containers.\n */\n public abstract void using(Ship ship) throws ContainerUnderflowException, ContainerOverflowException;\n}" }, { "identifier": "Ship", "path": "src/port/models/Ship.java", "snippet": "public class Ship {\n private int id; // Unique identifier for the ship\n private final int MAX_CAPACITY = 5; // Maximum number of containers the ship can carry\n private int currentCapacity; // Current number of containers on the ship\n\n /**\n * Constructor for creating a new Ship.\n * @param id the unique identifier for the ship\n * @param currentCapacity the initial number of containers on the ship\n */\n public Ship(int id, int currentCapacity) {\n this.id = id;\n this.currentCapacity = currentCapacity;\n }\n\n /**\n * Gets the unique identifier of the ship.\n * @return the ship's ID\n */\n public int getId() {\n return id;\n }\n\n /**\n * Gets the current number of containers on the ship.\n * @return the current capacity of the ship\n */\n public int getCurrentCapacity() {\n return currentCapacity;\n }\n\n /**\n * Gets the maximum capacity of containers that the ship can carry.\n * @return the maximum capacity of the ship\n */\n public int getMAX_CAPACITY() {\n return MAX_CAPACITY;\n }\n\n /**\n * Loads a single container onto the ship.\n * @throws ContainerOverflowException if the ship is already at maximum capacity\n */\n public void loadContainer() throws ContainerOverflowException {\n if (currentCapacity >= MAX_CAPACITY)\n throw new ContainerOverflowException(\"the Ship#\" + id +\n \" is fully loaded: MAX_CAPACITY = \" + MAX_CAPACITY);\n\n this.currentCapacity += 1;\n }\n\n /**\n * Unloads a single container from the ship.\n * @throws ContainerUnderflowException if the ship has no containers to unload\n */\n public void unloadContainer() throws ContainerUnderflowException {\n if (currentCapacity <= 0)\n throw new ContainerUnderflowException(\"the Ship#\" + id + \" has no containers.\");\n\n this.currentCapacity -= 1;\n }\n\n /**\n * Unloads all containers from the ship.\n * @throws ContainerUnderflowException if the ship has no containers to unload\n */\n public void unloadShip() throws ContainerUnderflowException {\n if (currentCapacity <= 0)\n throw new ContainerUnderflowException(\"the Ship#\" + id + \" has no containers.\");\n this.currentCapacity = 0;\n }\n\n /**\n * Provides a string representation of the ship and its current container capacity.\n * @return a string detailing the ship's ID and its current number of containers\n */\n public String toString() {\n return \"Ship #\" + id + \" has \" + currentCapacity + \" containers\";\n }\n}" } ]
import java.util.Random; import port.models.AbstractDock; import port.models.Ship;
999
package port.concurrent; public class DockClient implements Runnable { private int id; private DockPool<AbstractDock> pool; // Dock pool from which this client will request docks.
package port.concurrent; public class DockClient implements Runnable { private int id; private DockPool<AbstractDock> pool; // Dock pool from which this client will request docks.
Ship ship;
1
2023-10-27 12:56:39+00:00
2k
HeitorLouzeiro/gerenciador-disciplinas-java
core/src/main/java/com/project/Dao/SecretarioDAO.java
[ { "identifier": "DataBase", "path": "core/src/main/java/com/project/DataBase/DataBase.java", "snippet": "public class DataBase {\n // Variável para armazenar a conexão com o banco de dados.\n private Connection connection = null;\n\n // Variável para armazenar a instância do banco de dados.\n private static DataBase INSTANCE = null;\n\n /**\n * Construtor privado da classe DataBase. Inicia a conexão com o banco de dados e executa uma instrução SQL.\n *\n * @throws IOException Se ocorrer um erro de leitura durante o carregamento do arquivo SQL.\n */\n private DataBase() throws IOException {\n try {\n // Estabelece uma conexão com o banco de dados e armazena em uma variavel.\n connection = DriverManager.getConnection(\"jdbc:sqlite:core/sample.db\");\n\n // Cria uma instrução SQL que será executada.\n Statement statement = connection.createStatement();\n \n statement.setQueryTimeout(30); // Tempo limite de 30 segundos.\n\n // Ler o arquivo de texto e armazena em uma variável.\n String sql = FileUltils.loadTextFile(\"core/src/main/java/com/project/Resource/Description.sql\");\n\n // Executa a instrução SQL.\n statement.executeUpdate(sql);\n\n } catch (SQLException e) {\n // Em caso de erro, imprime o erro no console.\n System.err.println(\"Error connecting to the database\");\n e.printStackTrace();\n }\n }\n\n \n /**\n * Obtém a conexão com o banco de dados.\n *\n * @return A conexão com o banco de dados.\n */\n public Connection getConnection() {\n // Permite que outras classes acessem a conexão com o banco de dados.\n return this.connection;\n }\n\n /**\n * Fecha a conexão com o banco de dados.\n */\n\n // Permite que outras classes fechem a conexão com o banco de dados.\n public void closeConnection() {\n try {\n if (connection != null)\n connection.close();\n } catch (SQLException e) {\n System.err.println(\"Error closing database connection\");\n e.printStackTrace();\n }\n }\n /**\n * Obtém a instância da classe DataBase. Implementa o padrão Singleton.\n *\n * Esse padrão garante que apenas uma instância da classe DataBase seja criada durante a execução do programa.\n * \n * @return A instância única da classe DataBase.\n * @throws IOException Se ocorrer um erro de leitura durante o carregamento do arquivo SQL.\n */\n // Permite que outras classes acessem a instância do banco de dados.\n public static DataBase getInstance() throws IOException {\n // Se a instância for nula, cria uma nova instância.\n if (INSTANCE == null) {\n INSTANCE = new DataBase();\n }\n // Retorna a instância.\n return INSTANCE;\n }\n}" }, { "identifier": "Aluno", "path": "core/src/main/java/com/project/Classes/Aluno.java", "snippet": "public class Aluno extends Usuario {\n /**\n * Construtor padrão da classe Aluno.\n \n */\n public Aluno() {\n \n }\n\n // A classe Aluno herda os atributos e métodos da classe Usuario.\n // Não são necessários métodos ou atributos adicionais nesta classe específica.\n}" } ]
import java.io.IOException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import com.project.DataBase.DataBase; import com.project.Classes.Aluno;
1,451
package com.project.Dao; /** * Classe que representa um DAO (Data Access Object) para operações relacionadas aos alunos no sistema. * Estende a funcionalidade da classe IFPIDAO. * * Esta classe fornece métodos para recuperar, inserir, atualizar e deletar informações sobre alunos no banco de dados. * Ela utiliza a classe DataBase para obter uma conexão com o banco de dados. * * @author @HeitorLouzeiro */ public class SecretarioDAO { private Connection connection; /** * Construtor da classe SecretarioDAO. Obtém uma conexão com o banco de dados utilizando a classe DataBase. * * @throws IOException Se ocorrer um erro de leitura durante a obtenção da conexão com o banco de dados. */ public SecretarioDAO() throws IOException { connection = DataBase.getInstance().getConnection(); } /** * Recupera informações sobre os alunos do banco de dados e imprime na saída padrão. * * @throws SQLException Se ocorrer um erro durante a execução da consulta SQL. */ public void getAlunos() throws SQLException { Statement statement = connection.createStatement(); String sql = "SELECT * FROM usuario WHERE tipoUsuario = 'Aluno'"; ResultSet resultSet = statement.executeQuery(sql); while (resultSet.next()) { System.out.println("ID: " + resultSet.getString("codUsuario") + " " + resultSet.getString("nome") + " Usuario:" + resultSet.getString("tipoUsuario")); } statement.close(); } /** * Seleciona um aluno do banco de dados com base no código do usuário. * * @param codUsuario O código do usuário do aluno a ser selecionado. * @throws IOException Se ocorrer um erro de leitura durante a obtenção da conexão com o banco de dados. * @throws SQLException Se ocorrer um erro durante a execução da consulta SQL. */ public void SelectAlunoGetByCod(int codUsuario ) throws IOException, SQLException { System.out.println("Selecionando Aluno..."); PreparedStatement statement = connection.prepareStatement("SELECT * FROM Usuario WHERE codUsuario = ?"); statement.setInt(1, codUsuario); ResultSet resultSet = statement.executeQuery(); while (resultSet.next()) { System.out.println("Nome: " + resultSet.getString("nome") + " Usuario:" + resultSet.getString("tipoUsuario")); } statement.close(); } /** * Insere um novo aluno no banco de dados. * * @param aluno O objeto Aluno a ser inserido no banco de dados. * @throws IOException Se ocorrer um erro de leitura durante a obtenção da conexão com o banco de dados. * @throws SQLException Se ocorrer um erro durante a execução da consulta SQL. */
package com.project.Dao; /** * Classe que representa um DAO (Data Access Object) para operações relacionadas aos alunos no sistema. * Estende a funcionalidade da classe IFPIDAO. * * Esta classe fornece métodos para recuperar, inserir, atualizar e deletar informações sobre alunos no banco de dados. * Ela utiliza a classe DataBase para obter uma conexão com o banco de dados. * * @author @HeitorLouzeiro */ public class SecretarioDAO { private Connection connection; /** * Construtor da classe SecretarioDAO. Obtém uma conexão com o banco de dados utilizando a classe DataBase. * * @throws IOException Se ocorrer um erro de leitura durante a obtenção da conexão com o banco de dados. */ public SecretarioDAO() throws IOException { connection = DataBase.getInstance().getConnection(); } /** * Recupera informações sobre os alunos do banco de dados e imprime na saída padrão. * * @throws SQLException Se ocorrer um erro durante a execução da consulta SQL. */ public void getAlunos() throws SQLException { Statement statement = connection.createStatement(); String sql = "SELECT * FROM usuario WHERE tipoUsuario = 'Aluno'"; ResultSet resultSet = statement.executeQuery(sql); while (resultSet.next()) { System.out.println("ID: " + resultSet.getString("codUsuario") + " " + resultSet.getString("nome") + " Usuario:" + resultSet.getString("tipoUsuario")); } statement.close(); } /** * Seleciona um aluno do banco de dados com base no código do usuário. * * @param codUsuario O código do usuário do aluno a ser selecionado. * @throws IOException Se ocorrer um erro de leitura durante a obtenção da conexão com o banco de dados. * @throws SQLException Se ocorrer um erro durante a execução da consulta SQL. */ public void SelectAlunoGetByCod(int codUsuario ) throws IOException, SQLException { System.out.println("Selecionando Aluno..."); PreparedStatement statement = connection.prepareStatement("SELECT * FROM Usuario WHERE codUsuario = ?"); statement.setInt(1, codUsuario); ResultSet resultSet = statement.executeQuery(); while (resultSet.next()) { System.out.println("Nome: " + resultSet.getString("nome") + " Usuario:" + resultSet.getString("tipoUsuario")); } statement.close(); } /** * Insere um novo aluno no banco de dados. * * @param aluno O objeto Aluno a ser inserido no banco de dados. * @throws IOException Se ocorrer um erro de leitura durante a obtenção da conexão com o banco de dados. * @throws SQLException Se ocorrer um erro durante a execução da consulta SQL. */
public void InsertAluno(Aluno aluno) throws IOException, SQLException {
1
2023-10-30 18:29:39+00:00
2k
naraazi/TerminalChess
src/chess/ChessMatch.java
[ { "identifier": "Board", "path": "src/boardgame/Board.java", "snippet": "public class Board {\n private final Integer rows;\n private final Integer columns;\n private final Piece[][] pieces;\n\n public Board(Integer rows, Integer columns) {\n if (rows < 1 || columns < 1) {\n throw new BoardException(\"Error creating board: there must be at least 1 row and 1 column\");\n }\n\n this.rows = rows;\n this.columns = columns;\n pieces = new Piece[rows][columns];\n }\n\n public Integer getRows() {\n return rows;\n }\n\n\n public Integer getColumns() {\n return columns;\n }\n\n\n public Piece piece(int row, int column) {\n if (!positionExists(row, column)) {\n throw new BoardException(\"Position not on the board\");\n }\n\n return pieces[row][column];\n }\n\n public Piece piece(Position position) {\n if (!positionExists(position)) {\n throw new BoardException(\"Position not on the board\");\n }\n\n return pieces[position.getRow()][position.getColumn()];\n }\n\n public void placePiece(Piece piece, Position position) {\n if (thereIsAPiece(position)) {\n throw new BoardException(\"There is already a piece on position \" + position);\n }\n\n pieces[position.getRow()][position.getColumn()] = piece;\n piece.position = position;\n }\n\n public Piece removePiece(Position position) {\n if (!positionExists(position)) {\n throw new BoardException(\"Position not on the board\");\n }\n\n if (piece(position) == null) {\n return null;\n }\n\n Piece aux = piece(position);\n aux.position = null;\n pieces[position.getRow()][position.getColumn()] = null;\n return aux;\n }\n\n private boolean positionExists(int row, int column) {\n return row >= 0 && row < rows && column >= 0 && column < columns;\n }\n\n public boolean positionExists(Position position) {\n return positionExists(position.getRow(), position.getColumn());\n }\n\n public boolean thereIsAPiece(Position position) {\n if (!positionExists(position)) {\n throw new BoardException(\"Position not on the board\");\n }\n\n return piece(position) != null;\n }\n}" }, { "identifier": "Piece", "path": "src/boardgame/Piece.java", "snippet": "public abstract class Piece {\n protected Position position;\n private final Board board;\n\n public Piece(Board board) {\n this.board = board;\n }\n\n protected Board getBoard() {\n return board;\n }\n\n public abstract boolean[][] possibleMoves();\n\n //template method\n public boolean possibleMove(Position position) {\n return possibleMoves()[position.getRow()][position.getColumn()];\n }\n\n public boolean isThereAnyPossibleMove() {\n boolean[][] mat = possibleMoves();\n\n for (boolean[] booleans : mat) {\n for (int j = 0; j < mat.length; j++) {\n if (booleans[j]) {\n return true;\n }\n }\n }\n\n return false;\n }\n}" }, { "identifier": "Position", "path": "src/boardgame/Position.java", "snippet": "public class Position {\n private Integer row;\n private Integer column;\n\n public Position(Integer row, Integer column) {\n this.row = row;\n this.column = column;\n }\n\n public Integer getRow() {\n return row;\n }\n\n public void setRow(Integer row) {\n this.row = row;\n }\n\n public Integer getColumn() {\n return column;\n }\n\n public void setColumn(Integer column) {\n this.column = column;\n }\n\n public void setValues(int row, int column) {\n this.row = row;\n this.column = column;\n }\n\n @Override\n public String toString() {\n return row + \", \" + column;\n }\n}" } ]
import boardgame.Board; import boardgame.Piece; import boardgame.Position; import chess.pieces.*; import java.util.ArrayList; import java.util.List; import java.util.Objects;
1,016
package chess; public class ChessMatch { private Integer turn; private Color currentPlayer;
package chess; public class ChessMatch { private Integer turn; private Color currentPlayer;
private final Board board;
0
2023-10-26 19:27:08+00:00
2k
llllllxy/tiny-security-boot-starter
src/main/java/org/tinycloud/security/provider/RedisAuthProvider.java
[ { "identifier": "AuthProperties", "path": "src/main/java/org/tinycloud/security/AuthProperties.java", "snippet": "@ConfigurationProperties(prefix = \"tiny-security\")\npublic class AuthProperties {\n\n private String storeType = \"redis\";\n\n private String tokenName = \"token\";\n\n private Integer timeout = 3600;\n\n private String tokenStyle = \"uuid\";\n\n private String tokenPrefix;\n\n private String tableName = \"s_auth_token\";\n\n public String getStoreType() {\n return storeType;\n }\n\n public void setStoreType(String storeType) {\n this.storeType = storeType;\n }\n\n public String getTokenName() {\n return tokenName;\n }\n\n public void setTokenName(String tokenName) {\n this.tokenName = tokenName;\n }\n\n public Integer getTimeout() {\n return timeout;\n }\n\n public void setTimeout(Integer timeout) {\n this.timeout = timeout;\n }\n\n public String getTokenStyle() {\n return tokenStyle;\n }\n\n public void setTokenStyle(String tokenStyle) {\n this.tokenStyle = tokenStyle;\n }\n\n public String getTokenPrefix() {\n return tokenPrefix;\n }\n\n public void setTokenPrefix(String tokenPrefix) {\n this.tokenPrefix = tokenPrefix;\n }\n\n public String getTableName() {\n return tableName;\n }\n\n public void setTableName(String tableName) {\n this.tableName = tableName;\n }\n}" }, { "identifier": "AuthConsts", "path": "src/main/java/org/tinycloud/security/consts/AuthConsts.java", "snippet": "public class AuthConsts {\n\n /**\n * 登录用户 令牌 Redis Key 前缀\n */\n public static final String AUTH_TOKEN_KEY = \"tinysecurity:auth:token:\";\n\n // 无权限访问\n public static int CODE_NO_PERMISSION = 403;\n\n // 未登录或会话已失效\n public static int CODE_UNAUTHORIZED = 401;\n}" }, { "identifier": "TokenGenUtil", "path": "src/main/java/org/tinycloud/security/util/TokenGenUtil.java", "snippet": "public class TokenGenUtil {\n\n final static String TOKEN_STYLE_UUID = \"uuid\";\n\n final static String TOKEN_STYLE_SNOWFLAKE = \"snowflake\";\n\n final static String TOKEN_STYLE_OBJECTID = \"objectid\";\n\n final static String TOKEN_STYLE_RANDOM128 = \"random128\";\n\n final static String TOKEN_STYLE_NANOID = \"nanoid\";\n\n /**\n * 根据参数生存不同风格的token字符串\n *\n * @param tokenStyle token风格\n * @return token字符串\n */\n public static String genTokenStr(String tokenStyle) {\n String token;\n switch (tokenStyle) {\n case TOKEN_STYLE_UUID:\n token = UUID.randomUUID().toString().replace(\"-\", \"\");\n break;\n case TOKEN_STYLE_SNOWFLAKE:\n token = Snowflake.nextId();\n break;\n case TOKEN_STYLE_OBJECTID:\n token = ObjectId.nextId();\n break;\n case TOKEN_STYLE_RANDOM128:\n token = CommonUtil.getRandomString(128);\n break;\n case TOKEN_STYLE_NANOID:\n token = NanoId.INSTANCE.randomNanoId();\n break;\n default:\n token = UUID.randomUUID().toString().replaceAll(\"-\", \"\");\n break;\n }\n return token;\n }\n\n}" } ]
import org.springframework.util.Assert; import org.tinycloud.security.AuthProperties; import org.tinycloud.security.consts.AuthConsts; import org.tinycloud.security.util.TokenGenUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.util.StringUtils; import java.util.Objects; import java.util.Set; import java.util.concurrent.TimeUnit;
1,009
package org.tinycloud.security.provider; /** * 操作token和会话的接口(通过redis实现) * * @author liuxingyu01 * @version 2023-01-06-9:33 **/ public class RedisAuthProvider extends AbstractAuthProvider implements AuthProvider { final static Logger log = LoggerFactory.getLogger(RedisAuthProvider.class); private final StringRedisTemplate redisTemplate;
package org.tinycloud.security.provider; /** * 操作token和会话的接口(通过redis实现) * * @author liuxingyu01 * @version 2023-01-06-9:33 **/ public class RedisAuthProvider extends AbstractAuthProvider implements AuthProvider { final static Logger log = LoggerFactory.getLogger(RedisAuthProvider.class); private final StringRedisTemplate redisTemplate;
private final AuthProperties authProperties;
0
2023-10-26 08:13:08+00:00
2k
n0rb33rt/TwainCards
customer/src/main/java/com/norbert/customer/config/AuthProvider.java
[ { "identifier": "BadRequestException", "path": "customer/src/main/java/com/norbert/customer/exception/BadRequestException.java", "snippet": "public class BadRequestException extends RuntimeException{\n public BadRequestException(String message) {\n super(message);\n }\n}" }, { "identifier": "User", "path": "customer/src/main/java/com/norbert/customer/user/User.java", "snippet": "@AllArgsConstructor\n@NoArgsConstructor\n@Getter\n@Setter\n@Builder\n@EqualsAndHashCode\n@Entity(name = \"User\")\n@Table(\n name = \"\\\"user\\\"\",\n uniqueConstraints = @UniqueConstraint(name = \"unique_email\", columnNames = \"email\")\n)\npublic class User {\n @Id\n @SequenceGenerator(\n name = \"user_id_seq\",\n sequenceName = \"user_id_seq\",\n allocationSize = 1\n )\n @GeneratedValue(\n strategy = GenerationType.SEQUENCE,\n generator = \"user_id_seq\"\n )\n @Column(\n name = \"id\",\n updatable = false,\n columnDefinition = \"BIGINT\"\n )\n private Long id;\n\n @Column(\n name = \"email\",\n length = 319,\n nullable = false,\n columnDefinition = \"VARCHAR(319)\"\n )\n private String email;\n\n @Column(\n name = \"password\",\n columnDefinition = \"VARCHAR(61)\"\n )\n private String password;\n\n @Column(\n name = \"role\",\n nullable = false,\n columnDefinition = \"VARCHAR(8)\"\n )\n @Enumerated(EnumType.STRING)\n private Role role;\n\n @Column(\n name = \"enabled\",\n nullable = false,\n columnDefinition = \"BOOLEAN\"\n )\n private Boolean enabled;\n\n @Column(\n name = \"set_password\",\n nullable = false,\n columnDefinition = \"BOOLEAN\"\n )\n private Boolean setPassword;\n\n @OneToMany(\n orphanRemoval = true,\n cascade = CascadeType.ALL,\n mappedBy = \"user\",\n fetch = FetchType.EAGER\n )\n private List<Deck> decks;\n\n @OneToMany(\n orphanRemoval = true,\n cascade = CascadeType.ALL,\n mappedBy = \"user\"\n )\n private List<JwtToken> jwtTokens;\n\n @Column(\n name = \"subscription_until\",\n columnDefinition = \"TIMESTAMP WITHOUT TIME ZONE\"\n )\n private LocalDateTime subscriptionUntil;\n\n @Column(\n name = \"created_at\",\n updatable = false,\n nullable = false,\n columnDefinition = \"TIMESTAMP WITHOUT TIME ZONE\"\n )\n private LocalDateTime createdAt;\n}" }, { "identifier": "UserService", "path": "customer/src/main/java/com/norbert/customer/user/UserService.java", "snippet": "@Service\n@AllArgsConstructor\npublic class UserService {\n private final UserDAO userDAO;\n private final PasswordEncoder passwordEncoder;\n\n public User findUserByEmail(String email){\n return userDAO.findUserByEmail(email);\n }\n\n public boolean isUserPresent(String email){\n return userDAO.isUserPresent(email);\n }\n\n public void save(User user){\n userDAO.save(user);\n }\n\n public UserDTO getUserProfile(){\n User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();\n UserDTOMapper userDTOMapper = new UserDTOMapper();\n return userDTOMapper.apply(user);\n }\n\n public void updatePassword(PasswordUpdatingRequest request) {\n User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();\n String newHashedPassword = passwordEncoder.encode(request.password());\n user.setPassword(newHashedPassword);\n save(user);\n }\n}" } ]
import com.norbert.customer.exception.BadRequestException; import com.norbert.customer.user.User; import com.norbert.customer.user.UserService; import lombok.AllArgsConstructor; import org.springframework.security.authentication.AuthenticationProvider; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.DisabledException; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Component; import java.util.HashSet; import java.util.Set;
1,091
package com.norbert.customer.config; @Component @AllArgsConstructor public class AuthProvider implements AuthenticationProvider { private final UserService userService; private final PasswordEncoder passwordEncoder; @Override // todo: refactor public Authentication authenticate(Authentication authentication) throws AuthenticationException { String email = (String) authentication.getPrincipal(); String password = (String) authentication.getCredentials();
package com.norbert.customer.config; @Component @AllArgsConstructor public class AuthProvider implements AuthenticationProvider { private final UserService userService; private final PasswordEncoder passwordEncoder; @Override // todo: refactor public Authentication authenticate(Authentication authentication) throws AuthenticationException { String email = (String) authentication.getPrincipal(); String password = (String) authentication.getCredentials();
User user;
1
2023-10-30 19:00:07+00:00
2k
0-Gixty-0/Grupp-11-OOPP
sailinggame/src/test/java/modeltest/gameworld/WorldTest.java
[ { "identifier": "BasicMapGenerator", "path": "sailinggame/src/main/java/com/group11/model/gameworld/BasicMapGenerator.java", "snippet": "public class BasicMapGenerator implements IMapGenerator {\n\n @Override\n /**\n Primarly used for testing purposes as this type of map is no longer used in the game.\n @param mapWidth the width of the map to be generated\n @param mapHeight the height of the map to be generated\n @return a Map object with the specified dimensions\n */\n public Map generateMap(int mapWidth, int mapHeight) {\n\n Integer quarterWidth = mapWidth/4;\n Integer quarterHeight = mapHeight/4;\n\n List<List<ATile>> tileMatrix = new ArrayList<List<ATile>>();\n\n for (int i = 0; i < mapHeight; i++) {\n \n List<ATile> tileRow = new ArrayList<ATile>(); //Create rows\n\n for (int k = 0; k < mapWidth; k++) { \n \n //Creates a square of land in the middle of the matrix with a quarterSide distance to the edge\n if ((k >= quarterWidth) && (k <= mapWidth-quarterWidth) && (i >= quarterHeight) && (i <= mapHeight-quarterHeight)) { //Add landtiles\n tileRow.add(new LandTile(new Point(i,k))); //Should add landtile\n }\n\n else {\n tileRow.add(new SeaTile(new Point(i, k))); //Should add seatile\n }\n }\n tileMatrix.add(tileRow);\n }\n return new Map(tileMatrix, mapWidth, mapHeight);\n }\n}" }, { "identifier": "BasicWorldGenerator", "path": "sailinggame/src/main/java/com/group11/model/gameworld/BasicWorldGenerator.java", "snippet": "public class BasicWorldGenerator implements IWorldGenerator {\n\n IMapGenerator mapGenerator;\n\n /**\n * Constructor for a BasicWorldGenerator\n * @param mapGenerator the map generator to use for generating the world\n */\n public BasicWorldGenerator(IMapGenerator mapGenerator) {\n this.mapGenerator = mapGenerator;\n }\n\n /**\n * Method for generating a World object.\n *\n * @param mapWidth the width of the world.\n * @param mapHeight the height of the world.\n * @return a World object \n */\n @Override\n public World generateWorld(int mapWidth, int mapHeight) {\n\n Map map = this.mapGenerator.generateMap(mapWidth, mapHeight);\n\n return new World(map);\n }\n}" }, { "identifier": "IMapGenerator", "path": "sailinggame/src/main/java/com/group11/model/gameworld/IMapGenerator.java", "snippet": "public interface IMapGenerator {\n\n /**\n * Method for generating a Map object\n * @param mapWidth the width of the map.\n * @param mapHeight the height of the map.\n * @return a Map object \n */\n public Map generateMap(int mapWidth, int mapHeight);\n}" }, { "identifier": "Map", "path": "sailinggame/src/main/java/com/group11/model/gameworld/Map.java", "snippet": "public class Map {\n\n private List<List<ATile>> tileMatrix;\n private int mapWidth;\n private int mapHeight;\n\n public Map(List<List<ATile>> tileMatrix, int mapWidth, int mapHeight) {\n this.tileMatrix = tileMatrix;\n this.mapWidth = mapWidth;\n this.mapHeight = mapHeight;\n }\n\n /**\n * A getter for the area attribute of the Map object.\n * @return (Integer) area of the map\n */\n public int getArea() {\n return mapWidth * mapHeight;\n }\n\n public int getMapWidth() {\n return this.mapWidth;\n }\n\n public int getMapHeight() {\n return this.mapHeight;\n }\n\n /**\n * A getter for the tile at the specified coordinates.\n * @param x the x-coordinate of the tile\n * @param y the y-coordinate of the tile\n * @return the tile at the specified coordinates\n */\n public ATile getTile(int x, int y) {\n return this.tileMatrix.get(y).get(x);\n}\n\n /**\n * A getter for the tileMatrix attribute of the Map object.\n * @return (ArrayList<ArrayList<Tile>>) matrix of Tiles representing the map in the game logic.\n */\n public List<List<ATile>> getTileMatrix() {\n return tileMatrix;\n }\n}" }, { "identifier": "World", "path": "sailinggame/src/main/java/com/group11/model/gameworld/World.java", "snippet": "public class World {\n\n private Map map;\n\n /**\n * Creates a World out of a Map. Constructor is protected because Worlds should only be created by WorldGenerators.\n *\n * @param map the map used in the world\n */\n protected World(Map map) {\n this.map = map;\n }\n\n /**\n * getter for the map attribute\n *\n * @return (Map)\n */\n public Map getMap() {\n return map;\n }\n\n /**\n * setter fot the map attribute\n *\n * @param map\n */\n public void setMap(Map map) {\n this.map = map;\n }\n}" } ]
import org.junit.Test; import com.group11.model.gameworld.BasicMapGenerator; import com.group11.model.gameworld.BasicWorldGenerator; import com.group11.model.gameworld.IMapGenerator; import com.group11.model.gameworld.Map; import com.group11.model.gameworld.World; import static org.junit.Assert.*;
1,363
package modeltest.gameworld; public class WorldTest { @Test public void testGetMap() { IMapGenerator basicMapGenerator = new BasicMapGenerator();
package modeltest.gameworld; public class WorldTest { @Test public void testGetMap() { IMapGenerator basicMapGenerator = new BasicMapGenerator();
World world = (new BasicWorldGenerator(basicMapGenerator)).generateWorld(100,100);
1
2023-10-31 11:40:56+00:00
2k
MattiDragon/JsonPatcher
src/main/java/io/github/mattidragon/jsonpatcher/patch/PatchingContext.java
[ { "identifier": "JsonPatcher", "path": "src/main/java/io/github/mattidragon/jsonpatcher/JsonPatcher.java", "snippet": "public class JsonPatcher implements ModInitializer {\n private static final Set<String> SUPPORTED_VERSIONS = new HashSet<>(Set.of(\"1\"));\n public static final String MOD_ID = \"jsonpatcher\";\n public static final Logger MAIN_LOGGER = LoggerFactory.getLogger(MOD_ID);\n private static final String RELOAD_LOGGER_NAME = \"JsonPatcher Reload\";\n public static final Logger RELOAD_LOGGER = LoggerFactory.getLogger(RELOAD_LOGGER_NAME);\n\n static {\n hackLog4j();\n }\n\n public static Identifier id(String path) {\n return new Identifier(MOD_ID, path);\n }\n\n @Override\n public void onInitialize() {\n Config.MANAGER.get();\n DumpManager.cleanDump(\"\");\n }\n\n /**\n * Uses log4j core apis to reconfigure logging of patches into a custom file.\n * Should be stable enough, but just in case we handle errors gracefully.\n */\n private static void hackLog4j() {\n MAIN_LOGGER.debug(\"About to hack log4j config\");\n try {\n var log4jLogger = (org.apache.logging.log4j.core.Logger) LogManager.getLogger(RELOAD_LOGGER_NAME);\n var configuration = log4jLogger.getContext().getConfiguration();\n\n var appender = RandomAccessFileAppender.newBuilder()\n .setName(\"JsonPatcherFile\")\n .setFileName(\"logs/jsonpatcher.log\")\n .setLayout(PatternLayout.newBuilder().withPattern(\"[%d{HH:mm:ss}] [%t/%level] (%logger) %msg{nolookups}%n\").build())\n .setAppend(false)\n .build();\n appender.start();\n\n configuration.addAppender(appender);\n configuration.addLoggerAppender(log4jLogger, appender);\n configuration.setLoggerAdditive(log4jLogger, false);\n\n log4jLogger.setLevel(Level.toLevel(System.getProperty(\"jsonpatcher.log.level\"), Level.INFO));\n\n MAIN_LOGGER.debug(\"Successfully hacked log4j config. Now we have our own file!\");\n } catch (IncompatibleClassChangeError | NoClassDefFoundError | RuntimeException e) {\n MAIN_LOGGER.error(\"Failed to hack log4j. All output will be logged to main log.\", e);\n }\n }\n\n public static boolean isSupportedVersion(String version) {\n return SUPPORTED_VERSIONS.contains(version);\n }\n}" }, { "identifier": "DumpManager", "path": "src/main/java/io/github/mattidragon/jsonpatcher/misc/DumpManager.java", "snippet": "public class DumpManager {\n private static final Gson DUMP_GSON = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create();\n\n public static void dumpIfEnabled(Identifier id, ReloadDescription description, JsonElement patchedData) {\n if (Config.MANAGER.get().dumpPatchedFiles() && description.dumpPath() != null) {\n try {\n var file = getDumpPath(description.dumpPath())\n .resolve(Path.of(id.getNamespace(), id.getPath().split(\"/\")));\n Files.createDirectories(file.getParent());\n try (var writer = new OutputStreamWriter(Files.newOutputStream(file))) {\n DUMP_GSON.toJson(patchedData, writer);\n }\n } catch (IOException e) {\n JsonPatcher.RELOAD_LOGGER.error(\"Failed to dump patched file {}\", id, e);\n }\n }\n }\n\n public static void cleanDump(@Nullable String dumpLocation) {\n if (dumpLocation == null) return;\n\n var file = getDumpPath(dumpLocation);\n if (Files.exists(file)) {\n var errors = new ArrayList<IOException>();\n try (var stream = Files.walk(file)) {\n stream.sorted(Comparator.reverseOrder())\n .forEach(path -> {\n try {\n Files.delete(path);\n } catch (IOException e) {\n errors.add(e);\n }\n });\n if (!errors.isEmpty()) {\n var error = new IOException(\"Errors while deleting dumped files\");\n errors.forEach(error::addSuppressed);\n throw error;\n }\n } catch (IOException e) {\n JsonPatcher.RELOAD_LOGGER.error(\"Failed to clean dump directory\", e);\n }\n }\n }\n\n private static Path getDumpPath(String dumpLocation) {\n return FabricLoader.getInstance().getGameDir()\n .resolve(\"jsonpatcher-dump\")\n .resolve(dumpLocation);\n }\n}" } ]
import io.github.mattidragon.jsonpatcher.JsonPatcher; import io.github.mattidragon.jsonpatcher.misc.DumpManager; import io.github.mattidragon.jsonpatcher.misc.ReloadDescription; import net.minecraft.resource.InputSupplier; import net.minecraft.resource.ResourceManager; import net.minecraft.util.Identifier; import java.io.*; import java.util.concurrent.*;
1,456
package io.github.mattidragon.jsonpatcher.patch; public class PatchingContext { private static final ThreadLocal<Stored> ACTIVE = new ThreadLocal<>(); private static final ThreadLocal<Boolean> DISABLED = ThreadLocal.withInitial(() -> false); private final ReloadDescription description; private boolean loaded = false; private Patcher patcher = null; public PatchingContext(ReloadDescription description) { this.description = description; } public static Enabler disablePatching() { return new Enabler(); } public static PatchingContext get() { var stored = ACTIVE.get(); return stored == null ? null : stored.context; } public static void remove() { var stored = ACTIVE.get(); if (stored == null) throw new IllegalStateException("State not set"); if (stored.count > 1) { ACTIVE.set(new Stored(stored.context, stored.count - 1)); } else { ACTIVE.remove(); } } public static void set(PatchingContext context) { var stored = ACTIVE.get(); if (stored != null && stored.context != context) { remove(); // Clean up in case this was caused by one-off error throw new IllegalStateException("State already set to different value"); } var prevCount = stored == null ? 0 : stored.count; ACTIVE.set(new Stored(context, prevCount + 1)); } public void load(ResourceManager manager, Executor executor) { if (loaded) throw new IllegalStateException("Already loaded"); var patches = PatchLoader.load(executor, manager); DumpManager.cleanDump(description.dumpPath());
package io.github.mattidragon.jsonpatcher.patch; public class PatchingContext { private static final ThreadLocal<Stored> ACTIVE = new ThreadLocal<>(); private static final ThreadLocal<Boolean> DISABLED = ThreadLocal.withInitial(() -> false); private final ReloadDescription description; private boolean loaded = false; private Patcher patcher = null; public PatchingContext(ReloadDescription description) { this.description = description; } public static Enabler disablePatching() { return new Enabler(); } public static PatchingContext get() { var stored = ACTIVE.get(); return stored == null ? null : stored.context; } public static void remove() { var stored = ACTIVE.get(); if (stored == null) throw new IllegalStateException("State not set"); if (stored.count > 1) { ACTIVE.set(new Stored(stored.context, stored.count - 1)); } else { ACTIVE.remove(); } } public static void set(PatchingContext context) { var stored = ACTIVE.get(); if (stored != null && stored.context != context) { remove(); // Clean up in case this was caused by one-off error throw new IllegalStateException("State already set to different value"); } var prevCount = stored == null ? 0 : stored.count; ACTIVE.set(new Stored(context, prevCount + 1)); } public void load(ResourceManager manager, Executor executor) { if (loaded) throw new IllegalStateException("Already loaded"); var patches = PatchLoader.load(executor, manager); DumpManager.cleanDump(description.dumpPath());
JsonPatcher.RELOAD_LOGGER.info("Loaded {} patches for reload '{}'", patches.size(), description.name());
0
2023-10-30 14:09:36+00:00
2k
TISUnion/VelocityWhitelist
src/main/java/me/fallenbreath/velocitywhitelist/WhitelistManager.java
[ { "identifier": "Configuration", "path": "src/main/java/me/fallenbreath/velocitywhitelist/config/Configuration.java", "snippet": "public class Configuration\n{\n\tprivate final Map<String, Object> options = Maps.newHashMap();\n\n\t@SuppressWarnings(\"unchecked\")\n\tpublic void load(String yamlContent)\n\t{\n\t\tthis.options.clear();\n\t\tthis.options.putAll(new Yaml().loadAs(yamlContent, this.options.getClass()));\n\t}\n\n\tpublic boolean isEnabled()\n\t{\n\t\tObject playerCount = this.options.get(\"enabled\");\n\t\tif (playerCount instanceof Boolean)\n\t\t{\n\t\t\treturn (Boolean)playerCount;\n\t\t}\n\t\treturn false;\n\t}\n\n\tpublic String getKickMessage()\n\t{\n\t\tObject maxPlayer = this.options.get(\"kick_message\");\n\t\tif (maxPlayer instanceof String)\n\t\t{\n\t\t\treturn (String)maxPlayer;\n\t\t}\n\t\treturn \"You are not in whitelist!\";\n\t}\n}" }, { "identifier": "Whitelist", "path": "src/main/java/me/fallenbreath/velocitywhitelist/config/Whitelist.java", "snippet": "public class Whitelist\n{\n\tprivate final Set<String> names = Sets.newLinkedHashSet();\n\tprivate final Path whitelistFilePath;\n\tprivate final Path whitelistTempFilePath;\n\n\tpublic Whitelist(Path whitelistFilePath)\n\t{\n\t\tthis.whitelistFilePath = whitelistFilePath;\n\t\tthis.whitelistTempFilePath = whitelistFilePath.resolveSibling(whitelistFilePath.getFileName().toString() + \".tmp\");\n\t}\n\n\t@SuppressWarnings({\"unchecked\", \"rawtypes\"})\n\tpublic void load() throws IOException\n\t{\n\t\tMap<String, Object> options = Maps.newHashMap();\n\t\tString yamlContent = Files.readString(whitelistFilePath);\n\n\t\toptions = new Yaml().loadAs(yamlContent, options.getClass());\n\n\t\tthis.names.clear();\n\t\tObject list = options.get(\"names\");\n\t\tif (list instanceof List)\n\t\t{\n\t\t\t((List)list).forEach(entry -> this.names.add(entry.toString()));\n\t\t}\n\t}\n\n\tpublic void save() throws IOException\n\t{\n\t\tMap<String, Object> options = Maps.newHashMap();\n\t\toptions.put(\"names\", Lists.newArrayList(this.names));\n\n\t\tDumperOptions dumperOptions = new DumperOptions();\n\t\tdumperOptions.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);\n\n\t\tString yamlContent = new Yaml(dumperOptions).dump(options);\n\t\tFiles.writeString(this.whitelistTempFilePath, yamlContent, StandardCharsets.UTF_8);\n\t\tFiles.move(this.whitelistTempFilePath, this.whitelistFilePath, StandardCopyOption.REPLACE_EXISTING);\n\t}\n\n\tpublic Set<String> getNames()\n\t{\n\t\treturn this.names;\n\t}\n}" } ]
import com.google.common.collect.Lists; import com.velocitypowered.api.event.ResultedEvent; import com.velocitypowered.api.event.connection.LoginEvent; import com.velocitypowered.api.util.GameProfile; import me.fallenbreath.velocitywhitelist.config.Configuration; import me.fallenbreath.velocitywhitelist.config.Whitelist; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.TextComponent; import org.slf4j.Logger; import java.io.IOException; import java.nio.file.Path; import java.util.List;
786
package me.fallenbreath.velocitywhitelist; public class WhitelistManager { private final Logger logger; private final Configuration config; private final Path whitelistFilePath;
package me.fallenbreath.velocitywhitelist; public class WhitelistManager { private final Logger logger; private final Configuration config; private final Path whitelistFilePath;
private Whitelist whitelist = null;
1
2023-10-28 09:34:29+00:00
2k
ThomasGorisseGit/ERP_Essence_BUT
backend/src/main/java/fr/gorisse/erp/backend/services/UserCheckingService.java
[ { "identifier": "User", "path": "backend/src/main/java/fr/gorisse/erp/backend/entity/User.java", "snippet": "@Data\n@NoArgsConstructor\n@AllArgsConstructor\n@ToString\n@EqualsAndHashCode(callSuper = true)\n@Entity\npublic class User extends Person implements UserDetails {\n @Id\n @GeneratedValue(strategy = GenerationType.AUTO)\n private int id;\n\n @Convert(converter = LoginConverter.class)\n private Login login;\n\n @Convert(converter = PasswordConverter.class)\n @Getter(AccessLevel.NONE)\n private Password password;\n\n @Convert(converter = StatusConverter.class)\n private Status status;\n\n private Double salary;\n\n\n public User (String firstname, String lastname, String password){\n super(firstname,lastname);\n this.login = Login.create(firstname+\"@\"+lastname);\n this.password = Password.create(password);\n this.status = Status.create(\"Employee\");\n this.salary = Status.getSalary(\"Employee\");\n }\n public void setLogin(){\n this.login = Login.create(this.getFirstName() + \"@\" + this.getLastName());\n }\n\n @Override\n public Collection<? extends GrantedAuthority> getAuthorities() {\n return Collections.singletonList(new SimpleGrantedAuthority(\"ROLE_USER\"));\n }\n\n @Override\n public String getUsername() {\n return this.getLogin().toString();\n }\n @Override\n public String getPassword(){\n return this.password.getPassword();\n }\n @Override\n public boolean isAccountNonExpired() {\n return true;\n }\n\n @Override\n public boolean isAccountNonLocked() {\n return true;\n }\n\n @Override\n public boolean isCredentialsNonExpired() {\n return true;\n }\n\n @Override\n public boolean isEnabled() {\n return true;\n }\n}" }, { "identifier": "Login", "path": "backend/src/main/java/fr/gorisse/erp/backend/entity/valueObject/Login.java", "snippet": "@Value\npublic class Login {\n String login;\n\n private Login(String login){\n this.login = login;\n }\n public static Login create(String login){\n final int maxSize = 30;\n if(login.length()>maxSize) {\n throw new InvalidInput(\" Login must be less than \"+maxSize+\" characters\");\n }\n if(!hasValidChar(login))\n {\n throw new InvalidInput(\" The login contains invalid characters. \");\n }\n\n return new Login(login);\n\n }\n private static boolean hasValidChar(String login){\n boolean isValid = true;\n for(int i =0;i<login.length();i++){\n char currentChar = login.charAt(i);\n if (!contains(currentChar)) {\n isValid = false;\n break;\n }\n }\n return isValid;\n }\n private static boolean contains(char character){\n boolean founded = false;\n int i =0 ;\n final char[] authorizedChar = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_./#*@&éàùè'-123456789\".toCharArray();\n\n while (i<authorizedChar.length && !founded){\n if(authorizedChar[i]==character) founded = true;\n i++;\n }\n return founded;\n }\n public String toString(){\n return this.login;\n }\n}" }, { "identifier": "Password", "path": "backend/src/main/java/fr/gorisse/erp/backend/entity/valueObject/Password.java", "snippet": "@Value\npublic class Password {\n String password;\n\n private Password(String password) {\n this.password = password;\n }\n\n public static Password create(String password){\n final int maxSize = 400;\n if (password.length() > maxSize) {\n throw new InvalidInput(\" Password must be less than \"+maxSize+\" characters \");\n }\n else{\n return new Password(password);\n }\n }\n\n public String toString(){\n return this.password;\n }\n\n\n\n}" }, { "identifier": "Status", "path": "backend/src/main/java/fr/gorisse/erp/backend/entity/valueObject/Status.java", "snippet": "@Value\npublic class Status {\n String userStatus;\n private Status(String userStatus ){\n this.userStatus = userStatus;\n }\n public static Status create(String userStatus){\n if(Arrays.stream(StatusSalary.values()).anyMatch(word -> Objects.equals(word.toString(), userStatus))){\n return new Status(userStatus);\n }\n throw new InvalidInput(\"Status is incorrect\");\n }\n\n public static double getSalary(String userStatus){\n if(Arrays.stream(StatusSalary.values()).anyMatch(word -> Objects.equals(word.toString(), userStatus))){\n return StatusSalary.valueOf(userStatus).getSalary();\n }\n throw new InvalidInput(\"Status is incorrect\");\n }\n public String toString(){\n return this.userStatus;\n }\n}" }, { "identifier": "DataNotFounded", "path": "backend/src/main/java/fr/gorisse/erp/backend/exceptions/DataNotFounded.java", "snippet": "@ResponseStatus(value = HttpStatus.NOT_FOUND, reason = \"Data not founded\")\n\npublic class DataNotFounded extends NoSuchElementException {\n public DataNotFounded(String message){\n super(message);\n }\n}" }, { "identifier": "UserRepository", "path": "backend/src/main/java/fr/gorisse/erp/backend/repository/UserRepository.java", "snippet": "public interface UserRepository extends DefaultRepository<User> {\n Optional<User> findByLogin(Login login);\n}" }, { "identifier": "UserCheckingServiceInterface", "path": "backend/src/main/java/fr/gorisse/erp/backend/services/interfaces/UserCheckingServiceInterface.java", "snippet": "public interface UserCheckingServiceInterface {\n User getUserByLogin(String login);\n\n}" } ]
import fr.gorisse.erp.backend.entity.User; import fr.gorisse.erp.backend.entity.valueObject.Login; import fr.gorisse.erp.backend.entity.valueObject.Password; import fr.gorisse.erp.backend.entity.valueObject.Status; import fr.gorisse.erp.backend.exceptions.DataNotFounded; import fr.gorisse.erp.backend.repository.UserRepository; import fr.gorisse.erp.backend.services.interfaces.UserCheckingServiceInterface; import lombok.NoArgsConstructor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; import java.util.Optional;
1,450
package fr.gorisse.erp.backend.services; @Service @NoArgsConstructor
package fr.gorisse.erp.backend.services; @Service @NoArgsConstructor
public class UserCheckingService extends ServiceMethods<User> implements UserCheckingServiceInterface , UserDetailsService {
0
2023-10-29 20:50:47+00:00
2k
DavidPerezAntonio51/calculadora-distribuida-con-rmi
calculadora/src/main/java/mx/tese/BusMensajes.java
[ { "identifier": "RequestWorker", "path": "calculadora/src/main/java/mx/tese/BusMensajesCore/RequestWorker.java", "snippet": "public class RequestWorker implements Runnable {\n private final ServerRegistryManager serverRegistry;\n private final Socket clienteRequest;\n\n public RequestWorker(Socket clienteRequest, ServerRegistryManager serverRegistry) {\n this.serverRegistry = serverRegistry;\n this.clienteRequest = clienteRequest;\n }\n\n @Override\n public void run() {\n Optional<Replica<ServidorReplica>> server = serverRegistry.getServer();\n try {\n ObjectOutputStream output = new ObjectOutputStream(clienteRequest.getOutputStream());\n ObjectInputStream input = new ObjectInputStream(clienteRequest.getInputStream());\n String operacion = input.readUTF();\n if (!server.isPresent()) {\n output.writeObject(new Respuesta(\"No hay servidores disponibles para procesar la solicitud.\"));\n System.out.println(\"No hay servidores disponibles para procesar la solicitud.\");\n return;\n }\n Replica<ServidorReplica> replica = server.get();\n System.out.println(\"Enviando solicitud al servidor con puerto: \" + replica.getPort());\n ServidorReplica servidorReplica = replica.getReplica();\n Respuesta calcular = servidorReplica.calcular(operacion);\n output.writeObject(calcular);\n } catch (IOException e) {\n System.out.println(e.getMessage());\n throw new RuntimeException(e);\n } finally {\n try {\n if (server.isPresent()&&server.get().getReplica().healthCheck()) {\n serverRegistry.regresarServer(server.get());\n }\n } catch (RemoteException e) {\n System.out.println(\"Servidor no disponible, ya no se encola de nuevo.\");\n }\n }\n }\n}" }, { "identifier": "ServerRegistryManager", "path": "calculadora/src/main/java/mx/tese/BusMensajesCore/ServerRegistryManager.java", "snippet": "public interface ServerRegistryManager {\n Optional<Replica<ServidorReplica>> getServer();\n void regresarServer(Replica<ServidorReplica> server);\n}" }, { "identifier": "ServerRegistry", "path": "calculadora/src/main/java/mx/tese/RMI/ServerRegistry.java", "snippet": "public interface ServerRegistry extends Remote {\n boolean registrarServidor(String ip, Integer puerto) throws RemoteException;\n}" }, { "identifier": "ServerRegistryImpl", "path": "calculadora/src/main/java/mx/tese/RMI_Impl/ServerRegistryImpl.java", "snippet": "public class ServerRegistryImpl extends UnicastRemoteObject implements ServerRegistry, ServerRegistryManager {\n\n private Queue<Replica<ServidorReplica>> replicas;\n\n public ServerRegistryImpl() throws RemoteException {\n this.replicas = new ConcurrentLinkedQueue<>();\n }\n\n @Override\n public boolean registrarServidor(String ip, Integer puerto) {\n System.out.println(\"Registrando servidor: \" + ip + \":\" + puerto);\n String servidorRemotoURL = \"rmi://\" + ip + \":\" + puerto + \"/ServidorReplica\";\n try {\n ServidorReplica nuevaReplica = (ServidorReplica) Naming.lookup(servidorRemotoURL);\n Replica<ServidorReplica> replica = new Replica<>(nuevaReplica, puerto, ip);\n replicas.offer(replica);\n System.out.println(\"Servidor registrado correctamente, en linea: \" + nuevaReplica.healthCheck());\n return true;\n } catch (NotBoundException | RemoteException | MalformedURLException e) {\n System.err.println(\"Error al registrar el servidor con puerto: \" + puerto);\n System.err.println(\"Message: \" + e.getMessage() + \" Cause: \" + e.getCause());\n }\n return false;\n }\n\n @Override\n public synchronized Optional<Replica<ServidorReplica>> getServer() {\n if (replicas.isEmpty()) {\n // Si la cola está vacía, no hay elementos disponibles\n return Optional.empty();\n }\n while (true) {\n // Obtiene el elemento de la cola\n Replica<ServidorReplica> elemento = replicas.poll();\n if (elemento != null) {\n try {\n System.out.println(\"Verificando la salud del servidor con puerto:\"+elemento.getPort()+\"...\");\n // Verifica si el servidor está activo llamando a checkHealt\n if (elemento.getReplica().healthCheck()) {\n // Si el servidor está activo, regresa el elemento\n System.out.println(\"Servidor con puerto:\"+elemento.getPort()+\" En linea:\" + elemento.getReplica().healthCheck());\n return Optional.of(elemento);\n } else {\n System.out.println(\"El servidor ya no está activo. Descartando elemento.\");\n }\n } catch (RemoteException e) {\n // Si se produce una excepción, el servidor no está activo, por lo que quitamos el elemento\n System.err.println(\"Error al verificar la salud del servidor. Descartando elemento.\");\n }\n } else {\n // La cola está vacía, no hay elementos válidos disponibles\n return Optional.empty();\n }\n }\n }\n\n @Override\n public void regresarServer(Replica<ServidorReplica> server) {\n replicas.offer(server);\n }\n}" } ]
import mx.tese.BusMensajesCore.RequestWorker; import mx.tese.BusMensajesCore.ServerRegistryManager; import mx.tese.RMI.ServerRegistry; import mx.tese.RMI_Impl.ServerRegistryImpl; import java.net.ServerSocket; import java.net.Socket; import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry; import java.util.Scanner; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors;
1,540
package mx.tese; public class BusMensajes { public static void main(String[] args,Scanner scanner) throws InterruptedException { int puertoRMI = obtenerPuertoRMIValido(scanner); // Solicita al usuario el puerto RMI int puertoServerSocket = obtenerPuertoServerSocketValido(scanner); // Solicita al usuario el puerto del servidor de sockets int maxThreads = 10; // Establece el límite máximo de threads // Solicita al usuario la cantidad de threads int numThreads = solicitarNumeroThreads(maxThreads,scanner); // Crea el ExecutorService con la cantidad de threads especificada ExecutorService executor = Executors.newFixedThreadPool(numThreads); try { System.out.println("INICIANDO BUS DE MENSAJES..."); // Crea un registro RMI en el puerto por defecto Registry registry = LocateRegistry.createRegistry(puertoRMI); // Crea una instancia de la calculadora ServerRegistry serverRegistry = new ServerRegistryImpl(); // Registra la instancia en el registro RMI registry.rebind("ServerRegistry", serverRegistry); System.out.println("El ServerRegisty escucha en el puerto " + puertoRMI + ".");
package mx.tese; public class BusMensajes { public static void main(String[] args,Scanner scanner) throws InterruptedException { int puertoRMI = obtenerPuertoRMIValido(scanner); // Solicita al usuario el puerto RMI int puertoServerSocket = obtenerPuertoServerSocketValido(scanner); // Solicita al usuario el puerto del servidor de sockets int maxThreads = 10; // Establece el límite máximo de threads // Solicita al usuario la cantidad de threads int numThreads = solicitarNumeroThreads(maxThreads,scanner); // Crea el ExecutorService con la cantidad de threads especificada ExecutorService executor = Executors.newFixedThreadPool(numThreads); try { System.out.println("INICIANDO BUS DE MENSAJES..."); // Crea un registro RMI en el puerto por defecto Registry registry = LocateRegistry.createRegistry(puertoRMI); // Crea una instancia de la calculadora ServerRegistry serverRegistry = new ServerRegistryImpl(); // Registra la instancia en el registro RMI registry.rebind("ServerRegistry", serverRegistry); System.out.println("El ServerRegisty escucha en el puerto " + puertoRMI + ".");
ServerRegistryManager serverRegistryManager = (ServerRegistryManager) serverRegistry;
1
2023-10-27 02:16:18+00:00
2k
michilanau/jwt-authentication
src/main/java/com/malanau/jwtauthentication/user/infrastructure/controller/UserController.java
[ { "identifier": "ErrorResponse", "path": "src/main/java/com/malanau/jwtauthentication/shared/application/ErrorResponse.java", "snippet": "@AllArgsConstructor\n@Getter\npublic class ErrorResponse {\n Integer code;\n String message;\n}" }, { "identifier": "UserResponse", "path": "src/main/java/com/malanau/jwtauthentication/user/application/UserResponse.java", "snippet": "@AllArgsConstructor\n@Getter\npublic class UserResponse {\n String login;\n String token;\n}" }, { "identifier": "UserAuthRequest", "path": "src/main/java/com/malanau/jwtauthentication/user/application/authenticate/UserAuthRequest.java", "snippet": "@AllArgsConstructor\n@Getter\npublic class UserAuthRequest {\n String login;\n String password;\n}" }, { "identifier": "UserAuthenticator", "path": "src/main/java/com/malanau/jwtauthentication/user/application/authenticate/UserAuthenticator.java", "snippet": "@AllArgsConstructor\n@Service\npublic class UserAuthenticator {\n\n private final UserRepository userRepository;\n private final AuthenticationTokenCreator authenticationTokenCreator;\n\n public UserResponse authenticate(final UserAuthRequest userAuthRequest) {\n\n final Optional<User> user = userRepository.search(new Login(userAuthRequest.getLogin()));\n\n ensureUserExist(user, new Login(userAuthRequest.getLogin()));\n ensureCredentialsAreValid(user.get(), new Password(userAuthRequest.getPassword()));\n\n return new UserResponse(\n user.get().getLogin().value(),\n authenticationTokenCreator.createToken(user.get().getLogin().value()));\n }\n\n private void ensureUserExist(final Optional<User> user, final Login login) {\n if (!user.isPresent()) {\n throw new InvalidAuthLogin(login);\n }\n }\n\n private void ensureCredentialsAreValid(final User user, final Password password) {\n if (!user.passwordMatches(password)) {\n throw new InvalidAuthPassword(user.getLogin());\n }\n }\n}" }, { "identifier": "UserRegister", "path": "src/main/java/com/malanau/jwtauthentication/user/application/register/UserRegister.java", "snippet": "@Service\n@AllArgsConstructor\npublic class UserRegister {\n UserRepository userRepository;\n AuthenticationTokenCreator authenticationTokenCreator;\n\n public UserResponse register(final UserRegisterRequest userRegisterRequest) {\n\n final Optional<User> user = userRepository.search(new Login(userRegisterRequest.getLogin()));\n\n ensureUserDoesNotExist(user, new Login(userRegisterRequest.getLogin()));\n\n final User newUser =\n new User(\n new Login(userRegisterRequest.getLogin()),\n new Password(userRegisterRequest.getPassword()));\n userRepository.save(newUser);\n\n return new UserResponse(\n newUser.getLogin().value(),\n authenticationTokenCreator.createToken(newUser.getLogin().value()));\n }\n\n public void ensureUserDoesNotExist(final Optional<User> user, final Login login) {\n if (user.isPresent()) {\n throw new UserAlreadyExists(login);\n }\n }\n}" }, { "identifier": "UserRegisterRequest", "path": "src/main/java/com/malanau/jwtauthentication/user/application/register/UserRegisterRequest.java", "snippet": "@AllArgsConstructor\n@Getter\npublic class UserRegisterRequest {\n String login;\n String password;\n}" }, { "identifier": "InvalidAuthLogin", "path": "src/main/java/com/malanau/jwtauthentication/user/domain/InvalidAuthLogin.java", "snippet": "public final class InvalidAuthLogin extends RuntimeException {\n public InvalidAuthLogin(final Login login) {\n super(String.format(\"The user <%s> does not exist\", login.value()));\n }\n}" }, { "identifier": "InvalidAuthPassword", "path": "src/main/java/com/malanau/jwtauthentication/user/domain/InvalidAuthPassword.java", "snippet": "public final class InvalidAuthPassword extends RuntimeException {\n public InvalidAuthPassword(final Login login) {\n super(String.format(\"The credentials for <%s> are invalid\", login.value()));\n }\n}" }, { "identifier": "UserAlreadyExists", "path": "src/main/java/com/malanau/jwtauthentication/user/domain/UserAlreadyExists.java", "snippet": "public final class UserAlreadyExists extends RuntimeException {\n public UserAlreadyExists(final Login login) {\n super(String.format(\"The user <%s> already exists\", login.value()));\n }\n}" } ]
import com.malanau.jwtauthentication.shared.application.ErrorResponse; import com.malanau.jwtauthentication.user.application.UserResponse; import com.malanau.jwtauthentication.user.application.authenticate.UserAuthRequest; import com.malanau.jwtauthentication.user.application.authenticate.UserAuthenticator; import com.malanau.jwtauthentication.user.application.register.UserRegister; import com.malanau.jwtauthentication.user.application.register.UserRegisterRequest; import com.malanau.jwtauthentication.user.domain.InvalidAuthLogin; import com.malanau.jwtauthentication.user.domain.InvalidAuthPassword; import com.malanau.jwtauthentication.user.domain.UserAlreadyExists; import lombok.AllArgsConstructor; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController;
1,096
package com.malanau.jwtauthentication.user.infrastructure.controller; @RestController @AllArgsConstructor public class UserController {
package com.malanau.jwtauthentication.user.infrastructure.controller; @RestController @AllArgsConstructor public class UserController {
UserAuthenticator userAuthenticator;
3
2023-10-29 22:16:48+00:00
2k
nailuj1992/OracionesCatolicas
app/src/main/java/com/prayers/app/ui/adapter/NinthJoysAdapter.java
[ { "identifier": "AbstractActivity", "path": "app/src/main/java/com/prayers/app/activity/AbstractActivity.java", "snippet": "public abstract class AbstractActivity extends AppCompatActivity implements SharedPreferences.OnSharedPreferenceChangeListener {\n\n protected String initialLocale;\n\n /**\n * Get the view layout id bound to this activity object.\n *\n * @return\n */\n public abstract int getActivity();\n\n /**\n * Prepare all view fields.\n */\n public abstract void prepareActivity();\n\n /**\n * Update all fields on the view.\n */\n public abstract void updateViewState();\n\n /**\n * Does the back action.\n */\n public abstract void backAction();\n\n /**\n * Does the next action.\n */\n public abstract void nextAction();\n\n @Override\n protected final void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n initialLocale = LocaleHelper.getPersistedLocale(this);\n overridePendingTransition(R.anim.enter_activity, R.anim.exit_activity);\n\n setContentView(getActivity());\n prepareActivity();\n updateViewState();\n }\n\n @Override\n public final void onConfigurationChanged(Configuration newConfig) {\n super.onConfigurationChanged(newConfig);\n\n setContentView(getActivity());\n prepareActivity();\n updateViewState();\n }\n\n @Override\n protected void attachBaseContext(Context base) {\n super.attachBaseContext(LocaleHelper.onAttach(base));\n }\n\n @Override\n protected void onResume() {\n super.onResume();\n if (initialLocale != null && !initialLocale.equals(LocaleHelper.getPersistedLocale(this))) {\n recreate();\n }\n }\n\n @Override\n public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, @Nullable String key) {\n switch (key) {\n case GeneralConstants.KEY_PREF_LANGUAGE:\n LocaleHelper.setLocale(getApplicationContext(), PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).getString(key, \"\"));\n recreate(); // necessary here because this Activity is currently running and thus a recreate() in onResume() would be too late\n break;\n }\n }\n\n @Override\n public final void onBackPressed() {\n backAction();\n }\n\n}" }, { "identifier": "Joy", "path": "app/src/main/java/com/prayers/app/model/ninth/Joy.java", "snippet": "public class Joy implements Serializable {\n\n private String[] lines;\n\n public Joy(String... lines) throws PrayersException {\n if (lines == null || lines.length == 0) {\n throw new PrayersException(GeneralConstants.JOY_WITHOUT_LINES);\n }\n this.lines = lines;\n }\n\n public String[] getLines() {\n return lines;\n }\n\n}" } ]
import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import com.prayers.app.activity.AbstractActivity; import com.prayers.app.activity.R; import com.prayers.app.model.ninth.Joy;
729
package com.prayers.app.ui.adapter; public class NinthJoysAdapter extends RecyclerView.Adapter<ViewHolder> { private Context context; private Joy joy;
package com.prayers.app.ui.adapter; public class NinthJoysAdapter extends RecyclerView.Adapter<ViewHolder> { private Context context; private Joy joy;
private AbstractActivity activity;
0
2023-10-25 17:17:47+00:00
2k
llllllxy/tiny-mybatis-paginate
src/main/java/org/tinycloud/paginate/dialect/support/InforMixDialect.java
[ { "identifier": "Page", "path": "src/main/java/org/tinycloud/paginate/Page.java", "snippet": "public class Page<T> implements Serializable {\n private static final long serialVersionUID = 1L;\n\n /**\n * 当前页码(pageNo = offset / limit + 1;)\n */\n private Integer pageNum;\n\n /**\n * 分页大小(等价于limit)\n */\n private Integer pageSize;\n\n /**\n * 总记录数\n */\n private Integer total;\n\n /**\n * 总页数\n */\n private Integer pages;\n\n /**\n * 分页后的数据\n */\n private Collection<T> records;\n\n public Page() {\n\n }\n\n public Page(Integer pageNum, Integer pageSize) {\n this.pageSize = pageSize;\n this.pageNum = pageNum;\n }\n\n public Page(Collection<T> records, int total, Integer pageNum, Integer pageSize) {\n this.records = (records == null ? new ArrayList<T>() : records);\n this.total = total;\n this.pageSize = pageSize;\n this.pageNum = pageNum;\n this.pages = (total + pageSize - 1) / pageSize;\n }\n\n public Integer getPageNum() {\n return pageNum;\n }\n\n public void setPageNum(Integer pageNum) {\n this.pageNum = pageNum;\n }\n\n public Integer getPageSize() {\n return pageSize;\n }\n\n public void setPageSize(Integer pageSize) {\n this.pageSize = pageSize;\n }\n\n public Integer getPages() {\n return pages;\n }\n\n public void setPages(Integer pages) {\n this.pages = pages;\n }\n\n public Collection<T> getRecords() {\n return records;\n }\n\n public void setRecords(Collection<T> records) {\n this.records = records;\n }\n\n public Integer getTotal() {\n return total;\n }\n\n public void setTotal(Integer total) {\n this.total = total;\n this.pages = (total + pageSize - 1) / pageSize;\n }\n\n /**\n * 是否存在下一页\n *\n * @return true:存在,false:不存在\n */\n public boolean hasNextPage() {\n return this.getPages() > this.getPageNum();\n }\n\n /**\n * 是否存在上一页\n *\n * @return true:存在上一页,false:不存在\n */\n public boolean hasPreviousPage() {\n return this.getPageNum() > 1;\n }\n\n /**\n * 是否为首页\n *\n * @return true:首页,false:非首页\n */\n public boolean firstPage() {\n return this.getPageNum() == 1;\n }\n\n /**\n * 是否为末页\n *\n * @return true:为末页,false:非末页\n */\n public boolean lastPage() {\n return this.getPages().equals(this.getPageNum());\n }\n\n @Override\n public String toString() {\n return \"Page {pageNum=\" + pageNum + \", pageSize=\" + pageSize + \", total=\" + total + \", pages=\" + pages\n + \", records=\" + records + \"}\";\n }\n}" }, { "identifier": "AbstractDialect", "path": "src/main/java/org/tinycloud/paginate/dialect/AbstractDialect.java", "snippet": "public abstract class AbstractDialect implements Dialect {\n\n /**\n * 获取查询总条数sql\n *\n * @param oldSQL 原始sql\n * @return 查询总条数count sql\n */\n @Override\n public String getCountSql(String oldSQL) {\n StringBuilder sql = new StringBuilder();\n sql.append(\"SELECT COUNT(0) FROM ( \");\n sql.append(oldSQL);\n sql.append(\" ) TEMP_COUNT\");\n return sql.toString();\n }\n}" } ]
import org.tinycloud.paginate.Page; import org.tinycloud.paginate.dialect.AbstractDialect; import java.util.regex.Matcher; import java.util.regex.Pattern;
1,076
package org.tinycloud.paginate.dialect.support; public class InforMixDialect extends AbstractDialect { /** * 分页查询适配 * * @param oldSQL 原始sql * @param page 分页参数对象 * @return 处理过后的sql */ @Override
package org.tinycloud.paginate.dialect.support; public class InforMixDialect extends AbstractDialect { /** * 分页查询适配 * * @param oldSQL 原始sql * @param page 分页参数对象 * @return 处理过后的sql */ @Override
public String getPageSql(String oldSQL, Page<?> page) {
0
2023-10-26 06:05:58+00:00
2k
LeoK99/swtw45WS21_reupload
src/main/java/com/buschmais/frontend/components/ADRCommentComponent.java
[ { "identifier": "ADRComment", "path": "backup/java/com/buschmais/adr/ADRComment.java", "snippet": "@Data\npublic class ADRComment {\n\n\t@lombok.NonNull\n\tprivate String text;\n\n\t@Setter(AccessLevel.NONE)\n\tprivate List<ADRComment> replies;\n\n\tpublic ADRComment(){\n\t\treplies = new ArrayList<>();\n\t}\n\n\tpublic boolean addReply(@NonNull ADRComment comment){\n\t\treturn replies.add(comment);\n\t}\n\n\tpublic boolean removeReply(@NonNull ADRComment comment){\n\t\treturn replies.remove(comment);\n\t}\n}" }, { "identifier": "UserDao", "path": "src/main/java/com/buschmais/backend/users/dataAccess/UserDao.java", "snippet": "@Service\npublic class UserDao {\n\n\tprivate final UserRepository repo;\n\tprivate final MongoOperations mongoOperations;\n\tprivate final ImageDao imageDao;\n\n\tUserDao(@Autowired UserRepository repo,\n\t\t\t@Autowired MongoOperations mongoOperations,\n\t\t\t@Autowired ImageDao imageDao){\n\t\tthis.repo = repo;\n\t\tthis.mongoOperations = mongoOperations;\n\t\tthis.imageDao = imageDao;\n\t}\n\n\t/**\n\t * Gibt alle Nutzer zurück\n\t * @return entsprechender Nutzer\n\t */\n\tpublic List<User> findAll() {\n\t\treturn repo.findAll();\n\t}\n\n\tpublic Optional<User> findById(String id) {\n\t\tif(id == null) {\n\t\t\treturn Optional.empty();\n\t\t}\n\n\t\treturn repo.findById(id);\n\t}\n\n\t/**\n\t * Gibt einen Nutzer mit dem entsprechenden Nutzernamen zurück\n\t * @param userName der Nutzername des Nutzers\n\t * @return entsprechender Nutzer\n\t */\n\tpublic Optional<User> findByUserName(@NonNull final String userName) throws UsernameNotFoundException {\n\t\treturn repo.findByUserName(userName);\n\t}\n\n\t/**\n\t * Gibt alle Nutzer zurück, die genau alle gegebenen Rechte haben.\n\t * Es werden auf true und false gesetzte Werte beachtet.\n\t * Es werden also keine Nutzer zurückgegeben, die mehr (oder weniger) als die angeforderten Rechte besitzen.\n\t * @param rights UserRights Element zum Abgleich der Rechte\n\t * @return entsprechende Nutzer\n\t */\n\tpublic List<User> findAllByRights(@NonNull final UserRights rights) {\n\t\treturn repo.findAllByRights(rights);\n\t}\n\n\t/**\n\t * Gibt alle Nutzer zurück, die mindestens alle gegebenen Rechte haben.\n\t * Es werden nur auf true gesetzte Werte beachtet.\n\t * Es werden also auch alle Nutzer zurückgegeben, die mehr als die angeforderten Rechte besitzen.\n\t * @param rights UserRights Element zum Abgleich der Rechte\n\t * @return entsprechende Nutzer\n\t */\n\tpublic List<User> findAllByHasRights(@NonNull final UserRights rights) {\n\t\tif(rights.getFlags() == 0)\n\t\t\treturn repo.findAll();\n\n\t\tQuery q = new Query();\n\t\tq.addCriteria(Criteria.where(\"rights.flags\").bits().allSet(rights.getFlags()));\n\t\treturn mongoOperations.find(q, User.class);\n\t}\n\n\t/**\n\t * Speichert den angegebenen Nutzer in der Datenbank ab\n\t * @param user zu speichernder Nutzer\n\t * @return user which got saved; null, if a user with the username already exists\n\t */\n\tpublic User save(@NonNull final User user) {\n\t\tif(this.findByUserName(user.getUserName()).isPresent() && this.findById(user.getId()).isEmpty()) {\n\t\t\treturn null;\n\t\t}\n\t\treturn repo.save(user);\n\t}\n\n\t/**\n\t *\n\t * @return currently logged in user; null, if user not logged in or user got deleted\n\t */\n\tpublic User getCurrentUser(){\n\t\ttry {\n\t\t\treturn this.findById(VaadinSession.getCurrent().getAttribute(User.class).getId()).orElse(null);\n\t\t}\n\t\tcatch(Exception e) {\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tpublic void setCurrentUser(@NonNull final User user){\n\t\tVaadinSession.getCurrent().setAttribute(User.class, user);\n\t}\n\n\tpublic void deleteAll() {\n\t\trepo.findAll().forEach(u -> {if(u.getProfilePicture() != null) imageDao.delete(u.getProfilePicture());});\n\t\trepo.deleteAll();\n\t}\n\n\tpublic void delete(@NonNull User user) {\n\t\tif(user.getProfilePicture() != null){\n\t\t\timageDao.delete(user.getProfilePicture());\n\t\t}\n\t\trepo.delete(user);\n\t}\n}" } ]
import com.buschmais.backend.adr.ADRComment; import com.buschmais.backend.users.dataAccess.UserDao; import com.vaadin.flow.component.dependency.CssImport; import com.vaadin.flow.component.html.Label; import com.vaadin.flow.component.orderedlayout.VerticalLayout; import lombok.NonNull; import org.springframework.beans.factory.annotation.Autowired; import java.util.List;
1,205
package com.buschmais.frontend.components; @CssImport("./themes/adr-workbench/adrVoting/comment-component.css") public class ADRCommentComponent extends VerticalLayout {
package com.buschmais.frontend.components; @CssImport("./themes/adr-workbench/adrVoting/comment-component.css") public class ADRCommentComponent extends VerticalLayout {
private final UserDao userService;
1
2023-10-25 15:18:06+00:00
2k
rafaelrok/ms-order-pattern-saga-choreography
order-service/src/main/java/br/com/rafaelvieira/ms/choreography/orderservice/core/service/EventService.java
[ { "identifier": "ValidationException", "path": "order-service/src/main/java/br/com/rafaelvieira/ms/choreography/orderservice/config/exception/ValidationException.java", "snippet": "@ResponseStatus(HttpStatus.BAD_REQUEST)\npublic class ValidationException extends RuntimeException {\n\n public ValidationException(String message) {\n super(message);\n }\n}" }, { "identifier": "Event", "path": "order-service/src/main/java/br/com/rafaelvieira/ms/choreography/orderservice/core/document/Event.java", "snippet": "@Data\n@Builder\n@NoArgsConstructor\n@AllArgsConstructor\n@Document(collection = \"event\")\npublic class Event {\n\n @Id\n private String id;\n private String transactionId;\n private String orderId;\n private Order payload;\n private String source;\n private ESagaStatus status;\n private List<History> eventHistory;\n private LocalDateTime createdAt;\n\n public void addToHistory(History history) {\n if (isEmpty(eventHistory)) {\n eventHistory = new ArrayList<>();\n }\n eventHistory.add(history);\n }\n}" }, { "identifier": "History", "path": "order-service/src/main/java/br/com/rafaelvieira/ms/choreography/orderservice/core/document/History.java", "snippet": "@Data\n@Builder\n@NoArgsConstructor\n@AllArgsConstructor\npublic class History {\n\n private String source;\n private ESagaStatus status;\n private String message;\n private LocalDateTime createdAt;\n}" }, { "identifier": "Order", "path": "order-service/src/main/java/br/com/rafaelvieira/ms/choreography/orderservice/core/document/Order.java", "snippet": "@Data\n@Builder\n@NoArgsConstructor\n@AllArgsConstructor\n@Document(collection = \"order\")\npublic class Order {\n\n @Id\n private String id;\n private List<OrderProducts> products;\n private LocalDateTime createdAt;\n private String transactionId;\n private double totalAmount;\n private int totalItems;\n}" }, { "identifier": "EventFilters", "path": "order-service/src/main/java/br/com/rafaelvieira/ms/choreography/orderservice/core/dto/EventFilters.java", "snippet": "@Data\n@NoArgsConstructor\n@AllArgsConstructor\npublic class EventFilters {\n\n private String orderId;\n private String transactionId;\n}" }, { "identifier": "ESagaStatus", "path": "order-service/src/main/java/br/com/rafaelvieira/ms/choreography/orderservice/core/enums/ESagaStatus.java", "snippet": "public enum ESagaStatus {\n SUCCESS,\n ROLLBACK_PENDING,\n FAIL\n}" }, { "identifier": "EventRepository", "path": "order-service/src/main/java/br/com/rafaelvieira/ms/choreography/orderservice/core/repository/EventRepository.java", "snippet": "public interface EventRepository extends MongoRepository<Event, String> {\n\n List<Event> findAllByOrderByCreatedAtDesc();\n\n Optional<Event> findTop1ByOrderIdOrderByCreatedAtDesc(String orderId);\n\n Optional<Event> findTop1ByTransactionIdOrderByCreatedAtDesc(String transactionId);\n}" } ]
import br.com.rafaelvieira.ms.choreography.orderservice.config.exception.ValidationException; import br.com.rafaelvieira.ms.choreography.orderservice.core.document.Event; import br.com.rafaelvieira.ms.choreography.orderservice.core.document.History; import br.com.rafaelvieira.ms.choreography.orderservice.core.document.Order; import br.com.rafaelvieira.ms.choreography.orderservice.core.dto.EventFilters; import br.com.rafaelvieira.ms.choreography.orderservice.core.enums.ESagaStatus; import br.com.rafaelvieira.ms.choreography.orderservice.core.repository.EventRepository; import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import java.time.LocalDateTime; import java.util.List; import static org.springframework.util.ObjectUtils.isEmpty;
883
package br.com.rafaelvieira.ms.choreography.orderservice.core.service; @Slf4j @Service @AllArgsConstructor public class EventService { private static final String CURRENT_SOURCE = "ORDER_SERVICE";
package br.com.rafaelvieira.ms.choreography.orderservice.core.service; @Slf4j @Service @AllArgsConstructor public class EventService { private static final String CURRENT_SOURCE = "ORDER_SERVICE";
private final EventRepository repository;
6
2023-10-26 11:12:21+00:00
2k
MultiDuels/MultiDuels
common/src/main/java/dev/kafein/multiduels/common/redis/RedisClient.java
[ { "identifier": "Decoder", "path": "common/src/main/java/dev/kafein/multiduels/common/redis/codec/Decoder.java", "snippet": "public interface Decoder<T> {\n default T decode(@NotNull String payload) {\n return decode(GsonProvider.getGson().fromJson(payload, JsonObject.class));\n }\n\n T decode(@NotNull JsonObject payload);\n\n String encode(@NotNull T payload);\n}" }, { "identifier": "DecoderCollection", "path": "common/src/main/java/dev/kafein/multiduels/common/redis/codec/DecoderCollection.java", "snippet": "public final class DecoderCollection {\n private static final DecoderCollection DEFAULTS;\n\n static {\n DEFAULTS = DecoderCollection.newBuilder()\n .build();\n }\n\n private final Map<Class<?>, Decoder<?>> decoders;\n\n public DecoderCollection() {\n this(DecoderCollection.DEFAULTS);\n }\n\n public DecoderCollection(DecoderCollection collection) {\n this(collection.getDecoders());\n }\n\n public DecoderCollection(Map<Class<?>, Decoder<?>> decoders) {\n this.decoders = decoders;\n }\n\n public Map<Class<?>, Decoder<?>> getDecoders() {\n return this.decoders;\n }\n\n public Set<Class<?>> getKeys() {\n return this.decoders.keySet();\n }\n\n @SuppressWarnings(\"unchecked\")\n public <T> Decoder<T> getDecoder(@NotNull Class<?> type) {\n return (Decoder<T>) this.decoders.get(type);\n }\n\n public boolean isRegistered(@NotNull Class<?> type) {\n return this.decoders.containsKey(type);\n }\n\n public <T> void registerDecoder(@NotNull Class<T> type, @NotNull Decoder<T> decoder) {\n this.decoders.put(type, decoder);\n }\n\n public void unregisterDecoder(@NotNull Class<?> type) {\n this.decoders.remove(type);\n }\n\n @NotNull\n public static Builder newBuilder() {\n return new Builder();\n }\n\n public static final class Builder {\n private final Map<Class<?>, Decoder<?>> decoders;\n\n private Builder() {\n this.decoders = Maps.newHashMap();\n }\n\n public Builder registerDecoder(@NotNull Class<?> type, @NotNull Decoder<?> decoder) {\n this.decoders.put(type, decoder);\n return this;\n }\n\n public Builder unregisterDecoder(@NotNull Class<?> type) {\n this.decoders.remove(type);\n return this;\n }\n\n public DecoderCollection build() {\n return new DecoderCollection(this.decoders);\n }\n }\n}" }, { "identifier": "Message", "path": "common/src/main/java/dev/kafein/multiduels/common/redis/message/Message.java", "snippet": "public final class Message {\n private final String channel;\n private final @Nullable String key;\n private final String payload;\n\n public Message(String channel, @Nullable String key, String payload) {\n this.channel = channel;\n this.key = key;\n this.payload = payload;\n }\n\n @NotNull\n public static Message create(@NotNull String channel, @NotNull String payload) {\n return new Message(channel, null, payload);\n }\n\n @NotNull\n public static Message create(@NotNull String channel, @Nullable String key, @NotNull String payload) {\n return new Message(channel, key, payload);\n }\n\n public String getChannel() {\n return this.channel;\n }\n\n public @Nullable String getKey() {\n return this.key;\n }\n\n public String getPayload() {\n return this.payload;\n }\n}" }, { "identifier": "MessageListener", "path": "common/src/main/java/dev/kafein/multiduels/common/redis/message/MessageListener.java", "snippet": "@FunctionalInterface\npublic interface MessageListener {\n void onMessage(@NotNull RedisClient client, @NotNull JsonObject message);\n}" } ]
import org.jetbrains.annotations.Nullable; import redis.clients.jedis.JedisPool; import java.util.Map; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import com.google.common.util.concurrent.ThreadFactoryBuilder; import dev.kafein.multiduels.common.redis.codec.Decoder; import dev.kafein.multiduels.common.redis.codec.DecoderCollection; import dev.kafein.multiduels.common.redis.message.Message; import dev.kafein.multiduels.common.redis.message.MessageListener; import org.jetbrains.annotations.NotNull;
1,545
/* * MIT License * * Copyright (c) 2023 Kafein * * 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 dev.kafein.multiduels.common.redis; public final class RedisClient { private final RedisCredentials credentials; private final RedisCache cache; private final RedisOperations operations; private final DecoderCollection decoders; private final ExecutorService executorService; private JedisPool jedisPool; private boolean closed; public RedisClient(RedisCredentials credentials) { this.credentials = credentials; this.cache = new RedisCache(this); this.operations = new RedisOperations(this); this.decoders = new DecoderCollection(); this.executorService = Executors.newSingleThreadExecutor(new ThreadFactoryBuilder() .setNameFormat("multiduels-redis-%d") .setDaemon(true) .build()); } public RedisCredentials getCredentials() { return this.credentials; } public void connect() { this.jedisPool = RedisConnector.connect(this.credentials); } public void disconnect() { this.closed = true; this.operations.unsubscribeAll(); this.jedisPool.close(); } public JedisPool getJedisPool() { return this.jedisPool; } public boolean isClosed() { return this.closed; } public RedisCache getCache() { return this.cache; } public RedisOperations getOperations() { return this.operations; }
/* * MIT License * * Copyright (c) 2023 Kafein * * 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 dev.kafein.multiduels.common.redis; public final class RedisClient { private final RedisCredentials credentials; private final RedisCache cache; private final RedisOperations operations; private final DecoderCollection decoders; private final ExecutorService executorService; private JedisPool jedisPool; private boolean closed; public RedisClient(RedisCredentials credentials) { this.credentials = credentials; this.cache = new RedisCache(this); this.operations = new RedisOperations(this); this.decoders = new DecoderCollection(); this.executorService = Executors.newSingleThreadExecutor(new ThreadFactoryBuilder() .setNameFormat("multiduels-redis-%d") .setDaemon(true) .build()); } public RedisCredentials getCredentials() { return this.credentials; } public void connect() { this.jedisPool = RedisConnector.connect(this.credentials); } public void disconnect() { this.closed = true; this.operations.unsubscribeAll(); this.jedisPool.close(); } public JedisPool getJedisPool() { return this.jedisPool; } public boolean isClosed() { return this.closed; } public RedisCache getCache() { return this.cache; } public RedisOperations getOperations() { return this.operations; }
public <T> void publish(@NotNull String channel, @NotNull Message message) {
2
2023-10-31 10:55:38+00:00
2k
Mopheshi/BusTicketingSystem
src/main/java/morpheus/softwares/busticketingsystem/resources/TicketResource.java
[ { "identifier": "TicketService", "path": "src/main/java/morpheus/softwares/busticketingsystem/services/TicketService.java", "snippet": "@Stateless\npublic class TicketService {\n\n @PersistenceContext\n private EntityManager entityManager;\n\n public Ticket bookTicket(long routeId, String passengerName) {\n Route route = entityManager.find(Route.class, routeId);\n if (route != null) {\n Ticket ticket = new Ticket();\n ticket.setRoute(route);\n ticket.setPassengerName(passengerName);\n ticket.setBookingTime(new Date());\n entityManager.persist(ticket);\n\n return ticket;\n }\n\n return null;\n }\n\n public List<Ticket> getTicketsForRoute(long routeId) {\n TypedQuery<Ticket> typedQuery = entityManager.createQuery(\n \"SELECT t FROM Ticket t WHERE t.route.id = :routeId\", Ticket.class\n );\n typedQuery.setParameter(\"routeId\", routeId);\n\n return typedQuery.getResultList();\n }\n}" }, { "identifier": "Ticket", "path": "src/main/java/morpheus/softwares/busticketingsystem/tools/Ticket.java", "snippet": "@Entity\npublic class Ticket {\n\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private Long id;\n private String passengerName;\n private String ticketStatus;\n private Date bookingTime;\n private int seatNumber;\n\n @ManyToOne\n @JoinColumn(name = \"route_id\")\n private Route route;\n\n public Ticket() {\n }\n\n public Ticket(Long id, String passengerName, String ticketStatus, Date bookingTime, int seatNumber, Route route) {\n setId(id);\n setPassengerName(passengerName);\n setTicketStatus(ticketStatus);\n setBookingTime(bookingTime);\n setSeatNumber(seatNumber);\n setRoute(route);\n }\n\n public Long getId() {\n return id;\n }\n\n public void setId(Long id) {\n this.id = id;\n }\n\n public String getPassengerName() {\n return passengerName;\n }\n\n public void setPassengerName(String passengerName) {\n this.passengerName = passengerName;\n }\n\n public String getTicketStatus() {\n return ticketStatus;\n }\n\n public void setTicketStatus(String ticketStatus) {\n this.ticketStatus = ticketStatus;\n }\n\n public Date getBookingTime() {\n return bookingTime;\n }\n\n public void setBookingTime(Date bookingTime) {\n this.bookingTime = bookingTime;\n }\n\n public int getSeatNumber() {\n return seatNumber;\n }\n\n public void setSeatNumber(int seatNumber) {\n this.seatNumber = seatNumber;\n }\n\n public Route getRoute() {\n return route;\n }\n\n public void setRoute(Route route) {\n this.route = route;\n }\n}" } ]
import jakarta.ejb.EJB; import jakarta.ws.rs.Consumes; import jakarta.ws.rs.POST; import jakarta.ws.rs.Path; import jakarta.ws.rs.Produces; import jakarta.ws.rs.core.MediaType; import jakarta.ws.rs.core.Response; import morpheus.softwares.busticketingsystem.services.TicketService; import morpheus.softwares.busticketingsystem.tools.Ticket;
851
package morpheus.softwares.busticketingsystem.resources; /** * * @author MOPHE */ @Path("/tickets") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public class TicketResource { @EJB
package morpheus.softwares.busticketingsystem.resources; /** * * @author MOPHE */ @Path("/tickets") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public class TicketResource { @EJB
private TicketService ticketService;
0
2023-10-31 00:35:21+00:00
2k
aerospike/graph-synth
graph-synth/src/main/java/com/aerospike/graph/synth/util/tinkerpop/SchemaGraphUtil.java
[ { "identifier": "SchemaBuilder", "path": "graph-synth/src/main/java/com/aerospike/graph/synth/emitter/generator/schema/SchemaBuilder.java", "snippet": "public class SchemaBuilder {\n public static class Keys {\n public static final String VERTEX_TYPE = \"vertexType\";\n public static final String CHANCES_TO_CREATE = \"create.chances\";\n public static final String LIKELIHOOD = \"likelihood\";\n public static final String VALUE_GENERATOR_IMPL = \"value.generator.impl\";\n public static final String VALUE_GENERATOR_ARGS = \"value.generator.args\";\n public static final String ENTRYPOINT = \"entrypoint\";\n public static final String EDGE_TYPE = \"edgeType\";\n public static final String OUT_VERTEX_DISTRIBUTION = \"outVertexDistribution\";\n public static final String IN_VERTEX_DISTRIBUTION = \"inVertexDistribution\";\n }\n\n final Set<VertexSchema> vertexTypes;\n final Set<EdgeSchema> edgeTypes;\n\n public SchemaBuilder withVertexType(VertexSchema vertexSchema) {\n this.pushVertexSchema(vertexSchema);\n return this;\n }\n\n private SchemaBuilder() {\n this.vertexTypes = new HashSet<>();\n this.edgeTypes = new HashSet<>();\n }\n\n public static SchemaBuilder create() {\n return new SchemaBuilder();\n }\n\n private void pushVertexSchema(final VertexSchema vertexSchema) {\n vertexTypes.add(vertexSchema);\n }\n\n public SchemaBuilder withEdgeType(EdgeSchema edgeSchema) {\n this.pushEdgeSchema(edgeSchema);\n return this;\n }\n\n private void pushEdgeSchema(final EdgeSchema edgeSchema) {\n edgeTypes.add(edgeSchema);\n }\n\n public GraphSchema build(final List<RootVertexSpec> entrypointSpecs) {\n return build(entrypointSpecs.toArray(RootVertexSpec[]::new));\n }\n\n public GraphSchema build(final RootVertexSpec... entrypointSpecs) {\n final GraphSchema schema = new GraphSchema();\n schema.vertexTypes = new ArrayList<>(vertexTypes);\n schema.edgeTypes = new ArrayList<>(edgeTypes);\n schema.rootVertexTypes = Arrays.asList(entrypointSpecs);\n return schema;\n }\n}" }, { "identifier": "GraphSchema", "path": "graph-synth/src/main/java/com/aerospike/graph/synth/emitter/generator/schema/definition/GraphSchema.java", "snippet": "public class GraphSchema {\n public List<EdgeSchema> edgeTypes;\n public List<VertexSchema> vertexTypes;\n public List<RootVertexSpec> rootVertexTypes;\n public JoiningConfig joining;\n\n @Override\n public boolean equals(Object o) {\n if (!GraphSchema.class.isAssignableFrom(o.getClass()))\n return false;\n final GraphSchema other = (GraphSchema) o;\n for (final EdgeSchema e : edgeTypes) {\n final Iterator<EdgeSchema> i = other.edgeTypes.stream()\n .filter(it -> it.label().equals(e.label())).iterator();\n if (!i.hasNext())\n return false;\n if (!i.next().equals(e))\n return false;\n }\n for (final VertexSchema v : vertexTypes) {\n final Iterator<VertexSchema> i = other.vertexTypes.stream()\n .filter(it -> it.label().equals(v.label())).iterator();\n if (!i.hasNext())\n return false;\n if (!i.next().equals(v))\n return false;\n }\n for (final RootVertexSpec rvs : rootVertexTypes) {\n final Iterator<RootVertexSpec> i = other.rootVertexTypes.stream()\n .filter(it -> it.name.equals(rvs.name)).iterator();\n if (!i.hasNext())\n return false;\n if (!i.next().equals(rvs))\n return false;\n }\n return true;\n }\n}" }, { "identifier": "RootVertexSpec", "path": "graph-synth/src/main/java/com/aerospike/graph/synth/emitter/generator/schema/definition/RootVertexSpec.java", "snippet": "public class RootVertexSpec {\n public String name;\n public Double likelihood;\n public Integer chancesToCreate;\n\n public VertexSchema toVertexSchema(GraphSchema schema) {\n return schema.vertexTypes.stream()\n .filter(vertexSchema -> vertexSchema.name.equals(name)).findFirst()\n .orElseThrow(() -> new RuntimeException(\"No vertex type found for \" + name));\n }\n\n @Override\n public boolean equals(Object o){\n if (!RootVertexSpec.class.isAssignableFrom(o.getClass()))\n return false;\n RootVertexSpec other = (RootVertexSpec) o;\n if (!name.equals(other.name))\n return false;\n if (!likelihood.equals(other.likelihood))\n return false;\n if (!chancesToCreate.equals(other.chancesToCreate))\n return false;\n return true;\n }\n}" } ]
import com.aerospike.graph.synth.emitter.generator.schema.SchemaBuilder; import com.aerospike.graph.synth.emitter.generator.schema.definition.GraphSchema; import com.aerospike.graph.synth.emitter.generator.schema.definition.RootVertexSpec; import org.apache.tinkerpop.gremlin.structure.Edge; import org.apache.tinkerpop.gremlin.structure.Graph; import org.apache.tinkerpop.gremlin.structure.T; import org.apache.tinkerpop.gremlin.structure.Vertex; import java.util.HashMap; import java.util.Map; import static com.aerospike.movement.util.core.configuration.ConfigurationUtil.subKey;
1,320
/* * @author Grant Haywood <grant.haywood@aerospike.com> * Developed May 2023 - Oct 2023 * Copyright (c) 2023 Aerospike Inc. */ package com.aerospike.graph.synth.util.tinkerpop; /* Created by Grant Haywood grant@iowntheinter.net 7/17/23 */ public class SchemaGraphUtil { public static void writeToGraph(final Graph graph, final GraphSchema graphSchema) {
/* * @author Grant Haywood <grant.haywood@aerospike.com> * Developed May 2023 - Oct 2023 * Copyright (c) 2023 Aerospike Inc. */ package com.aerospike.graph.synth.util.tinkerpop; /* Created by Grant Haywood grant@iowntheinter.net 7/17/23 */ public class SchemaGraphUtil { public static void writeToGraph(final Graph graph, final GraphSchema graphSchema) {
final Map<String, RootVertexSpec> rootVertexSpecMap = new HashMap<>();
2
2023-10-27 22:54:12+00:00
2k
SUFIAG/ATM-Machine-Using-Java
source-code/src/dataLayer/writerAndReaderTest.java
[ { "identifier": "Amount", "path": "source-code/src/logicLayer/Amount.java", "snippet": "public class Amount {\n private int totalAmount, fiftyNotes, twentyNotes, tenNotes, fiveNotes;\n\n // constructor\n public Amount() {}\n\n public Amount(int totalAmount, int fiftyNotes, int twentyNotes, int tenNotes, int fiveNotes) {\n this.totalAmount = totalAmount;\n this.fiftyNotes = fiftyNotes;\n this.twentyNotes = twentyNotes;\n this.tenNotes = tenNotes;\n this.fiveNotes = fiveNotes;\n }\n\n // getters\n public int getFiftyNotes() {return fiftyNotes;}\n public int getFiveNotes() {return fiveNotes;}\n public int getTenNotes() {return tenNotes;}\n public int getTotalAmount() {return totalAmount;}\n public int getTwentyNotes() {return twentyNotes;}\n\n // setters\n public void setFiftyNotes(int fiftyNotes) {this.fiftyNotes = fiftyNotes;}\n public void setFiveNotes(int fiveNotes) {this.fiveNotes = fiveNotes;}\n public void setTenNotes(int tenNotes) {this.tenNotes = tenNotes;}\n public void setTotalAmount(int totalAmount) {this.totalAmount = totalAmount;}\n public void setTwentyNotes(int twentyNotes) {this.twentyNotes = twentyNotes;}\n}" }, { "identifier": "User", "path": "source-code/src/logicLayer/User.java", "snippet": "public class User {\n private String accNo, pin;\n private int ID, balance, overdraft;\n\n //constructors\n public User() {\n }\n public User(int id, String accNo, String pin, int balance, int overdraft) {\n this.ID = id;\n this.accNo = accNo;\n this.pin = pin;\n this.balance = balance;\n this.overdraft = overdraft;\n }\n\n //getters\n public int getID() {\n return ID;\n }\n public String getAccNo() {return accNo;}\n public int getBalance() {return balance;}\n public int getOverdraft() {return overdraft;}\n public String getPin() {return pin;}\n\n //setters\n public void setID(int ID) {\n this.ID = ID;\n }\n public void setAccNo(String accNo) {this.accNo = accNo;}\n public void setBalance(int balance) {this.balance = balance;}\n public void setOverdraft(int overdraft) {this.overdraft = overdraft;}\n public void setPin(String pin) {this.pin = pin;}\n}" } ]
import logicLayer.Amount; import logicLayer.User; import org.junit.jupiter.api.Test; import java.util.Vector; import static org.junit.jupiter.api.Assertions.*;
693
package dataLayer; class writerAndReaderTest { private writerAndReader readAndWrite; private writerAndReaderTest() { readAndWrite = new writerAndReader(); } @Test void readUsersFromFile() {
package dataLayer; class writerAndReaderTest { private writerAndReader readAndWrite; private writerAndReaderTest() { readAndWrite = new writerAndReader(); } @Test void readUsersFromFile() {
Vector<User> users = new Vector<>();
1
2023-10-25 18:26:41+00:00
2k
Java-Game-Engine-Merger/Libgdx-Processing
framework/src/main/java/hhs/gdx/hslib/ui/Controller.java
[ { "identifier": "Resource", "path": "framework/src/main/java/hhs/gdx/hslib/tools/Resource.java", "snippet": "public class Resource implements Disposable{\n public static int width=Gdx.graphics.getWidth();\n public static int height=Gdx.graphics.getHeight();\n public static float u;\n public static Game game;\n public static HashMap<Class<?>,Screen> screens;\n public static AppRecorder recoder;\n public static SpriteBatch batch;\n public static ShapeRenderer shape;\n public static CacheRenderer cacheRender;\n public static AssetManager asset;\n public static FontManager font;\n public static JsonReader jreader;\n public static XmlReader xreader;\n public Resource(Game gameIn) {\n this.game=gameIn;\n asset=new AssetManager();\n batch=new SpriteBatch();\n shape=new ShapeRenderer();\n cacheRender=new CacheRenderer(new SpriteCache());\n recoder=new AppRecorder();\n screens=new HashMap<>();\n jreader=new JsonReader();\n xreader=new XmlReader();\n }\n public static void setScreen(Screen s) {\n game.setScreen(s);\n }\n public static <T extends BasicScreen> void setScreen(Class<T> screen) {\n Screen s;\n if((s=screens.get(screen))!=null) {\n game.setScreen(s);\n return;\n }\n try {\n s=screen.getConstructor().newInstance();\n }catch(Exception e) {\n e.printStackTrace();\n }\n game.setScreen(s);\n }\n @Override\n public void dispose() {\n asset.dispose();\n batch.dispose();\n shape.dispose();\n if(font!=null) font.dispose();\n cacheRender.dispose();\n }\n}" }, { "identifier": "TextureTool", "path": "framework/src/main/java/hhs/gdx/hslib/tools/TextureTool.java", "snippet": "public class TextureTool{\n public static TextureRegionDrawable ttd(Texture t) {\n return new TextureRegionDrawable(new TextureRegion(t));\n }\n public static TextureRegionDrawable rtd(TextureRegion tr) {\n return new TextureRegionDrawable(tr);\n }\n public static TextureRegion ttr(Texture t) {\n return new TextureRegion(t);\n }\n public static TextureRegion[] split(Texture t,int rows,int columns) {\n TextureRegion[][] atr=split_2(t,rows,columns);\n TextureRegion[] fin=new TextureRegion[atr.length*atr[0].length];\n int index=0;\n for(int i=0;i<atr.length;i++) {\n for(int j=0;j<atr[i].length;j++) {\n fin[index++]=atr[i][j];\n }\n }\n return fin;\n }\n public static TextureRegion[][] split_2(Texture t,int rows,int columns) {\n TextureRegion tr=new TextureRegion(t);\n TextureRegion[][] atr=tr.split(t.getWidth()/columns,t.getHeight()/rows);\n return atr;\n }\n}" } ]
import com.badlogic.gdx.graphics.g2d.TextureRegion; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.scenes.scene2d.ui.Touchpad; import hhs.gdx.hslib.tools.Resource; import hhs.gdx.hslib.tools.TextureTool;
777
package hhs.gdx.hslib.ui; public class Controller extends Touchpad{ TextureRegion ground,knob; Controlable control; Vector2 prence=new Vector2(); public Controller(Controlable c,TextureRegion ground,TextureRegion knob) {
package hhs.gdx.hslib.ui; public class Controller extends Touchpad{ TextureRegion ground,knob; Controlable control; Vector2 prence=new Vector2(); public Controller(Controlable c,TextureRegion ground,TextureRegion knob) {
super(50,new Touchpad.TouchpadStyle(TextureTool.rtd(ground),TextureTool.rtd(knob)));
1
2023-10-27 05:47:39+00:00
2k
llllllxy/tinycloud
tinycloud-common/src/main/java/org/tinycloud/common/exception/BusinessException.java
[ { "identifier": "ResultCode", "path": "tinycloud-common/src/main/java/org/tinycloud/common/consts/ResultCode.java", "snippet": "public enum ResultCode {\n SUCCESS(\"0\", \"成功\"),\n PARAM_ERROR(\"400\", \"参数校验失败\"),\n UNAUTHORIZED(\"401\", \"会话不存在或已失效\"),\n NOT_EXIST(\"402\", \"不存在\"),\n FORBIDDEN(\"403\", \"访问受限,无权限\"),\n RESOURCE_NOT_FOUND(\"404\", \"资源未找到\"),\n RESOURCE_METHOD_NOT_SUPPORT(\"405\", \"请求方法不支持\"),\n RESOURCE_CONFLICT(\"409\", \"资源冲突\"),\n DUPLICATE_SUBMISSIONS(\"410\", \"重复提交\"),\n REQUEST_PARAM_ERROR(\"412\", \"参数错误\"),\n PRECONDITION_FAILED(\"428\", \"要求先决条件\"),\n NOT_SUPPORT(\"429\", \"不支持的请求\"),\n ALREADY_EXECUTING(\"410\", \"程序正在执行,请稍后再试\"),\n UNKNOWN_ERROR(\"500\", \"系统未知错误\"),\n NOT_IMPLEMENTED(\"501\", \"接口暂未实现\");\n\n /**\n * 错误码\n */\n private String code;\n\n /**\n * 错误描述\n */\n private String desc;\n\n public String getCode() {\n return code;\n }\n\n public void setCode(String code) {\n this.code = code;\n }\n\n public String getDesc() {\n return desc;\n }\n\n public void setDesc(String desc) {\n this.desc = desc;\n }\n\n ResultCode(String code, String desc) {\n this.code = code;\n this.desc = desc;\n }\n\n ResultCode() {\n }\n}" }, { "identifier": "SystemCode", "path": "tinycloud-common/src/main/java/org/tinycloud/common/consts/SystemCode.java", "snippet": "public enum SystemCode {\n USER_CENTER(\"1000\", \"用户中心\"),\n AUTH_CENTER(\"2000\", \"会话中心\"),\n ABILITY_CENTER(\"3000\", \"能力中心\"),\n MESSAGE_CENTER(\"4000\", \"消息中心\"),\n JOB_CENTER(\"5000\", \"调度中心\"),\n OSS_CENTER(\"6000\", \"文件中心\"),\n GATEWAY(\"7000\", \"网关\"),\n\n SYSTEM(\"9000\", \"系统管理服务\"),\n ;\n\n private String code;\n\n private String desc;\n\n private SystemCode(String code, String desc) {\n this.code = code;\n this.desc = desc;\n }\n\n public String getCode() {\n return this.code;\n }\n\n public String getDesc() {\n return this.desc;\n }\n\n public void setCode(String code) {\n this.code = code;\n }\n\n public void setDesc(String desc) {\n this.desc = desc;\n }\n}" } ]
import org.tinycloud.common.consts.ResultCode; import org.tinycloud.common.consts.SystemCode;
1,049
package org.tinycloud.common.exception; /** * <p> * 统一业务异常封装 * </p> * * @author liuxingyu01 * @since 2023-03-07 15:47:38 */ public class BusinessException extends RuntimeException { private final String code; private final String message; private final Object errT; public String getCode() { return code; } public String getMessage() { return message; } public Object getErrT() { return errT; } private BusinessException(String code, String message, Object errT) { super(message); this.code = code; this.message = message; this.errT = errT; } private BusinessException(String code, String message) { this(code, message, null); } /** * 带系统码的异常,用来区分微服务系统 * @param systemCode 系统编码枚举 * @param code 错误码 * @param message 错误信息 */ public BusinessException(SystemCode systemCode, String code, String message) { this(systemCode.getCode() + code, message, null); } /** * 带系统码的异常,用来区分微服务系统 * @param systemCode 系统编码枚举 * @param code 错误码 */
package org.tinycloud.common.exception; /** * <p> * 统一业务异常封装 * </p> * * @author liuxingyu01 * @since 2023-03-07 15:47:38 */ public class BusinessException extends RuntimeException { private final String code; private final String message; private final Object errT; public String getCode() { return code; } public String getMessage() { return message; } public Object getErrT() { return errT; } private BusinessException(String code, String message, Object errT) { super(message); this.code = code; this.message = message; this.errT = errT; } private BusinessException(String code, String message) { this(code, message, null); } /** * 带系统码的异常,用来区分微服务系统 * @param systemCode 系统编码枚举 * @param code 错误码 * @param message 错误信息 */ public BusinessException(SystemCode systemCode, String code, String message) { this(systemCode.getCode() + code, message, null); } /** * 带系统码的异常,用来区分微服务系统 * @param systemCode 系统编码枚举 * @param code 错误码 */
public BusinessException(SystemCode systemCode, ResultCode code) {
0
2023-10-28 02:05:15+00:00
2k
AysuCgs/JavaMicroservices
ElasticService/src/main/java/com/aysu/service/UserProfileService.java
[ { "identifier": "UserProfileSaveRequestDto", "path": "AuthService/src/main/java/com/aysu/dto/request/UserProfileSaveRequestDto.java", "snippet": "@Data\n@AllArgsConstructor\n@NoArgsConstructor\n@Builder\npublic class UserProfileSaveRequestDto {\n\n private Long authid;\n private String username;\n private String email;\n\n}" }, { "identifier": "IUserProfileMapper", "path": "ElasticService/src/main/java/com/aysu/mapper/IUserProfileMapper.java", "snippet": "@Mapper(componentModel = \"spring\", unmappedTargetPolicy = ReportingPolicy.IGNORE)\npublic interface IUserProfileMapper {\n\n IUserProfileMapper INSTANCE= Mappers.getMapper(IUserProfileMapper.class);\n\n @Mapping(source = \"id\",target = \"userProfileId\")\n UserProfile toUserProfile(final UserProfileSaveRequestDto dto);\n\n\n\n}" }, { "identifier": "IUserProfileRepository", "path": "ElasticService/src/main/java/com/aysu/repository/IUserProfileRepository.java", "snippet": "@Repository\npublic interface IUserProfileRepository extends ElasticsearchRepository<UserProfile, Long> {\n\n boolean existsUserProfileById(Long id);\n}" }, { "identifier": "UserProfile", "path": "ElasticService/src/main/java/com/aysu/repository/entity/UserProfile.java", "snippet": "@Builder // bir sınıftan nesne türetmeyi sağlar.\n@Data //get set metodlarını otomatik tanımlar.\n@NoArgsConstructor //boş constructor oluşturur.\n@AllArgsConstructor //dolu constructor oluşturur.\n@ToString\n@Document(indexName = \"tbl_user_profile\")\npublic class UserProfile {\n\n @Id\n private Long id;\n private Long userProfileId;\n private Long authid;\n private String username;\n private String email;\n\n private String ad;\n private String address;\n private String phone;\n private String avatar;\n\n private Long createAt;\n private boolean state;\n\n}" }, { "identifier": "ServiceManager", "path": "AuthService/src/main/java/com/aysu/utility/ServiceManager.java", "snippet": "public class ServiceManager<T,ID> implements IService<T,ID>{\n\n private final JpaRepository<T,ID> repository;\n public ServiceManager(JpaRepository<T, ID> repository) {\n this.repository = repository;\n }\n\n @Override\n public T save(T t) {\n return repository.save(t);\n }\n @Override\n public Iterable<T> saveAll(Iterable<T> t) {\n return repository.saveAll(t);\n }\n\n @Override\n public T update(T t) {\n return repository.save(t);\n }\n\n @Override\n public void delete(T t) {\n repository.delete(t);\n }\n @Override\n public void deleteById(ID id) {\n repository.deleteById(id);\n }\n\n @Override\n public Optional<T> findById(ID id) {\n return repository.findById(id);\n }\n @Override\n public List<T> findAll() {\n return repository.findAll();\n }\n\n}" } ]
import com.aysu.dto.request.UserProfileSaveRequestDto; import com.aysu.mapper.IUserProfileMapper; import com.aysu.repository.IUserProfileRepository; import com.aysu.repository.entity.UserProfile; import com.aysu.utility.ServiceManager; import org.springframework.stereotype.Service;
757
package com.aysu.service; @Service public class UserProfileService extends ServiceManager<UserProfile, Long> {
package com.aysu.service; @Service public class UserProfileService extends ServiceManager<UserProfile, Long> {
private final IUserProfileRepository iUserProfileRepository;
2
2023-10-27 19:48:42+00:00
2k
llllllxy/bluewind-base
src/main/java/com/bluewind/base/common/config/GlobalExceptionHandler.java
[ { "identifier": "Result", "path": "src/main/java/com/bluewind/base/common/base/Result.java", "snippet": "public class Result implements Serializable {\n private static final long serialVersionUID = -1491499610244557029L;\n\n private Integer code;\n\n private String msg;\n\n private Object data;\n\n public Integer getCode() {\n return code;\n }\n\n public void setCode(Integer code) {\n this.code = code;\n }\n\n public String getMsg() {\n return msg;\n }\n\n public void setMsg(String msg) {\n this.msg = msg;\n }\n\n public Object getData() {\n return data;\n }\n\n public void setData(Object data) {\n this.data = data;\n }\n\n public Result(Integer code, String msg) {\n this.code = code;\n this.msg = msg;\n }\n\n public Result(Integer code, String msg, Object data) {\n this.code = code;\n this.msg = msg;\n this.data = data;\n }\n\n public static Result ok(String msg, Object data) {\n return new Result(HttpStatus.SUCCESS, msg, data);\n }\n\n public static Result ok(String msg) {\n return new Result(HttpStatus.SUCCESS, msg, null);\n }\n\n public static Result error(String msg) {\n return new Result(HttpStatus.ERROR, msg);\n }\n\n public static Result create(Integer code, String msg, Object data) {\n return new Result(code, msg, data);\n }\n\n public static Result create(Integer code, String msg) {\n return new Result(code, msg);\n }\n\n}" }, { "identifier": "HttpStatus", "path": "src/main/java/com/bluewind/base/common/consts/HttpStatus.java", "snippet": "public class HttpStatus {\n /**\n * 操作成功\n */\n public static final int SUCCESS = 200;\n\n /**\n * 对象创建成功\n */\n public static final int CREATED = 201;\n\n /**\n * 请求已经被接受\n */\n public static final int ACCEPTED = 202;\n\n /**\n * 操作已经执行成功,但是没有返回数据\n */\n public static final int NO_CONTENT = 204;\n\n /**\n * 资源已被移除\n */\n public static final int MOVED_PERM = 301;\n\n /**\n * 重定向\n */\n public static final int SEE_OTHER = 303;\n\n /**\n * 资源没有被修改\n */\n public static final int NOT_MODIFIED = 304;\n\n /**\n * 参数列表错误(缺少,格式不匹配)\n */\n public static final int BAD_REQUEST = 400;\n\n /**\n * 未授权\n */\n public static final int UNAUTHORIZED = 401;\n\n /**\n * 访问受限,授权过期\n */\n public static final int FORBIDDEN = 403;\n\n /**\n * 资源,服务未找到\n */\n public static final int NOT_FOUND = 404;\n\n /**\n * 不允许的http方法\n */\n public static final int BAD_METHOD = 405;\n\n /**\n * 资源冲突,或者资源被锁\n */\n public static final int CONFLICT = 409;\n\n /**\n * 不支持的数据,媒体类型\n */\n public static final int UNSUPPORTED_TYPE = 415;\n\n /**\n * 系统内部错误\n */\n public static final int ERROR = 500;\n\n /**\n * 接口未实现\n */\n public static final int NOT_IMPLEMENTED = 501;\n}" } ]
import com.bluewind.base.common.base.Result; import com.bluewind.base.common.consts.HttpStatus; import org.apache.shiro.authc.AuthenticationException; import org.apache.shiro.authz.AuthorizationException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice;
1,117
package com.bluewind.base.common.config; /** * @author liuxingyu01 * @date 2022-08-27 12:38 * @description 全局异常处理 **/ @RestControllerAdvice public class GlobalExceptionHandler { private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class); @ExceptionHandler(RuntimeException.class) public Result handleRuntimeException(Exception e) { logger.error("GlobalExceptionHandler -- RuntimeException = {e}", e);
package com.bluewind.base.common.config; /** * @author liuxingyu01 * @date 2022-08-27 12:38 * @description 全局异常处理 **/ @RestControllerAdvice public class GlobalExceptionHandler { private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class); @ExceptionHandler(RuntimeException.class) public Result handleRuntimeException(Exception e) { logger.error("GlobalExceptionHandler -- RuntimeException = {e}", e);
return Result.create(HttpStatus.ERROR, e.getMessage());
1
2023-10-26 10:02:07+00:00
2k
oehf/xds-registry-to-fhir
src/main/java/org/openehealth/app/xdstofhir/registry/common/mapper/XdsToFhirFolderMapper.java
[ { "identifier": "MappingSupport", "path": "src/main/java/org/openehealth/app/xdstofhir/registry/common/MappingSupport.java", "snippet": "@UtilityClass\npublic class MappingSupport {\n public static final String OID_URN = \"urn:oid:\";\n public static final String UUID_URN = \"urn:uuid:\";\n public static final String XDS_URN = \"urn:ihe:xds:\";\n public static final String URI_URN = \"urn:ietf:rfc:3986\";\n public static final String MHD_COMPREHENSIVE_PROFILE = \"https://profiles.ihe.net/ITI/MHD/StructureDefinition/IHE.MHD.Comprehensive.DocumentReference\";\n public static final String MHD_COMPREHENSIVE_SUBMISSIONSET_PROFILE = \"https://profiles.ihe.net/ITI/MHD/StructureDefinition/IHE.MHD.Comprehensive.SubmissionSet\";\n public static final String MHD_COMPREHENSIVE_FOLDER_PROFILE = \"https://profiles.ihe.net/ITI/MHD/StructureDefinition/IHE.MHD.Comprehensive.Folder\";\n\n public static final Map<Precision, TemporalPrecisionEnum> PRECISION_MAP_FROM_XDS = new EnumMap<>(\n Map.of(Precision.DAY, TemporalPrecisionEnum.DAY,\n Precision.HOUR, TemporalPrecisionEnum.SECOND,\n Precision.MINUTE, TemporalPrecisionEnum.SECOND,\n Precision.MONTH, TemporalPrecisionEnum.MONTH,\n Precision.SECOND, TemporalPrecisionEnum.SECOND,\n Precision.YEAR, TemporalPrecisionEnum.YEAR));\n public static final Map<TemporalPrecisionEnum, Precision> PRECISION_MAP_FROM_FHIR = PRECISION_MAP_FROM_XDS\n .entrySet().stream()\n .collect(Collectors.toMap(Map.Entry::getValue, Map.Entry::getKey, (x, y) -> y, LinkedHashMap::new));\n\n public static final Map<AssociationType, DocumentRelationshipType> DOC_DOC_FHIR_ASSOCIATIONS = new EnumMap<>(\n Map.of(AssociationType.APPEND, DocumentRelationshipType.APPENDS,\n AssociationType.REPLACE, DocumentRelationshipType.REPLACES,\n AssociationType.SIGNS, DocumentRelationshipType.SIGNS,\n AssociationType.TRANSFORM, DocumentRelationshipType.TRANSFORMS));\n\n public static final Map<DocumentRelationshipType, AssociationType> DOC_DOC_XDS_ASSOCIATIONS = DOC_DOC_FHIR_ASSOCIATIONS\n .entrySet().stream()\n .collect(Collectors.toMap(Map.Entry::getValue, Map.Entry::getKey, (x, y) -> y, LinkedHashMap::new));\n\n\n public static final Map<AvailabilityStatus, DocumentReferenceStatus> STATUS_MAPPING_FROM_XDS = new EnumMap<>(\n Map.of(AvailabilityStatus.APPROVED, DocumentReferenceStatus.CURRENT,\n AvailabilityStatus.DEPRECATED, DocumentReferenceStatus.SUPERSEDED));\n public static final Map<DocumentReferenceStatus, AvailabilityStatus> STATUS_MAPPING_FROM_FHIR = STATUS_MAPPING_FROM_XDS\n .entrySet().stream()\n .collect(Collectors.toMap(Map.Entry::getValue, Map.Entry::getKey, (x, y) -> y, LinkedHashMap::new));\n\n\n public static String toUrnCoded(String value) {\n String adaptedValue = value;\n try {\n URN.create(adaptedValue);\n } catch (URISyntaxException invalidUrn) {\n try {\n new Oid(value);\n adaptedValue = OID_URN + value;\n } catch (GSSException invalidOid) {\n try {\n UUID.fromString(value);\n adaptedValue = OID_URN + value;\n } catch (IllegalArgumentException invalidUuid) {\n adaptedValue = XDS_URN + value;\n }\n }\n }\n return adaptedValue;\n }\n\n public static String urnDecodedScheme(String urnCodedSystem) {\n return urnCodedSystem\n .replace(OID_URN, \"\")\n .replace(UUID_URN, \"\")\n .replace(XDS_URN, \"\");\n }\n\n}" }, { "identifier": "MhdFolder", "path": "src/main/java/org/openehealth/app/xdstofhir/registry/common/fhir/MhdFolder.java", "snippet": "@ResourceDef(name = \"List\", profile = MappingSupport.MHD_COMPREHENSIVE_FOLDER_PROFILE)\npublic class MhdFolder extends ListResource {\n private static final long serialVersionUID = 6730967324453182475L;\n\n public static final CodeableConcept FOLDER_CODEING = new CodeableConcept(\n new Coding(\"https://profiles.ihe.net/ITI/MHD/CodeSystem/MHDlistTypes\", \"folder\",\n \"Folder as a FHIR List\"));\n\n public MhdFolder() {\n super();\n setCode(FOLDER_CODEING);\n setStatus(ListStatus.CURRENT);\n setMode(ListMode.WORKING);\n }\n\n @Child(name = \"designationType\", type = {CodeableConcept.class}, order=1, min=1, max=Child.MAX_UNLIMITED, modifier=false, summary=false)\n @Extension(url = \"https://profiles.ihe.net/ITI/MHD/StructureDefinition/ihe-designationType\", definedLocally = false, isModifier = false)\n @Description(shortDefinition = \"Clinical code of the List\")\n @Getter @Setter\n private List<CodeableConcept> designationType;\n\n}" } ]
import java.util.Collections; import java.util.Date; import java.util.List; import java.util.function.BiFunction; import lombok.RequiredArgsConstructor; import org.hl7.fhir.r4.model.Annotation; import org.hl7.fhir.r4.model.Identifier; import org.hl7.fhir.r4.model.ListResource.ListEntryComponent; import org.openehealth.app.xdstofhir.registry.common.MappingSupport; import org.openehealth.app.xdstofhir.registry.common.fhir.MhdFolder; import org.openehealth.ipf.commons.ihe.xds.core.metadata.Folder; import org.springframework.stereotype.Component;
1,457
package org.openehealth.app.xdstofhir.registry.common.mapper; @Component @RequiredArgsConstructor public class XdsToFhirFolderMapper extends AbstractXdsToFhirMapper implements BiFunction<Folder, List<ListEntryComponent>, MhdFolder> { @Override public MhdFolder apply(Folder xdFolder, List<ListEntryComponent> references) { var mhdList = new MhdFolder(); mhdList.setId(xdFolder.getEntryUuid()); mhdList.addIdentifier(fromIdentifier(xdFolder.getEntryUuid(), Identifier.IdentifierUse.OFFICIAL)); mhdList.addIdentifier(
package org.openehealth.app.xdstofhir.registry.common.mapper; @Component @RequiredArgsConstructor public class XdsToFhirFolderMapper extends AbstractXdsToFhirMapper implements BiFunction<Folder, List<ListEntryComponent>, MhdFolder> { @Override public MhdFolder apply(Folder xdFolder, List<ListEntryComponent> references) { var mhdList = new MhdFolder(); mhdList.setId(xdFolder.getEntryUuid()); mhdList.addIdentifier(fromIdentifier(xdFolder.getEntryUuid(), Identifier.IdentifierUse.OFFICIAL)); mhdList.addIdentifier(
fromIdentifier(MappingSupport.OID_URN + xdFolder.getUniqueId(), Identifier.IdentifierUse.USUAL));
0
2023-10-30 18:58:31+00:00
2k
SUFIAG/Issue-Tracking-Application-Java
source-code/src/main/java/presentationLayer/EditInformation.java
[ { "identifier": "ITS", "path": "source-code/src/main/java/logicLayer/ITS.java", "snippet": "public class ITS {\n private writerAndReader readAndWrite;\n private Vector<Issue> issues;\n private static ITS instance;\n\n //constructor\n private ITS() {\n //initializing data members\n readAndWrite = new writerAndReader();\n issues = new Vector<>();\n\n //initializing issues from file\n try {\n File myObj = new File(\"./IssuesTrackingSystem/src/main/java/dataLayer/issues.csv\");\n if (!myObj.createNewFile()) { //if file has already created\n readAndWrite.readIssuesFromFile(issues);\n } else {\n readAndWrite.writeHeadersInFile();\n }\n } catch (Exception e) {\n System.err.println(\"Error: \" + e.getMessage());\n }\n }\n\n //getters\n public writerAndReader getReadAndWrite() {\n return readAndWrite;\n }\n public Vector<Issue> getIssues() {return issues;}\n\n //setters\n public void setReadAndWrite(writerAndReader readAndWrite) {\n this.readAndWrite = readAndWrite;\n }\n public void setIssues(Vector<Issue> issues) {this.issues = issues;}\n\n //function to get instance of this class\n public static ITS getInstance(){\n if (instance == null) {\n instance = new ITS();\n }\n return instance;\n }\n\n //function to check if the issue exists or not\n public boolean validateIssueID(String ID) {\n for (Issue issue : issues) {\n if (Integer.parseInt(ID) == issue.getID()) {\n return true;\n }\n }\n return false;\n }\n\n //function for adding issue\n public void addIssue(String desc, String assignee, String status, String creationDate) {\n int ID = 0;\n\n //getting maximum ID\n for (Issue issue : issues) {\n if (issue.getID() > ID) {\n ID = issue.getID();\n }\n }\n ID++;\n\n //adding issue\n Issue i = new Issue(ID, desc, assignee, status, creationDate);\n issues.add(i);\n readAndWrite.writeIssueIntoFile(i);\n }\n\n //function for editing Issue\n public void editIssue(String ID, String desc, String assignee, String status, String creationDate){\n for (int i = 0; i < issues.size(); ++i) {\n if (Integer.parseInt(ID) == issues.get(i).getID()) {\n issues.set(i, new Issue(issues.get(i).getID(), desc, assignee, status, creationDate));\n }\n }\n readAndWrite.truncateAFile(\"./IssuesTrackingSystem/src/main/java/dataLayer/issues.csv\");\n readAndWrite.writeHeadersInFile();\n for (Issue issue : issues) {\n readAndWrite.writeIssueIntoFile(issue);\n }\n }\n\n //function for deleting issue\n public void deleteIssue(String ID) {\n int index = -1;\n for(int i = 0; i < issues.size(); ++i){\n //Replacing IDs and Also Finding Index to Delete\n if (Integer.parseInt(ID) == issues.get(i).getID()){\n index = i;\n if (i == 0) {\n issues.get(i).setID(0);\n } else if (i == issues.size() - 1) {\n break;\n } else {\n issues.get(i).setID(issues.get(i).getID() - 1);\n }\n } else if(index != -1){\n issues.get(i).setID(issues.get(i - 1).getID() + 1);\n }\n }\n issues.remove(index); //Removing issue From Vector\n readAndWrite.truncateAFile(\"./IssuesTrackingSystem/src/main/java/dataLayer/issues.csv\");\n readAndWrite.writeHeadersInFile();\n for (Issue issue : issues) {\n readAndWrite.writeIssueIntoFile(issue);\n }\n }\n\n // function for searching issue\n public Issue searchIssue(String ID){\n for (Issue issue : issues) {\n if (Integer.parseInt(ID) == issue.getID()) {\n return issue;\n }\n }\n return null;\n }\n}" }, { "identifier": "Issue", "path": "source-code/src/main/java/logicLayer/Issue.java", "snippet": "public class Issue {\n private String desc, assignee, status, creationDate;\n private int ID;\n\n //constructors\n public Issue(){}\n public Issue(int ID, String desc, String assignee, String status, String creationDate) {\n this.ID = ID;\n this.desc = desc;\n this.assignee = assignee;\n this.status = status;\n this.creationDate = creationDate;\n }\n\n //getters\n public int getID() {return ID;}\n public String getAssignee() {return assignee;}\n public String getCreationDate() {return creationDate;}\n public String getDesc() {return desc;}\n public String getStatus() {return status;}\n\n //setters\n public void setAssignee(String assignee) {this.assignee = assignee;}\n public void setCreationDate(String creationDate) {this.creationDate = creationDate;}\n public void setDesc(String desc) {this.desc = desc;}\n public void setID(int ID) {this.ID = ID;}\n public void setStatus(String status) {this.status = status;}\n}" } ]
import logicLayer.Issue; import logicLayer.ITS;
1,384
/* * 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 presentationLayer; /** * * @author SA */ public class EditInformation extends javax.swing.JFrame { private String ID;
/* * 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 presentationLayer; /** * * @author SA */ public class EditInformation extends javax.swing.JFrame { private String ID;
private Issue issue;
1
2023-10-25 19:14:47+00:00
2k
ddoubest/mini-spring
src/com/test/Test3.java
[ { "identifier": "AnnotationClassPathXmlApplicationContext", "path": "src/com/minis/context/AnnotationClassPathXmlApplicationContext.java", "snippet": "public class AnnotationClassPathXmlApplicationContext extends AbstractApplicationContext {\n private final DefaultListableBeanFactory beanFactory;\n\n public AnnotationClassPathXmlApplicationContext(String fileName, List<String> packageNames) {\n this(fileName, packageNames, true);\n }\n\n public AnnotationClassPathXmlApplicationContext(String fileName, List<String> packageNames, boolean isRefresh) {\n Resource resource = new ClassPathXmlResource(fileName);\n beanFactory = new DefaultListableBeanFactory();\n XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(beanFactory);\n reader.loadBeanDefinitions(resource);\n List<String> controllerNames = ScanComponentHelper.scanPackages(packageNames);\n ScanComponentHelper.loadBeanDefinitions(beanFactory, controllerNames);\n if (isRefresh) {\n refresh();\n }\n }\n\n @Override\n protected void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory) {\n beanFactory.addBeanPostProcessor(new AutowiredAnnotationBeanPostProcessor(this));\n beanFactory.addBeanPostProcessor(new FactoryAwareBeanPostProcessor(this));\n }\n\n @Override\n protected void initApplicationEventPublisher() {\n setApplicationEventPublisher(new SimpleApplicationEventPublisher());\n }\n\n @Override\n protected void onRefresh() {\n beanFactory.refresh();\n }\n\n @Override\n protected void registerListeners() {\n ApplicationListener applicationListener = new ApplicationListener();\n getApplicationEventPublisher().addApplicationListener(applicationListener);\n }\n\n @Override\n protected void finishRefresh() {\n publishEvent(new ContextRefreshEvent(\"Context Refreshed...\"));\n }\n\n @Override\n public ConfigurableListableBeanFactory getBeanFactory() throws IllegalStateException {\n return beanFactory;\n }\n}" }, { "identifier": "ApplicationContext", "path": "src/com/minis/context/ApplicationContext.java", "snippet": "public interface ApplicationContext\n extends EnvironmentCapable, ListableBeanFactory,\n ConfigurableBeanFactory, ApplicationEventPublisher{\n String getApplicationName();\n long getStartupDate();\n ConfigurableListableBeanFactory getBeanFactory() throws IllegalStateException;\n void setEnvironment(Environment environment);\n Environment getEnvironment();\n void addBeanFactoryPostProcessor(BeanFactoryPostProcessor postProcessor);\n void refresh() throws BeansException, IllegalStateException;\n void close();\n boolean isActive();\n}" }, { "identifier": "BeansException", "path": "src/com/minis/exceptions/BeansException.java", "snippet": "public class BeansException extends Exception {\n public BeansException(String message) {\n super(message);\n }\n}" }, { "identifier": "User", "path": "src/com/test/entity/User.java", "snippet": "public class User {\n private int id;\n private String name;\n private Date birthday;\n\n public int getId() {\n return id;\n }\n\n public void setId(int id) {\n this.id = id;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public Date getBirthday() {\n return birthday;\n }\n\n public void setBirthday(Date birthday) {\n this.birthday = birthday;\n }\n\n @Override\n public String toString() {\n return \"User{\" +\n \"id=\" + id +\n \", name='\" + name + '\\'' +\n \", birthday=\" + birthday +\n '}';\n }\n}" }, { "identifier": "UserService", "path": "src/com/test/service/UserService.java", "snippet": "@Component\npublic class UserService {\n @Autowired\n JdbcTemplate jdbcTemplate;\n\n @Autowired\n SqlSessionFactory sqlSessionFactory;\n\n public User getUserInfo(int userId) {\n String sql = \"select id,name,birthday from user where id=\" + userId;\n Object user = jdbcTemplate.query(stmt -> {\n ResultSet resultSet = stmt.executeQuery(sql);\n User rtnUser = null;\n if (resultSet.next()) {\n rtnUser = new User();\n rtnUser.setId(resultSet.getInt(\"id\"));\n rtnUser.setName(resultSet.getString(\"name\"));\n rtnUser.setBirthday(new Date(resultSet.getTimestamp(\"birthday\").getTime()));\n }\n resultSet.close();\n return rtnUser;\n });\n return (User) user;\n }\n\n public User getUserInfoPrepared(int userId) {\n String sql = \"select id,name,birthday from user where id=?\";\n Object user = jdbcTemplate.query(sql, preparedStatement -> {\n ResultSet resultSet = preparedStatement.executeQuery();\n User rtnUser = null;\n if (resultSet.next()) {\n rtnUser = new User();\n rtnUser.setId(resultSet.getInt(\"id\"));\n rtnUser.setName(resultSet.getString(\"name\"));\n rtnUser.setBirthday(new Date(resultSet.getTimestamp(\"birthday\").getTime()));\n }\n resultSet.close();\n return rtnUser;\n }, userId);\n return (User) user;\n }\n\n public List<User> getUsers(int userId) {\n String sql = \"select id,name,birthday from user where id=?\";\n return jdbcTemplate.query(sql, (resultSet, rowIdx) -> {\n User rtnUser = new User();\n rtnUser.setId(resultSet.getInt(\"id\"));\n rtnUser.setName(resultSet.getString(\"name\"));\n rtnUser.setBirthday(new Date(resultSet.getTimestamp(\"birthday\").getTime()));\n return rtnUser;\n }, userId);\n }\n\n public User getUserInfoBySqlSession(int userId) {\n String sqlId = \"com.test.entity.User.getUserInfo\";\n SqlSession sqlSession = sqlSessionFactory.openSession();\n return (User) sqlSession.selectOne(sqlId, preparedStatement -> {\n ResultSet resultSet = preparedStatement.executeQuery();\n User rtnUser = null;\n if (resultSet.next()) {\n rtnUser = new User();\n rtnUser.setId(resultSet.getInt(\"id\"));\n rtnUser.setName(resultSet.getString(\"name\"));\n rtnUser.setBirthday(new Date(resultSet.getTimestamp(\"birthday\").getTime()));\n }\n resultSet.close();\n return rtnUser;\n },userId);\n }\n}" } ]
import com.minis.beans.factory.annotation.Autowired; import com.minis.context.AnnotationClassPathXmlApplicationContext; import com.minis.context.ApplicationContext; import com.minis.core.Component; import com.minis.exceptions.BeansException; import com.test.entity.User; import com.test.service.UserService; import java.util.ArrayList; import java.util.List;
1,487
package com.test; @Component public class Test3 { @Autowired UserService userService; public static void main(String[] args) throws BeansException { List<String> scanPaths = new ArrayList<>(); scanPaths.add("com.test");
package com.test; @Component public class Test3 { @Autowired UserService userService; public static void main(String[] args) throws BeansException { List<String> scanPaths = new ArrayList<>(); scanPaths.add("com.test");
ApplicationContext ctx = new AnnotationClassPathXmlApplicationContext("applicationContext.xml", scanPaths);
0
2023-10-30 12:36:32+00:00
2k
xingduansuzhao-MC/ModTest
src/main/java/com/xdsz/test/events/TestKeyEvents.java
[ { "identifier": "Test", "path": "src/main/java/com/xdsz/test/Test.java", "snippet": "@Mod(\"test\")\npublic class Test\n{\n // Directly reference a log4j logger.\n public static final Logger LOGGER = LogManager.getLogger();//p15的private改为public,控制台能查看调试\n public static final String MOD_ID = \"test\";\n\n public Test() {\n // Register the setup method for mod loading\n FMLJavaModLoadingContext.get().getModEventBus().addListener(this::setup);\n\n FMLJavaModLoadingContext.get().getModEventBus().addListener(this::doClientStuff);\n\n RegistryHandler.init();\n\n // Register ourselves for server and other game events we are interested in\n MinecraftForge.EVENT_BUS.register(this);\n }\n\n private void setup(final FMLCommonSetupEvent event) {\n DeferredWorkQueue.runLater(() -> {\n GlobalEntityTypeAttributes.put(RegistryHandler.TEST_BEAR.get(), TestBearEntity.testBearAttributes().create());\n });\n }\n\n private void doClientStuff(final FMLClientSetupEvent event) {\n RenderTypeLookup.setRenderLayer(TestFluids.HONEYTEST_FLUID.get(), RenderType.getTranslucent());\n RenderTypeLookup.setRenderLayer(TestFluids.HONEYTEST_BLOCK.get(), RenderType.getTranslucent());\n RenderTypeLookup.setRenderLayer(TestFluids.HONEYTEST_FLOWING.get(), RenderType.getTranslucent());\n\n TestKeybinds.register(event);\n }\n\n public static final ItemGroup TAB = new ItemGroup(\"testTab\") {\n @Override\n public ItemStack createIcon() {\n return new ItemStack(RegistryHandler.SAPPHIRE.get());\n }\n };\n\n}" }, { "identifier": "TestKeybinds", "path": "src/main/java/com/xdsz/test/key/TestKeybinds.java", "snippet": "@OnlyIn(Dist.CLIENT)\npublic class TestKeybinds {\n public static KeyBinding testKey;\n\n public static void register(final FMLClientSetupEvent evet){\n testKey = create(\"test_key\", KeyEvent.VK_R);\n ClientRegistry.registerKeyBinding(testKey);\n }\n\n private static KeyBinding create(String name, int key){\n return new KeyBinding(\"key.\" + Test.MOD_ID + \".\" + name, key, \"key.category.\" + Test.MOD_ID);\n }\n}" } ]
import com.xdsz.test.Test; import com.xdsz.test.key.TestKeybinds; import net.minecraft.client.Minecraft; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.client.event.InputEvent; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.common.Mod;
702
package com.xdsz.test.events; @Mod.EventBusSubscriber(modid = Test.MOD_ID, bus = Mod.EventBusSubscriber.Bus.FORGE, value = Dist.CLIENT) public class TestKeyEvents { @SubscribeEvent public static void pressKey(InputEvent.KeyInputEvent event){ Minecraft mc = Minecraft.getInstance(); if(mc.world == null) return; processKeyPress(mc, event.getKey()); } private static void processKeyPress(Minecraft mc, int key){
package com.xdsz.test.events; @Mod.EventBusSubscriber(modid = Test.MOD_ID, bus = Mod.EventBusSubscriber.Bus.FORGE, value = Dist.CLIENT) public class TestKeyEvents { @SubscribeEvent public static void pressKey(InputEvent.KeyInputEvent event){ Minecraft mc = Minecraft.getInstance(); if(mc.world == null) return; processKeyPress(mc, event.getKey()); } private static void processKeyPress(Minecraft mc, int key){
if(mc.currentScreen == null && TestKeybinds.testKey.isPressed()){
1
2023-10-28 05:14:07+00:00
2k
SUFIAG/Weather-Application-Android
app/src/main/java/com/aniketjain/weatherapp/adapter/DaysAdapter.java
[ { "identifier": "UpdateUI", "path": "app/src/main/java/com/aniketjain/weatherapp/update/UpdateUI.java", "snippet": "public class UpdateUI {\n\n public static String getIconID(int condition, long update_time, long sunrise, long sunset) {\n if (condition >= 200 && condition <= 232)\n return \"thunderstorm\";\n else if (condition >= 300 && condition <= 321)\n return \"drizzle\";\n else if (condition >= 500 && condition <= 531)\n return \"rain\";\n else if (condition >= 600 && condition <= 622)\n return \"snow\";\n else if (condition >= 701 && condition <= 781)\n return \"wind\";\n else if (condition == 800) {\n if (update_time >= sunrise && update_time <= sunset)\n return \"clear_day\";\n else\n return \"clear_night\";\n } else if (condition == 801) {\n if (update_time >= sunrise && update_time <= sunset)\n return \"few_clouds_day\";\n else\n return \"few_clouds_night\";\n } else if (condition == 802)\n return \"scattered_clouds\";\n else if (condition == 803 || condition == 804)\n return \"broken_clouds\";\n return null;\n }\n\n public static String TranslateDay(String dayToBeTranslated, Context context) {\n switch (dayToBeTranslated.trim()) {\n case \"Monday\":\n return context.getResources().getString(R.string.monday);\n case \"Tuesday\":\n return context.getResources().getString(R.string.tuesday);\n case \"Wednesday\":\n return context.getResources().getString(R.string.wednesday);\n case \"Thursday\":\n return context.getResources().getString(R.string.thursday);\n case \"Friday\":\n return context.getResources().getString(R.string.friday);\n case \"Saturday\":\n return context.getResources().getString(R.string.saturday);\n case \"Sunday\":\n return context.getResources().getString(R.string.sunday);\n }\n return dayToBeTranslated;\n }\n}" }, { "identifier": "URL", "path": "app/src/main/java/com/aniketjain/weatherapp/url/URL.java", "snippet": "public class URL {\n private String link;\n private static String city_url;\n\n public URL() {\n link = \"https://api.openweathermap.org/data/2.5/onecall?exclude=minutely&lat=\"\n + LocationCord.lat + \"&lon=\" + LocationCord.lon + \"&appid=\" + LocationCord.API_KEY;\n }\n\n public String getLink() {\n return link;\n }\n\n\n public static void setCity_url(String cityName) {\n city_url = \"https://api.openweathermap.org/data/2.5/weather?&q=\" + cityName + \"&appid=\" + LocationCord.API_KEY;\n }\n\n public static String getCity_url() {\n return city_url;\n }\n\n}" } ]
import android.annotation.SuppressLint; import android.content.Context; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.toolbox.JsonObjectRequest; import com.android.volley.toolbox.Volley; import com.aniketjain.weatherapp.R; import com.aniketjain.weatherapp.update.UpdateUI; import com.aniketjain.weatherapp.url.URL; import com.github.ybq.android.spinkit.SpinKitView; import org.json.JSONException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale;
1,404
package com.aniketjain.weatherapp.adapter; public class DaysAdapter extends RecyclerView.Adapter<DaysAdapter.DayViewHolder> { private final Context context; public DaysAdapter(Context context) { this.context = context; } private String updated_at, min, max, pressure, wind_speed, humidity; private int condition; private long update_time, sunset, sunrise; @NonNull @Override public DayViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(context).inflate(R.layout.day_item_layout, parent, false); return new DayViewHolder(view); } @Override public void onBindViewHolder(@NonNull DayViewHolder holder, int position) { getDailyWeatherInfo(position + 1, holder); } @Override public int getItemCount() { return 6; } @SuppressLint("DefaultLocale") private void getDailyWeatherInfo(int i, DayViewHolder holder) { URL url = new URL(); RequestQueue requestQueue = Volley.newRequestQueue(context); JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url.getLink(), null, response -> { try { update_time = response.getJSONObject("current").getLong("dt"); updated_at = new SimpleDateFormat("EEEE", Locale.ENGLISH).format(new Date((update_time * 1000) + (i * 864_000_00L))); // i=0 condition = response.getJSONArray("daily").getJSONObject(i).getJSONArray("weather").getJSONObject(0).getInt("id"); sunrise = response.getJSONArray("daily").getJSONObject(i).getLong("sunrise"); sunset = response.getJSONArray("daily").getJSONObject(i).getLong("sunset"); min = String.format("%.0f", response.getJSONArray("daily").getJSONObject(i).getJSONObject("temp").getDouble("min") - 273.15); max = String.format("%.0f", response.getJSONArray("daily").getJSONObject(i).getJSONObject("temp").getDouble("max") - 273.15); pressure = response.getJSONArray("daily").getJSONObject(i).getString("pressure"); wind_speed = response.getJSONArray("daily").getJSONObject(i).getString("wind_speed"); humidity = response.getJSONArray("daily").getJSONObject(i).getString("humidity"); updateUI(holder); hideProgressBar(holder); } catch (JSONException e) { e.printStackTrace(); } }, null); requestQueue.add(jsonObjectRequest); Log.i("json_req", "Day " + i); } @SuppressLint("SetTextI18n") private void updateUI(DayViewHolder holder) {
package com.aniketjain.weatherapp.adapter; public class DaysAdapter extends RecyclerView.Adapter<DaysAdapter.DayViewHolder> { private final Context context; public DaysAdapter(Context context) { this.context = context; } private String updated_at, min, max, pressure, wind_speed, humidity; private int condition; private long update_time, sunset, sunrise; @NonNull @Override public DayViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(context).inflate(R.layout.day_item_layout, parent, false); return new DayViewHolder(view); } @Override public void onBindViewHolder(@NonNull DayViewHolder holder, int position) { getDailyWeatherInfo(position + 1, holder); } @Override public int getItemCount() { return 6; } @SuppressLint("DefaultLocale") private void getDailyWeatherInfo(int i, DayViewHolder holder) { URL url = new URL(); RequestQueue requestQueue = Volley.newRequestQueue(context); JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url.getLink(), null, response -> { try { update_time = response.getJSONObject("current").getLong("dt"); updated_at = new SimpleDateFormat("EEEE", Locale.ENGLISH).format(new Date((update_time * 1000) + (i * 864_000_00L))); // i=0 condition = response.getJSONArray("daily").getJSONObject(i).getJSONArray("weather").getJSONObject(0).getInt("id"); sunrise = response.getJSONArray("daily").getJSONObject(i).getLong("sunrise"); sunset = response.getJSONArray("daily").getJSONObject(i).getLong("sunset"); min = String.format("%.0f", response.getJSONArray("daily").getJSONObject(i).getJSONObject("temp").getDouble("min") - 273.15); max = String.format("%.0f", response.getJSONArray("daily").getJSONObject(i).getJSONObject("temp").getDouble("max") - 273.15); pressure = response.getJSONArray("daily").getJSONObject(i).getString("pressure"); wind_speed = response.getJSONArray("daily").getJSONObject(i).getString("wind_speed"); humidity = response.getJSONArray("daily").getJSONObject(i).getString("humidity"); updateUI(holder); hideProgressBar(holder); } catch (JSONException e) { e.printStackTrace(); } }, null); requestQueue.add(jsonObjectRequest); Log.i("json_req", "Day " + i); } @SuppressLint("SetTextI18n") private void updateUI(DayViewHolder holder) {
String day = UpdateUI.TranslateDay(updated_at, context);
0
2023-10-25 21:15:57+00:00
2k
dawex/sigourney
trust-framework/verifiable-credentials-model/src/main/java/com/dawex/sigourney/trustframework/vc/model/v2310/dataproduct/DataProductVerifiableCredential.java
[ { "identifier": "CompositeValue", "path": "trust-framework/verifiable-credentials-core/src/main/java/com/dawex/sigourney/trustframework/vc/core/jsonld/CompositeValue.java", "snippet": "public interface CompositeValue {\n\tObject[] getValues();\n}" }, { "identifier": "Format", "path": "trust-framework/verifiable-credentials-model/src/main/java/com/dawex/sigourney/trustframework/vc/model/v2310/serialization/Format.java", "snippet": "public class Format {\n\tpublic static final String DATA_PRODUCT_CREDENTIAL_SUBJECT = \"DATA_PRODUCT_CREDENTIAL_SUBJECT\";\n\n\tpublic static final String DATA_PRODUCT_DATA_LICENSORS = \"DATA_PRODUCT_DATA_LICENSORS\";\n\n\tpublic static final String DATA_PRODUCT_EXPOSED_THROUGH = \"DATA_PRODUCT_EXPOSED_THROUGH\";\n\n\tpublic static final String DATA_PRODUCT_ISSUER = \"DATA_PRODUCT_ISSUER\";\n\n\tpublic static final String DATA_PRODUCT_PROVIDED_BY = \"DATA_PRODUCT_PROVIDED_BY\";\n\n\tpublic static final String DATA_PRODUCT_VERIFIABLE_CREDENTIAL = \"DATA_PRODUCT_VERIFIABLE_CREDENTIAL\";\n\n\tpublic static final String ORGANISATION_CREDENTIAL_SUBJECT = \"ORGANISATION_CREDENTIAL_SUBJECT\";\n\n\tpublic static final String ORGANISATION_ISSUER = \"ORGANISATION_ISSUER\";\n\n\tpublic static final String ORGANISATION_VERIFIABLE_CREDENTIAL = \"ORGANISATION_VERIFIABLE_CREDENTIAL\";\n\n\tprivate Format() {\n\t\t// no instance allowed\n\t}\n}" }, { "identifier": "GAIAX_TRUST_FRAMEWORK", "path": "trust-framework/verifiable-credentials-core/src/main/java/com/dawex/sigourney/trustframework/vc/core/jsonld/ExternalContext.java", "snippet": "public static final String GAIAX_TRUST_FRAMEWORK = \"https://registry.lab.gaia-x.eu/development/api/trusted-shape-registry/v1/shapes/jsonld/trustframework#\";" }, { "identifier": "SECURITY_JWS_2020", "path": "trust-framework/verifiable-credentials-core/src/main/java/com/dawex/sigourney/trustframework/vc/core/jsonld/ExternalContext.java", "snippet": "public static final String SECURITY_JWS_2020 = \"https://w3id.org/security/suites/jws-2020/v1\";" }, { "identifier": "VERIFIABLE_CREDENTIALS", "path": "trust-framework/verifiable-credentials-core/src/main/java/com/dawex/sigourney/trustframework/vc/core/jsonld/ExternalContext.java", "snippet": "public static final String VERIFIABLE_CREDENTIALS = \"https://www.w3.org/2018/credentials/v1\";" }, { "identifier": "DAWEX_IRI", "path": "trust-framework/verifiable-credentials-model/src/main/java/com/dawex/sigourney/trustframework/vc/model/v2310/Namespace.java", "snippet": "public static final String DAWEX_IRI = \"https://dawex.com/schemas/dataoffering#\";" }, { "identifier": "DAWEX_NS", "path": "trust-framework/verifiable-credentials-model/src/main/java/com/dawex/sigourney/trustframework/vc/model/v2310/Namespace.java", "snippet": "public static final String DAWEX_NS = \"dw\";" }, { "identifier": "DCAT_IRI", "path": "trust-framework/verifiable-credentials-model/src/main/java/com/dawex/sigourney/trustframework/vc/model/v2310/Namespace.java", "snippet": "public static final String DCAT_IRI = \"http://www.w3.org/ns/dcat#\";" }, { "identifier": "DCAT_NS", "path": "trust-framework/verifiable-credentials-model/src/main/java/com/dawex/sigourney/trustframework/vc/model/v2310/Namespace.java", "snippet": "public static final String DCAT_NS = \"dcat\";" }, { "identifier": "DC_TERMS_IRI", "path": "trust-framework/verifiable-credentials-model/src/main/java/com/dawex/sigourney/trustframework/vc/model/v2310/Namespace.java", "snippet": "public static final String DC_TERMS_IRI = \"http://purl.org/dc/terms/\";" }, { "identifier": "DC_TERMS_NS", "path": "trust-framework/verifiable-credentials-model/src/main/java/com/dawex/sigourney/trustframework/vc/model/v2310/Namespace.java", "snippet": "public static final String DC_TERMS_NS = \"dct\";" }, { "identifier": "LOCATION_IRI", "path": "trust-framework/verifiable-credentials-model/src/main/java/com/dawex/sigourney/trustframework/vc/model/v2310/Namespace.java", "snippet": "public static final String LOCATION_IRI = \"http://www.w3.org/ns/locn#\";" }, { "identifier": "LOCATION_NS", "path": "trust-framework/verifiable-credentials-model/src/main/java/com/dawex/sigourney/trustframework/vc/model/v2310/Namespace.java", "snippet": "public static final String LOCATION_NS = \"locn\";" } ]
import com.dawex.sigourney.trustframework.vc.core.jsonld.CompositeValue; import com.dawex.sigourney.trustframework.vc.core.jsonld.annotation.JsonLdContexts; import com.dawex.sigourney.trustframework.vc.core.jsonld.annotation.JsonLdEmbeddedContext; import com.dawex.sigourney.trustframework.vc.core.jsonld.annotation.JsonLdProperty; import com.dawex.sigourney.trustframework.vc.core.jsonld.annotation.JsonLdType; import com.dawex.sigourney.trustframework.vc.model.v2310.serialization.Format; import java.time.ZonedDateTime; import java.util.Objects; import static com.dawex.sigourney.trustframework.vc.core.jsonld.ExternalContext.GAIAX_TRUST_FRAMEWORK; import static com.dawex.sigourney.trustframework.vc.core.jsonld.ExternalContext.SECURITY_JWS_2020; import static com.dawex.sigourney.trustframework.vc.core.jsonld.ExternalContext.VERIFIABLE_CREDENTIALS; import static com.dawex.sigourney.trustframework.vc.model.v2310.Namespace.DAWEX_IRI; import static com.dawex.sigourney.trustframework.vc.model.v2310.Namespace.DAWEX_NS; import static com.dawex.sigourney.trustframework.vc.model.v2310.Namespace.DCAT_IRI; import static com.dawex.sigourney.trustframework.vc.model.v2310.Namespace.DCAT_NS; import static com.dawex.sigourney.trustframework.vc.model.v2310.Namespace.DC_TERMS_IRI; import static com.dawex.sigourney.trustframework.vc.model.v2310.Namespace.DC_TERMS_NS; import static com.dawex.sigourney.trustframework.vc.model.v2310.Namespace.LOCATION_IRI; import static com.dawex.sigourney.trustframework.vc.model.v2310.Namespace.LOCATION_NS;
1,477
package com.dawex.sigourney.trustframework.vc.model.v2310.dataproduct; /** * @see <a href="https://www.w3.org/2018/credentials/v1">Verifiable Credential Schema</a> */ @JsonLdContexts( addBaseContext = true, embeddedContexts = { @JsonLdEmbeddedContext(term = DAWEX_NS, iri = DAWEX_IRI),
package com.dawex.sigourney.trustframework.vc.model.v2310.dataproduct; /** * @see <a href="https://www.w3.org/2018/credentials/v1">Verifiable Credential Schema</a> */ @JsonLdContexts( addBaseContext = true, embeddedContexts = { @JsonLdEmbeddedContext(term = DAWEX_NS, iri = DAWEX_IRI),
@JsonLdEmbeddedContext(term = DCAT_NS, iri = DCAT_IRI),
7
2023-10-25 16:10:40+00:00
2k
AysuCgs/JavaMonolithic
src/main/java/com/aysu/service/MusteriService.java
[ { "identifier": "MusteriSaveRequestDto", "path": "src/main/java/com/aysu/dto/request/MusteriSaveRequestDto.java", "snippet": "@Builder // bir sınıftan nesne türetmeyi sağlar.\n@Data //get set metodlarını otomatik tanımlar.\n@NoArgsConstructor //boş constructor oluşturur.\n@AllArgsConstructor //dolu constructor oluşturur.\npublic class MusteriSaveRequestDto {\n String ad;\n String adres;\n String tel;\n\n String token;\n String ip;\n String userpcmodel;\n}" }, { "identifier": "MusteriFindAllResponseDto", "path": "src/main/java/com/aysu/dto/response/MusteriFindAllResponseDto.java", "snippet": "@Builder // bir sınıftan nesne türetmeyi sağlar.\n@Data //get set metodlarını otomatik tanımlar.\n@NoArgsConstructor //boş constructor oluşturur.\n@AllArgsConstructor //dolu constructor oluşturur.\npublic class MusteriFindAllResponseDto {\n String username;\n String ad;\n String img;\n}" }, { "identifier": "IMusteriMapper", "path": "src/main/java/com/aysu/mapper/IMusteriMapper.java", "snippet": "@Mapper(componentModel = \"spring\",unmappedTargetPolicy = ReportingPolicy.IGNORE)\npublic interface IMusteriMapper {\n IMusteriMapper INSTANCE= Mappers.getMapper(IMusteriMapper.class);\n /*\n Bundan sonrasında dönüşüm yapmak istediğiniz sınıflarla iligli metodları yazın.\n */\n MusteriFindAllResponseDto fromMusteri(final Musteri musteri);\n\n Musteri fromSaveRequestDto(final MusteriSaveRequestDto dto);\n}" }, { "identifier": "IMusteriRepository", "path": "src/main/java/com/aysu/repository/IMusteriRepository.java", "snippet": "@Repository\npublic interface IMusteriRepository extends JpaRepository<Musteri,Long> {\n /*\n find: kelimesi ile başlanması gereklidir.\n By: işlem yapılacak bileşen adından önce yazılması gereklidir.\n [değişkenadı] Ad: kullanılan repository içine geçilen entity içindeki\n //arama yapılmak istenen field adı ilk karakteri büyük harfle olacak şekilde yazılır.\n Geri dönüş tipi olmalıdır.\n\n */\n // select * from tblmusteri where ad=?\n Musteri findByAd(String ad);\n\n List<Musteri> findAllByIl(String il);\n\n Optional<Musteri> findOptionalByUsernameAndPassword(String username, String password);\n}" }, { "identifier": "Musteri", "path": "src/main/java/com/aysu/repository/entity/Musteri.java", "snippet": "@Builder // bir sınıftan nesne türetmeyi sağlar.\n@Data //get set metodlarını otomatik tanımlar.\n@NoArgsConstructor //boş constructor oluşturur.\n@AllArgsConstructor //dolu constructor oluşturur.\n@ToString\n@Entity\n@Table(name = \"tblmusteri\")\npublic class Musteri {\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n Long id;\n\n String ad;\n String adres;\n String tel;\n\n String il;\n String username;\n String password;\n String email;\n String img;\n}" }, { "identifier": "ServiceManager", "path": "src/main/java/com/aysu/utility/ServiceManager.java", "snippet": "public class ServiceManager<T,ID> implements IService<T,ID>{\n\n private final JpaRepository<T,ID> repository;\n public ServiceManager(JpaRepository<T, ID> repository) {\n this.repository = repository;\n }\n\n @Override\n public T save(T t) {\n return repository.save(t);\n }\n @Override\n public Iterable<T> saveAll(Iterable<T> t) {\n return repository.saveAll(t);\n }\n @Override\n public T update(T t) {\n return repository.save(t);\n }\n @Override\n public void delete(T t) {\n repository.delete(t);\n }\n @Override\n public void deleteById(ID id) {\n repository.deleteById(id);\n }\n @Override\n public Optional<T> findById(ID id) {\n return repository.findById(id);\n }\n @Override\n public List<T> findAll() {\n return repository.findAll();\n }\n\n}" } ]
import com.aysu.dto.request.MusteriSaveRequestDto; import com.aysu.dto.response.MusteriFindAllResponseDto; import com.aysu.mapper.IMusteriMapper; import com.aysu.repository.IMusteriRepository; import com.aysu.repository.entity.Musteri; import com.aysu.utility.ServiceManager; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; import java.util.Optional;
1,154
package com.aysu.service; @Service public class MusteriService extends ServiceManager<Musteri,Long> {
package com.aysu.service; @Service public class MusteriService extends ServiceManager<Musteri,Long> {
private final IMusteriRepository repository;
3
2023-10-27 19:47:03+00:00
2k
SkEditorTeam/SkAnalyzer
api/src/main/java/me/glicz/skanalyzer/SkAnalyzer.java
[ { "identifier": "AddonsLoader", "path": "api/src/main/java/me/glicz/skanalyzer/loader/AddonsLoader.java", "snippet": "@RequiredArgsConstructor\npublic class AddonsLoader {\n public static final File USER_HOME = new File(System.getProperty(\"user.home\"));\n public static final File ADDONS = new File(USER_HOME, \"SkAnalyzer/addons\");\n public static final String MOCK_SKRIPT = \"MockSkript.jar\";\n public static final String MOCK_SKRIPT_BRIDGE = \"MockSkriptBridge.jar\";\n private final SkAnalyzer skAnalyzer;\n private JavaPlugin skript;\n @Getter\n private MockSkriptBridge mockSkriptBridge;\n\n @SuppressWarnings(\"UnstableApiUsage\")\n public void loadAddons() {\n if (skript != null)\n throw new RuntimeException(\"Addons are already loaded!\");\n skript = loadSimpleAddon(new File(skAnalyzer.getWorkingDirectory(), MOCK_SKRIPT));\n mockSkriptBridge = loadMockSkriptBridge();\n FileUtils.listFiles(skAnalyzer.getWorkingDirectory(), new String[]{\"jar\"}, false).forEach(this::loadSimpleAddon);\n skAnalyzer.getLogger().info(\n \"Successfully loaded addons: {}\",\n Arrays.stream(Bukkit.getPluginManager().getPlugins())\n .map(plugin -> plugin.getPluginMeta().getDisplayName())\n .collect(Collectors.joining(\", \"))\n );\n }\n\n private JavaPlugin loadSimpleAddon(File file) {\n Class<?> pluginClass = loadAddon(file);\n if (pluginClass == null) return null;\n try {\n JavaPlugin plugin = (JavaPlugin) pluginClass.getConstructor().newInstance();\n skAnalyzer.getServer().getPluginManager().registerLoadedPlugin(plugin);\n skAnalyzer.getServer().getPluginManager().enablePlugin(plugin);\n return plugin;\n } catch (Exception e) {\n skAnalyzer.getLogger().error(\"Something went wrong while trying to load %s\".formatted(file.getPath()), e);\n }\n return null;\n }\n\n private MockSkriptBridge loadMockSkriptBridge() {\n File file = new File(skAnalyzer.getWorkingDirectory(), MOCK_SKRIPT_BRIDGE);\n Class<?> pluginClass = loadAddon(file);\n if (pluginClass == null) return null;\n try {\n MockSkriptBridge plugin = (MockSkriptBridge) pluginClass.getConstructor(SkAnalyzer.class).newInstance(skAnalyzer);\n skAnalyzer.getServer().getPluginManager().registerLoadedPlugin(plugin);\n skAnalyzer.getServer().getPluginManager().enablePlugin(plugin);\n return plugin;\n } catch (Exception e) {\n skAnalyzer.getLogger().error(\"Something went wrong while trying to load %s\".formatted(file.getPath()), e);\n }\n return null;\n }\n\n @SuppressWarnings(\"UnstableApiUsage\")\n private Class<?> loadAddon(File file) {\n if (skript != null && file.getName().equals(MOCK_SKRIPT)) return null;\n if (mockSkriptBridge != null && file.getName().equals(MOCK_SKRIPT_BRIDGE)) return null;\n try {\n JarFile jarFile = new JarFile(file);\n PluginDescriptionFile description = new PluginDescriptionFile(jarFile.getInputStream(jarFile.getEntry(\"plugin.yml\")));\n if (Bukkit.getServer().getPluginManager().isPluginEnabled(description.getName()))\n throw new RuntimeException(\"Plugin named '%s' is already loaded\".formatted(description.getName()));\n AnalyzerClassLoader classLoader = new AnalyzerClassLoader(\n SkAnalyzer.class.getClassLoader(),\n description,\n new File(skAnalyzer.getWorkingDirectory(), description.getName()),\n file,\n jarFile\n );\n if (skript != null)\n classLoader.getGroup().add((ConfiguredPluginClassLoader) skript.getClass().getClassLoader());\n return classLoader.loadClass(description.getMainClass(), true, false, false);\n } catch (Exception | ExceptionInInitializerError e) {\n skAnalyzer.getLogger().error(\"Something went wrong while trying to load %s\".formatted(file.getPath()), e);\n }\n return null;\n }\n}" }, { "identifier": "AnalyzerServer", "path": "api/src/main/java/me/glicz/skanalyzer/mockbukkit/AnalyzerServer.java", "snippet": "@Getter\npublic class AnalyzerServer extends ServerMock {\n private final AnalyzerUnsafeValues unsafe = new AnalyzerUnsafeValues();\n private final AnalyzerStructureManager structureManager = new AnalyzerStructureManager();\n private final AnalyzerPotionBrewer potionBrewer = new AnalyzerPotionBrewer();\n\n public void startTicking() {\n new Timer().scheduleAtFixedRate(new TimerTask() {\n @Override\n public void run() {\n ((BukkitSchedulerMock) Bukkit.getScheduler()).performOneTick();\n }\n }, 50, 50);\n }\n\n @Override\n public @NotNull String getName() {\n return \"SkAnalyzer\";\n }\n\n @SuppressWarnings(\"DataFlowIssue\")\n @Override\n public @NotNull BlockData createBlockData(String data) {\n if (data.contains(\":\"))\n data = data.split(\":\")[1];\n String rawMaterial = (data.indexOf('[') == -1)\n ? data\n : data.substring(0, data.indexOf('['));\n Material material = Material.getMaterial(rawMaterial.toUpperCase());\n if (material == null)\n return null;\n return createBlockData(material);\n }\n\n @Override\n public @NotNull BlockData createBlockData(Material material, String data) {\n return createBlockData(material);\n }\n\n @Override\n public boolean isStopping() {\n return false;\n }\n}" } ]
import be.seeseemelk.mockbukkit.MockBukkit; import com.google.common.base.Preconditions; import lombok.AccessLevel; import lombok.Data; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.experimental.Accessors; import me.glicz.skanalyzer.loader.AddonsLoader; import me.glicz.skanalyzer.mockbukkit.AnalyzerServer; import org.apache.commons.io.FileUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Unmodifiable; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.EnumSet; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.concurrent.CompletableFuture;
1,515
package me.glicz.skanalyzer; @Getter public class SkAnalyzer { public static final String WORKING_DIR_PROPERTY = "skanalyzer.workingDir"; private final EnumSet<AnalyzerFlag> flags; private final File workingDirectory; private final Logger logger; private final AnalyzerServer server;
package me.glicz.skanalyzer; @Getter public class SkAnalyzer { public static final String WORKING_DIR_PROPERTY = "skanalyzer.workingDir"; private final EnumSet<AnalyzerFlag> flags; private final File workingDirectory; private final Logger logger; private final AnalyzerServer server;
private final AddonsLoader addonsLoader;
0
2023-10-25 20:04:09+00:00
2k
ForestRealms/Homework-Collect-Backend
src/main/java/space/glowberry/homeworkcollectbackend/Controller/HomeworkController.java
[ { "identifier": "HomeworkDataAccess", "path": "src/main/java/space/glowberry/homeworkcollectbackend/DataAccess/HomeworkDataAccess.java", "snippet": "@Repository\npublic class HomeworkDataAccess implements DataAccess, EntityGetter<Homework> {\n private JdbcTemplate template;\n\n @Autowired\n public void setTemplate(JdbcTemplate template) {\n this.template = template;\n }\n\n @Override\n public List<Homework> get() {\n return this.template.query(\"select * from `homework`\", new HomeworkRowMapper());\n }\n\n public Homework getById(int id){\n for (Homework homework : get()) {\n if (homework.getId() == id) return homework;\n }\n return null;\n }\n\n public void addHomework(Homework homework) throws HomeworkAlreadyExists {\n int id = homework.getId();\n for (Homework homework1 : get()) {\n if (homework1.getId() == id) throw new HomeworkAlreadyExists();\n }\n String title = homework.getTitle();\n String description = homework.getDescription();\n Date due = homework.getDue();\n this.template.update(\"INSERT INTO homework (`id`, `title`, `description`, `due`) VALUES (?, ?, ?, ?)\",\n id, title, description, due);\n\n }\n\n public void updateHomework(Homework homework){\n for (Homework h : get()) {\n if(h.getId() == homework.getId()){\n this.template.update(\"update homework set title = ?, description = ?, due = ? where id=?;\",\n homework.getTitle(), homework.getDescription(), homework.getDue(), homework.getId());\n }\n }\n }\n}" }, { "identifier": "Homework", "path": "src/main/java/space/glowberry/homeworkcollectbackend/Entity/Homework.java", "snippet": "public class Homework {\n private int id;\n private String title;\n private String description;\n private Date due;\n\n public Homework(int id, String title, String description, Date due) {\n this.id = id;\n this.title = title;\n this.description = description;\n this.due = due;\n }\n\n public int getId() {\n return id;\n }\n\n public void setId(int id) {\n this.id = id;\n }\n\n public String getTitle() {\n return title;\n }\n\n public void setTitle(String title) {\n this.title = title;\n }\n\n public String getDescription() {\n return description;\n }\n\n public void setDescription(String description) {\n this.description = description;\n }\n\n public Date getDue() {\n return due;\n }\n\n public void setDue(Date due) {\n this.due = due;\n }\n}" }, { "identifier": "HomeworkService", "path": "src/main/java/space/glowberry/homeworkcollectbackend/Service/HomeworkService.java", "snippet": "@Service\npublic class HomeworkService {\n\n private HomeworkDataAccess homeworkDataAccess;\n\n @Autowired\n public void setHomeworkDataAccess(HomeworkDataAccess homeworkDataAccess) {\n this.homeworkDataAccess = homeworkDataAccess;\n }\n\n public int addHomework(int id,\n String title,\n String description,\n Date due){\n try {\n this.homeworkDataAccess.addHomework(new Homework(id, title, description, due));\n return 1;\n }catch (HomeworkAlreadyExists e){\n return 0;\n }\n\n }\n\n public void updateHomework(int id,\n String title,\n String description,\n Date due){\n this.homeworkDataAccess.updateHomework(new Homework(id, title, description, due));\n }\n}" } ]
import com.alibaba.fastjson2.JSONObject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import space.glowberry.homeworkcollectbackend.DataAccess.HomeworkDataAccess; import space.glowberry.homeworkcollectbackend.Entity.Homework; import space.glowberry.homeworkcollectbackend.Service.HomeworkService; import java.util.Calendar; import java.util.Date;
1,022
package space.glowberry.homeworkcollectbackend.Controller; @RestController public class HomeworkController { // @PostMapping("/upload") // public JSONObject uploadHomework(@RequestParam("file")MultipartFile multipartFile){ // // } private HomeworkDataAccess homeworkDataAccess;
package space.glowberry.homeworkcollectbackend.Controller; @RestController public class HomeworkController { // @PostMapping("/upload") // public JSONObject uploadHomework(@RequestParam("file")MultipartFile multipartFile){ // // } private HomeworkDataAccess homeworkDataAccess;
private HomeworkService homeworkService;
2
2023-11-01 11:50:05+00:00
2k
mcxiaoxiao/library-back
src/main/java/com/main/book/BookResolver.java
[ { "identifier": "BookEntity", "path": "src/main/java/com/main/schema/BookEntity.java", "snippet": "@Entity\n@Table(name = \"book\", schema = \"public\", catalog = \"library\")\npublic class BookEntity {\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n @Id\n @Column(name = \"bookid\")\n private int bookid;\n @Basic\n @Column(name = \"author\")\n private String author;\n @Basic\n @Column(name = \"level\")\n private Integer level;\n @Basic\n @Column(name = \"type\")\n private String type;\n @Basic\n @Column(name = \"borrowed\")\n private Boolean borrowed;\n @Basic\n @Column(name = \"isbn\")\n private String isbn;\n @Basic\n @Column(name = \"libid\")\n private Integer libid;\n @Basic\n @Column(name = \"name\")\n private String name;\n @Basic\n @Column(name = \"price\")\n private Double price;\n @Basic\n @Column(name = \"publisher\")\n private String publisher;\n @Basic\n @Column(name = \"libname\")\n private String libname;\n @Basic\n @Column(name = \"content\")\n private String content;\n\n public int getBookid() {\n return bookid;\n }\n\n public void setBookid(int bookid) {\n this.bookid = bookid;\n }\n\n public String getAuthor() {\n return author;\n }\n\n public void setAuthor(String author) {\n this.author = author;\n }\n\n public Integer getLevel() {\n return level;\n }\n\n public void setLevel(Integer level) {\n this.level = level;\n }\n\n public String getType() {\n return type;\n }\n\n public void setType(String type) {\n this.type = type;\n }\n\n public Boolean getBorrowed() {\n return borrowed;\n }\n\n public void setBorrowed(Boolean borrowed) {\n this.borrowed = borrowed;\n }\n\n public String getIsbn() {\n return isbn;\n }\n\n public void setIsbn(String isbn) {\n this.isbn = isbn;\n }\n\n public Integer getLibid() {\n return libid;\n }\n\n public void setLibid(Integer libid) {\n this.libid = libid;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public Double getPrice() {\n return price;\n }\n\n public void setPrice(Double price) {\n this.price = price;\n }\n\n public String getPublisher() {\n return publisher;\n }\n\n public void setPublisher(String publisher) {\n this.publisher = publisher;\n }\n\n public String getLibname() {\n return libname;\n }\n\n public void setLibname(String libname) {\n this.libname = libname;\n }\n\n public String getContent() { return content; }\n\n public void setContent(String content) { this.content = content;}\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (o == null || getClass() != o.getClass()) return false;\n\n BookEntity that = (BookEntity) o;\n\n if (bookid != that.bookid) return false;\n if (author != null ? !author.equals(that.author) : that.author != null) return false;\n if (level != null ? !level.equals(that.level) : that.level != null) return false;\n if (type != null ? !type.equals(that.type) : that.type != null) return false;\n if (borrowed != null ? !borrowed.equals(that.borrowed) : that.borrowed != null) return false;\n if (isbn != null ? !isbn.equals(that.isbn) : that.isbn != null) return false;\n if (libid != null ? !libid.equals(that.libid) : that.libid != null) return false;\n if (name != null ? !name.equals(that.name) : that.name != null) return false;\n if (price != null ? !price.equals(that.price) : that.price != null) return false;\n if (publisher != null ? !publisher.equals(that.publisher) : that.publisher != null) return false;\n if (libname != null ? !libname.equals(that.libname) : that.libname != null) return false;\n if (content != null ? !content.equals(that.content) : that.content != null) return false;\n\n return true;\n }\n\n @Override\n public int hashCode() {\n int result = bookid;\n result = 31 * result + (author != null ? author.hashCode() : 0);\n result = 31 * result + (level != null ? level.hashCode() : 0);\n result = 31 * result + (type != null ? type.hashCode() : 0);\n result = 31 * result + (borrowed != null ? borrowed.hashCode() : 0);\n result = 31 * result + (isbn != null ? isbn.hashCode() : 0);\n result = 31 * result + (libid != null ? libid.hashCode() : 0);\n result = 31 * result + (name != null ? name.hashCode() : 0);\n result = 31 * result + (price != null ? price.hashCode() : 0);\n result = 31 * result + (publisher != null ? publisher.hashCode() : 0);\n result = 31 * result + (libname != null ? libname.hashCode() : 0);\n result = 31 * result + (content != null ? content.hashCode() : 0);\n return result;\n }\n\n\n}" }, { "identifier": "PagesBookEntity", "path": "src/main/java/com/main/schema/PagesBookEntity.java", "snippet": "public class PagesBookEntity {\n public List<BookEntity> list;\n public int totalCount;\n}" } ]
import com.main.schema.BookEntity; import com.main.schema.PagesBookEntity; import com.netflix.graphql.dgs.DgsComponent; import com.netflix.graphql.dgs.DgsMutation; import com.netflix.graphql.dgs.DgsQuery; import com.netflix.graphql.dgs.InputArgument; import javax.annotation.Resource;
1,557
package com.main.book; @DgsComponent public class BookResolver { @Resource private BookService bookService; @DgsQuery
package com.main.book; @DgsComponent public class BookResolver { @Resource private BookService bookService; @DgsQuery
public PagesBookEntity findBookAll(@InputArgument Integer pageNumber, @InputArgument Integer pageSize) {
1
2023-10-30 14:38:00+00:00
2k
kdetard/koki
app/src/main/java/io/github/kdetard/koki/keycloak/RxRestKeycloak.java
[ { "identifier": "ResetPasswordResult", "path": "app/src/main/java/io/github/kdetard/koki/keycloak/models/ResetPasswordResult.java", "snippet": "public enum ResetPasswordResult {\n EMPTY(\"Empty response\"),\n FAILED_TO_SEND_MAIL(\"Failed to send mail\"),\n SPECIFY(\"Empty fields\"),\n TIMEOUT(\"Timeout\"),\n NULL(\"Null response\"),\n UNKNOWN(\"Unknown error occurred\"),\n SUCCESS(\"Success\"),\n ;\n\n private final String text;\n\n ResetPasswordResult(final String text) {\n this.text = text;\n }\n\n @NonNull\n @Override\n public String toString() {\n return text;\n }\n}" }, { "identifier": "SignUpResult", "path": "app/src/main/java/io/github/kdetard/koki/keycloak/models/SignUpResult.java", "snippet": "public enum SignUpResult {\n EMPTY(R.string.signup_empty_response),\n INVALID(R.string.signup_invalid_fields),\n SPECIFY(R.string.signup_empty_fields),\n TIMEOUT(R.string.signup_timeout),\n EMAIL_EXISTS(R.string.signup_email_exists),\n USERNAME_EXISTS(R.string.signup_username_exists),\n NULL(R.string.signup_null),\n UNKNOWN(R.string.signup_unknown),\n SUCCESS(R.string.signup_success),\n ;\n\n private final int resId;\n\n SignUpResult(final int resId) {\n this.resId = resId;\n }\n\n @NonNull\n public String getText(Context context) {\n return context.getString(resId);\n }\n}" }, { "identifier": "KeycloakGrantType", "path": "app/src/main/java/io/github/kdetard/koki/keycloak/models/KeycloakGrantType.java", "snippet": "public class KeycloakGrantType {\n /**\n * The grant type used for exchanging an authorization code for one or more tokens.\n *\n * @see \"The OAuth 2.0 Authorization Framework (RFC 6749), Section 4.1.3\n * <https://tools.ietf.org/html/rfc6749#section-4.1.3>\"\n */\n public static final String AUTHORIZATION_CODE = \"authorization_code\";\n\n /**\n * The grant type used when obtaining an access token.\n *\n * @see \"The OAuth 2.0 Authorization Framework (RFC 6749), Section 4.2\n * <https://tools.ietf.org/html/rfc6749#section-4.2>\"\n */\n public static final String IMPLICIT = \"implicit\";\n\n /**\n * The grant type used when obtaining an access token via password.\n *\n * @see \"The OAuth 2.0 Authorization Framework (RFC 6749), Section 6\n * <https://tools.ietf.org/html/rfc6749#section-4.3>\"\n */\n public static final String PASSWORD = \"password\";\n\n /**\n * The grant type used when exchanging a refresh token for a new token.\n *\n * @see \"The OAuth 2.0 Authorization Framework (RFC 6749), Section 6\n * <https://tools.ietf.org/html/rfc6749#section-6>\"\n */\n public static final String REFRESH_TOKEN = \"refresh_token\";\n}" } ]
import android.net.Uri; import com.tencent.mmkv.MMKV; import org.jsoup.Jsoup; import java.io.IOException; import java.util.Objects; import io.github.kdetard.koki.keycloak.models.ResetPasswordResult; import io.github.kdetard.koki.keycloak.models.SignUpResult; import io.github.kdetard.koki.keycloak.models.KeycloakConfig; import io.github.kdetard.koki.keycloak.models.KeycloakGrantType; import io.github.kdetard.koki.keycloak.models.KeycloakToken; import io.reactivex.rxjava3.annotations.NonNull; import io.reactivex.rxjava3.core.Completable; import io.reactivex.rxjava3.core.Single; import okhttp3.ResponseBody; import timber.log.Timber;
1,008
package io.github.kdetard.koki.keycloak; public class RxRestKeycloak extends RxKeycloak { public static @NonNull Single<KeycloakToken> newSession( final KeycloakApiService service, final KeycloakConfig config, final String username, final String password ) { return buildRequest(config) .flatMap(authRequest -> service.newSession( authRequest.configuration.tokenEndpoint.toString(), authRequest.clientId, username, password, KeycloakGrantType.PASSWORD )) .onErrorResumeNext(e -> { Timber.w(e, "Error occurred while signing in"); return Single.error(e); }); }
package io.github.kdetard.koki.keycloak; public class RxRestKeycloak extends RxKeycloak { public static @NonNull Single<KeycloakToken> newSession( final KeycloakApiService service, final KeycloakConfig config, final String username, final String password ) { return buildRequest(config) .flatMap(authRequest -> service.newSession( authRequest.configuration.tokenEndpoint.toString(), authRequest.clientId, username, password, KeycloakGrantType.PASSWORD )) .onErrorResumeNext(e -> { Timber.w(e, "Error occurred while signing in"); return Single.error(e); }); }
public static @NonNull Single<SignUpResult> createUser(
1
2023-10-30 00:44:59+00:00
2k
HiNinoJay/easyUsePoi
src/main/java/top/nino/easyUsePoi/web/TestController.java
[ { "identifier": "NinoWordUtil", "path": "src/main/java/top/nino/easyUsePoi/word/NinoWordUtil.java", "snippet": "@Slf4j\n@Component\npublic class NinoWordUtil {\n\n @Autowired\n private DocumentTool documentTool;\n\n /**\n * 读取json文件\n * @param json\n * @return\n */\n public WordJsonVo startFromJson(String json){\n // 通过URL去访问服务器上的资源\n URL url = null;\n try {\n url = new URL(json);\n URLConnection urlCon = url.openConnection();\n urlCon.connect(); //获取连接\n InputStream is = urlCon.getInputStream();\n BufferedReader buffer = new BufferedReader(new InputStreamReader(is));\n StringBuffer bs = new StringBuffer();\n String l = null;\n while((l = buffer.readLine()) != null){\n bs.append(l);\n }\n return JSONObject.parseObject(bs.toString(), WordJsonVo.class);\n } catch (IOException e) {\n e.printStackTrace();\n }\n return null;\n }\n\n public WordJsonVo readFromLocalJson() {\n try {\n ClassPathResource resource = new ClassPathResource(\"wordJson.json\");\n BufferedReader buffer = new BufferedReader(new InputStreamReader(resource.getInputStream()));\n StringBuffer bs = new StringBuffer();\n String l = null;\n while((l = buffer.readLine()) != null){\n bs.append(l);\n }\n WordJsonVo wordInfo = JSON.parseObject(bs.toString(), WordJsonVo.class);\n return wordInfo;\n } catch (Exception e) {\n // 处理异常\n e.printStackTrace();\n return null;\n }\n }\n\n /**\n * 根据 WordJsonVo 生成数据\n * @param wordJsonVo\n */\n public XWPFDocument constructWordByVo(WordJsonVo wordJsonVo) {\n return documentTool.constructWordByVo(wordJsonVo);\n }\n\n\n /**\n * 自定义文件名\n * @param xwpfDocument\n * @param fileName\n */\n public void exportWord(XWPFDocument xwpfDocument, String fileName) {\n documentTool.exportWord(xwpfDocument, fileName);\n }\n\n /**\n * 生成该word, 文件名默认\n *\n * @param docxDocument\n */\n public void exportWord(XWPFDocument docxDocument) {\n documentTool.exportWord(docxDocument);\n }\n}" }, { "identifier": "WordJsonVo", "path": "src/main/java/top/nino/easyUsePoi/word/module/data/WordJsonVo.java", "snippet": "@Data\npublic class WordJsonVo {\n\n /**\n * 一些提前准备的数据\n */\n private HashMap<String, String> preData;\n\n\n /**\n * 该word的组成\n */\n private List<WordModule> wordBody;\n\n}" } ]
import com.alibaba.fastjson.JSON; import org.apache.poi.xwpf.usermodel.XWPFDocument; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.ClassPathResource; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import top.nino.easyUsePoi.word.NinoWordUtil; import top.nino.easyUsePoi.word.module.data.WordJsonVo; import java.io.InputStreamReader;
877
package top.nino.easyUsePoi.web; /** * @Author:zengzhj * @Date:2023/10/31 20:20 */ @RequestMapping("/nino") @RestController public class TestController { @Autowired private NinoWordUtil ninoWordUtil; @GetMapping("/testWord") public void test() {
package top.nino.easyUsePoi.web; /** * @Author:zengzhj * @Date:2023/10/31 20:20 */ @RequestMapping("/nino") @RestController public class TestController { @Autowired private NinoWordUtil ninoWordUtil; @GetMapping("/testWord") public void test() {
WordJsonVo wordJsonVo = ninoWordUtil.readFromLocalJson();
1
2023-10-31 19:43:22+00:00
2k
Verionn/MoneyMinder
src/main/java/com/minder/MoneyMinder/controllers/purchasedItem/PurchasedItemController.java
[ { "identifier": "CategoryRepository", "path": "src/main/java/com/minder/MoneyMinder/repositories/CategoryRepository.java", "snippet": "@Repository\npublic interface CategoryRepository extends JpaRepository<CategoryEntity, Long> {\n}" }, { "identifier": "PurchasedItemRepository", "path": "src/main/java/com/minder/MoneyMinder/repositories/PurchasedItemRepository.java", "snippet": "@Repository\npublic interface PurchasedItemRepository extends JpaRepository<PurchasedItemEntity, Long> {\n @Query(\"SELECT l FROM PurchasedItemEntity l WHERE l.categoryId = :categoryId\")\n List<PurchasedItemEntity> findAllByCategoryId(Long categoryId);\n\n @Query(\"SELECT DISTINCT l FROM PurchasedItemEntity l WHERE l.name LIKE :prefix || '%'\")\n List<PurchasedItemEntity> findAllByPrefix(String prefix);\n\n @Query(\"SELECT l FROM PurchasedItemEntity l WHERE l.categoryId = :categoryId AND FUNCTION('DATEDIFF', DAY, l.timeBought, CURRENT_DATE()) <= :days\")\n List<PurchasedItemEntity> findAllByCategoryIdInLastNDays(Long categoryId, Long days);\n\n @Query(\"SELECT l FROM PurchasedItemEntity l WHERE FUNCTION('DATEDIFF', DAY, l.timeBought, CURRENT_DATE()) <= :days\")\n List<PurchasedItemEntity> findAllInLastNDays(Long days);\n\n @Query(\"SELECT l FROM PurchasedItemEntity l ORDER BY timeBought DESC LIMIT :amountOfItems\")\n List<PurchasedItemEntity> findAllByDateBought(Long amountOfItems);\n\n @Query(\"SELECT l FROM PurchasedItemEntity l WHERE l.listId = :listId\")\n List<PurchasedItemEntity> findAllByListId(Long listId);\n}" }, { "identifier": "ItemService", "path": "src/main/java/com/minder/MoneyMinder/services/ItemService.java", "snippet": "public interface ItemService {\n\n ItemEntity addItem(ItemEntity itemEntity, Long listId);\n\n Optional<ItemEntity> getItem(Long itemId);\n\n List<ItemEntity> getItemsByListId(Long listId);\n\n void deleteItem(Long itemID);\n\n Optional<ItemEntity> updateItem(Long itemId, UpdateItemRequestBody updateItemRequestBody);\n\n boolean existsById(Long itemId);\n\n void deleteItemsByListId(Long listId);\n\n PurchasedItemResponse markItemAsPurchased(PurchasedItemRecord purchasedItemRecord);\n\n boolean checkIfItemIsOnTheList(Long itemId, Long listId);\n}" }, { "identifier": "ListService", "path": "src/main/java/com/minder/MoneyMinder/services/ListService.java", "snippet": "public interface ListService {\n\n Optional<ListEntity> getList(Long listId);\n\n List<ListEntity> getLists();\n\n ListEntity addList(ListEntity listEntity);\n\n void deleteList(Long listId);\n\n Optional<ListEntity> updateList(Long listId, UpdateListRequestBody updateListRequestBody);\n\n double getFullPrice(Long listId);\n\n boolean existsById(Long listId);\n}" }, { "identifier": "PurchasedItemService", "path": "src/main/java/com/minder/MoneyMinder/services/PurchasedItemService.java", "snippet": "public interface PurchasedItemService {\n List<PurchasedItemResponse> getPurchasedItemsByCategoryId(Long categoryId);\n\n PurchasedItemNameListResponse getPurchasedItemNamesByPrefix(String prefix);\n\n List<PurchasedItemResponse> getPurchasedItemsByCategoryIdInLastNDays(Long categoryId, Long days);\n\n List<PurchasedItemResponse> getPurchasedItemsInLastNDays(Long days);\n\n List<PurchasedItemResponse> getLastNPurchasedItems(Long amountOfItems);\n\n List<PurchasedItemResponse> getPurchasedItemsFromList(Long listId);\n}" } ]
import com.minder.MoneyMinder.controllers.purchasedItem.dto.PurchasedItemListResponse; import com.minder.MoneyMinder.controllers.purchasedItem.dto.PurchasedItemNameListResponse; import com.minder.MoneyMinder.repositories.CategoryRepository; import com.minder.MoneyMinder.repositories.PurchasedItemRepository; import com.minder.MoneyMinder.services.ItemService; import com.minder.MoneyMinder.services.ListService; import com.minder.MoneyMinder.services.PurchasedItemService; import org.apache.coyote.Response; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping;
1,007
package com.minder.MoneyMinder.controllers.purchasedItem; @Controller @RequestMapping(path = "/purchasedItems") public class PurchasedItemController { private final PurchasedItemService purchasedItemService;
package com.minder.MoneyMinder.controllers.purchasedItem; @Controller @RequestMapping(path = "/purchasedItems") public class PurchasedItemController { private final PurchasedItemService purchasedItemService;
private final PurchasedItemRepository purchasedItemRepository;
1
2023-10-25 12:45:10+00:00
2k
inceptive-tech/ENTSOEDataRetrieval
src/main/java/tech/inceptive/ai4czc/entsoedataretrieval/fetcher/DisponibilityChecker.java
[ { "identifier": "DataRetrievalError", "path": "src/main/java/tech/inceptive/ai4czc/entsoedataretrieval/exceptions/DataRetrievalError.java", "snippet": "public class DataRetrievalError extends RuntimeException{\n private static final Logger LOGGER = LogManager.getLogger(DataRetrievalError.class);\n\n public DataRetrievalError(String message) {\n super(message);\n }\n\n public DataRetrievalError(String message, Throwable cause) {\n super(message, cause);\n }\n\n public DataRetrievalError(Throwable cause) {\n super(cause);\n }\n \n \n}" }, { "identifier": "Area", "path": "src/main/java/tech/inceptive/ai4czc/entsoedataretrieval/fetcher/inputs/Area.java", "snippet": "public enum Area {\n MONTENEGRO(\"10YCS-CG-TSO---S\", \"BZN|ME, CTA|ME, Montenegro (ME), MBA|ME, SCA|ME, LFA|ME\",\n \"Montenegro\", \"ME\"),\n ITALY_CENTRE_SOUTH(\"10Y1001A1001A71M\", \"BZN|IT-Centre-South, SCA|IT-Centre-South, MBA|IT-Z-Centre-South\",\n \"Italy Centre South\", \"IT-CS\"),\n BOSNIA(\"10YBA-JPCC-----D\", \"LFA|BA, BZN|BA, CTA|BA, Bosnia and Herz. (BA), SCA|BA, MBA|BA\",\n \"Bosnia\", \"BA\"),\n SERBIA(\"10YCS-SERBIATSOV\", \"LFA|RS, SCA|RS, MBA|RS, Serbia (RS), CTA|RS, BZN|RS\",\n \"Serbia\", \"RS\"),\n KOSOVO(\"10Y1001C--00100H\", \"BZN|XK, CTA|XK, Kosovo (XK), MBA|XK, LFB|XK, LFA|XK\",\n \"Kosovo\", \"XK\"),\n ALBANIA(\"10YAL-KESH-----5\", \"LFB|AL, LFA|AL, BZN|AL, CTA|AL, Albania (AL), SCA|AL, MBA|AL\", \n \"Albania\", \"AL\");\n\n private static final Logger LOGGER = LogManager.getLogger(Area.class);\n\n private static final Map<String, Area> CLIID_TO_AREA = new HashMap<>();\n private static final Map<String, Area> ID_TO_AREA = new HashMap<>();\n\n static {\n for (Area area : Area.values()) {\n CLIID_TO_AREA.put(area.getOptionCLIID(), area);\n ID_TO_AREA.put(area.getId(), area);\n }\n }\n\n private final String id;\n private final String longDescription;\n private final String prettyName;\n private final String optionCLIID;\n\n private Area(String id, String longDescription, String prettyName, String optionCLIID) {\n this.id = id;\n this.longDescription = longDescription;\n this.prettyName = prettyName;\n this.optionCLIID = optionCLIID;\n }\n\n /**\n *\n * @return\n */\n public String getId() {\n return id;\n }\n\n /**\n * The long description as presented on ENTSOE platform\n *\n * @return\n */\n public String getLongDescription() {\n return longDescription;\n }\n\n /**\n * Pretty name of the selected area\n *\n * @return\n */\n public String getPrettyName() {\n return prettyName;\n }\n\n /**\n * The ID on the CLI interface\n *\n * @return\n */\n public String getOptionCLIID() {\n return optionCLIID;\n }\n\n public static Area fromCLIID(String cliId) {\n if (cliId == null) {\n throw new IllegalArgumentException(\"Id cannot be null\");\n }\n\n Area area = CLIID_TO_AREA.get(cliId);\n if (area == null) {\n throw new IllegalArgumentException(\"No enum instance found with id: \" + cliId);\n }\n return area;\n }\n\n public static Area fromID(String id) {\n if (id == null) {\n throw new IllegalArgumentException(\"Id cannot be null\");\n }\n Area area = ID_TO_AREA.get(id);\n if (area == null) {\n throw new IllegalArgumentException(\"Non enum instance found with id:\" + id);\n }\n return area;\n }\n\n}" } ]
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.type.TypeFactory; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import java.io.IOException; import java.io.InputStream; import java.time.LocalDate; import java.time.LocalDateTime; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.logging.Level; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import tech.inceptive.ai4czc.entsoedataretrieval.exceptions.DataRetrievalError; import tech.inceptive.ai4czc.entsoedataretrieval.fetcher.inputs.Area;
1,564
/* * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template */ package tech.inceptive.ai4czc.entsoedataretrieval.fetcher; /** * The class to verify if a data column is available at ENTSOE platform at a given date. Some data are not available * until a specific date. This class provides a method to check it. * * @author Andres Bel Alonso */ public class DisponibilityChecker { private static final Logger LOGGER = LogManager.getLogger(DisponibilityChecker.class); private static record Entry(String article, Area area) { } ; private static record SourceEntry(String article, Area area, LocalDateTime startDt) { } ; /** * Key : area + data type * Value : start of availability date */ public Map<Entry, LocalDateTime> availabilityIndex; public DisponibilityChecker() { InputStream is = DisponibilityChecker.class.getResourceAsStream("availability.json"); availabilityIndex = new HashMap<>(); ObjectMapper objectMapper = new ObjectMapper(); objectMapper.registerModule(new JavaTimeModule()); try { List<SourceEntry> sourceEntries = objectMapper.readValue(is, TypeFactory.defaultInstance().constructCollectionLikeType(List.class, SourceEntry.class)); for (SourceEntry curEntry : sourceEntries) { availabilityIndex.put(new Entry(curEntry.article, curEntry.area), curEntry.startDt); } } catch (IOException ex) {
/* * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template */ package tech.inceptive.ai4czc.entsoedataretrieval.fetcher; /** * The class to verify if a data column is available at ENTSOE platform at a given date. Some data are not available * until a specific date. This class provides a method to check it. * * @author Andres Bel Alonso */ public class DisponibilityChecker { private static final Logger LOGGER = LogManager.getLogger(DisponibilityChecker.class); private static record Entry(String article, Area area) { } ; private static record SourceEntry(String article, Area area, LocalDateTime startDt) { } ; /** * Key : area + data type * Value : start of availability date */ public Map<Entry, LocalDateTime> availabilityIndex; public DisponibilityChecker() { InputStream is = DisponibilityChecker.class.getResourceAsStream("availability.json"); availabilityIndex = new HashMap<>(); ObjectMapper objectMapper = new ObjectMapper(); objectMapper.registerModule(new JavaTimeModule()); try { List<SourceEntry> sourceEntries = objectMapper.readValue(is, TypeFactory.defaultInstance().constructCollectionLikeType(List.class, SourceEntry.class)); for (SourceEntry curEntry : sourceEntries) { availabilityIndex.put(new Entry(curEntry.article, curEntry.area), curEntry.startDt); } } catch (IOException ex) {
throw new DataRetrievalError(ex);
0
2023-10-30 09:09:53+00:00
2k
NUMS-half/OnlineOA
src/main/java/cn/edu/neu/onlineoa/controller/UserMultiQueryServlet.java
[ { "identifier": "User", "path": "src/main/java/cn/edu/neu/onlineoa/bean/User.java", "snippet": "public class User {\n private String uid;\n private String username;\n private String password;\n private int identityId = -1;\n\n public User() {}\n\n public User(String uid, String username, String password, int identityId) {\n this.username = username;\n this.password = password;\n this.uid = uid;\n this.identityId = identityId;\n }\n\n public String getUsername() {\n return username;\n }\n\n public void setUsername(String username) {\n this.username = username;\n }\n\n public String getPassword() {\n return password;\n }\n\n public void setPassword(String password) {\n this.password = password;\n }\n\n public String getUid() {\n return uid;\n }\n\n public void setUid(String uid) {\n this.uid = uid;\n }\n\n public int getIdentityId() {\n return identityId;\n }\n\n public void setIdentityId(int identityId) {\n this.identityId = identityId;\n }\n\n @Override\n public String toString() {\n return \"User{\" +\n \"uid='\" + uid + '\\'' +\n \", username='\" + username + '\\'' +\n \", password='\" + password + '\\'' +\n \", identityId=\" + identityId +\n '}';\n }\n}" }, { "identifier": "UserService", "path": "src/main/java/cn/edu/neu/onlineoa/service/UserService.java", "snippet": "public class UserService {\n\n SqlSessionFactory sqlSessionFactory = MybatisUtils.getSessionFactoryInstance();\n\n public List<User> findAllUser() {\n try ( SqlSession sqlSession = sqlSessionFactory.openSession() ) {\n UserDao userDao = sqlSession.getMapper(UserDao.class);\n return userDao.findAllUser();\n }\n }\n\n public List<User> findAllTeacher() {\n try ( SqlSession sqlSession = sqlSessionFactory.openSession() ) {\n UserDao userDao = sqlSession.getMapper(UserDao.class);\n return userDao.findAllTeacher();\n }\n }\n\n public List<User> findAllHeadTeacher() {\n try ( SqlSession sqlSession = sqlSessionFactory.openSession() ) {\n UserDao userDao = sqlSession.getMapper(UserDao.class);\n return userDao.findAllHeadTeacher();\n }\n }\n\n public User findUserByUid(String uid) {\n try ( SqlSession sqlSession = sqlSessionFactory.openSession() ) {\n UserDao userDao = sqlSession.getMapper(UserDao.class);\n return userDao.findUserByUid(uid);\n }\n }\n\n public int deleteUserByUid(String uid) {\n try ( SqlSession sqlSession = sqlSessionFactory.openSession(true) ) {\n UserDao userDao = sqlSession.getMapper(UserDao.class);\n return userDao.deleteUserByUid(uid);\n } catch ( Exception e ) {\n return 0;\n }\n }\n\n public int addUser(User user) {\n try ( SqlSession sqlSession = sqlSessionFactory.openSession(true) ) {\n UserDao userDao = sqlSession.getMapper(UserDao.class);\n return userDao.addUser(user);\n } catch ( Exception e ) {\n return 0;\n }\n }\n\n public int updateUser(User user) {\n try ( SqlSession sqlSession = sqlSessionFactory.openSession(true) ) {\n UserDao userDao = sqlSession.getMapper(UserDao.class);\n return userDao.updateUser(user);\n } catch ( Exception e ) {\n return 0;\n }\n }\n\n public List<User> findUserWithMultiCondition(User user) {\n try ( SqlSession sqlSession = sqlSessionFactory.openSession() ) {\n UserDao userDao = sqlSession.getMapper(UserDao.class);\n return userDao.findUserWithMultiCondition(user);\n }\n }\n\n}" } ]
import cn.edu.neu.onlineoa.bean.User; import cn.edu.neu.onlineoa.service.UserService; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.List;
1,203
package cn.edu.neu.onlineoa.controller; @WebServlet(name = "UserMultiQueryServlet", urlPatterns = "/queryUser") public class UserMultiQueryServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String uid = req.getParameter("uid"); String username = req.getParameter("username"); String identityStr = req.getParameter("identity"); String pageNumStr = req.getParameter("pageNum"); String pageSizeStr = req.getParameter("pageSize"); int pageNum = 1; int pageSize = 10; int identity = -1; if ( pageNumStr != null && !pageNumStr.isEmpty() ) pageNum = Integer.parseInt(pageNumStr); if ( pageSizeStr != null && !pageSizeStr.isEmpty() ) pageSize = Integer.parseInt(pageSizeStr); if ( identityStr != null ) identity = Integer.parseInt(identityStr); if ( !uid.equals("") || !username.equals("") || identity != -1 ) { User userQuery = new User(); userQuery.setUid(uid); userQuery.setUsername(username); userQuery.setIdentityId(identity);
package cn.edu.neu.onlineoa.controller; @WebServlet(name = "UserMultiQueryServlet", urlPatterns = "/queryUser") public class UserMultiQueryServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String uid = req.getParameter("uid"); String username = req.getParameter("username"); String identityStr = req.getParameter("identity"); String pageNumStr = req.getParameter("pageNum"); String pageSizeStr = req.getParameter("pageSize"); int pageNum = 1; int pageSize = 10; int identity = -1; if ( pageNumStr != null && !pageNumStr.isEmpty() ) pageNum = Integer.parseInt(pageNumStr); if ( pageSizeStr != null && !pageSizeStr.isEmpty() ) pageSize = Integer.parseInt(pageSizeStr); if ( identityStr != null ) identity = Integer.parseInt(identityStr); if ( !uid.equals("") || !username.equals("") || identity != -1 ) { User userQuery = new User(); userQuery.setUid(uid); userQuery.setUsername(username); userQuery.setIdentityId(identity);
UserService userService = new UserService();
1
2023-10-31 04:50:21+00:00
2k
SUFIAG/Message-Publisher-To-Amazon-SNS-Java-AWS
src/main/java/com/contactsunny/poc/AmazonSNSPublisherPOC/App.java
[ { "identifier": "SamsungPhone", "path": "src/main/java/com/contactsunny/poc/AmazonSNSPublisherPOC/models/SamsungPhone.java", "snippet": "public class SamsungPhone {\n\n private String name;\n private String description;\n private long timestamp;\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getDescription() {\n return description;\n }\n\n public void setDescription(String description) {\n this.description = description;\n }\n\n public long getTimestamp() {\n return timestamp;\n }\n\n public void setTimestamp(long timestamp) {\n this.timestamp = timestamp;\n }\n}" }, { "identifier": "SNSUtil", "path": "src/main/java/com/contactsunny/poc/AmazonSNSPublisherPOC/utils/SNSUtil.java", "snippet": "@Component\npublic class SNSUtil {\n\n @Value(\"${sns.topic.arn}\")\n private String snsTopicARN;\n\n @Value(\"${aws.accessKey}\")\n private String awsAccessKey;\n\n @Value(\"${aws.secretKey}\")\n private String awsSecretKey;\n\n @Value(\"${aws.region}\")\n private String awsRegion;\n\n private AmazonSNS amazonSNS;\n\n private static final Logger logger = LoggerFactory.getLogger(SNSUtil.class);\n\n @PostConstruct\n private void postConstructor() {\n\n logger.info(\"SQS URL: \" + snsTopicARN);\n\n AWSCredentialsProvider awsCredentialsProvider = new AWSStaticCredentialsProvider(\n new BasicAWSCredentials(awsAccessKey, awsSecretKey)\n );\n\n this.amazonSNS = AmazonSNSClientBuilder.standard()\n .withCredentials(awsCredentialsProvider)\n .withRegion(awsRegion)\n .build();\n }\n\n public void publishSNSMessage(String message) {\n\n logger.info(\"Publishing SNS message: \" + message);\n\n PublishResult result = this.amazonSNS.publish(this.snsTopicARN, message);\n\n logger.info(\"SNS Message ID: \" + result.getMessageId());\n }\n}" } ]
import com.contactsunny.poc.AmazonSNSPublisherPOC.models.SamsungPhone; import com.contactsunny.poc.AmazonSNSPublisherPOC.utils.SNSUtil; import com.google.gson.Gson; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import java.util.ArrayList; import java.util.List;
673
package com.contactsunny.poc.AmazonSNSPublisherPOC; @SpringBootApplication public class App implements CommandLineRunner { @Autowired private SNSUtil snsUtil; public static void main(String[] args) { SpringApplication.run(App.class, args); } @Override public void run(String... args) throws Exception {
package com.contactsunny.poc.AmazonSNSPublisherPOC; @SpringBootApplication public class App implements CommandLineRunner { @Autowired private SNSUtil snsUtil; public static void main(String[] args) { SpringApplication.run(App.class, args); } @Override public void run(String... args) throws Exception {
List<SamsungPhone> samsungPhones = new ArrayList<>();
0
2023-10-25 22:44:39+00:00
2k
TNO/PPS
plugins/nl.esi.pps.architecture/src-gen/nl/esi/pps/architecture/instantiated/util/InstantiatedAdapterFactory.java
[ { "identifier": "PropertiesContainer", "path": "plugins/nl.esi.emf.properties/src-gen/nl/esi/emf/properties/PropertiesContainer.java", "snippet": "public interface PropertiesContainer extends EObject {\n\t/**\n\t * Returns the value of the '<em><b>Properties</b></em>' map.\n\t * The key is of type {@link java.lang.String},\n\t * and the value is of type {@link java.io.Serializable},\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * <!-- begin-model-doc -->\n\t * <br><br>\n\t * <b>Deprecated:</b> Properties should only be used from an Xtend context using {@link nl.esi.emf.properties.xtend.PersistedProperty}.\n\t * \n\t * @deprecated\n\t * <!-- end-model-doc -->\n\t * @return the value of the '<em>Properties</em>' map.\n\t * @see nl.esi.emf.properties.PropertiesPackage#getPropertiesContainer_Properties()\n\t * @model mapType=\"nl.esi.emf.properties.PropertyMapEntry&lt;org.eclipse.emf.ecore.EString, nl.esi.emf.properties.EPropertyValue&gt;\"\n\t * @generated\n\t */\n\t@Deprecated\n\tEMap<String, Serializable> getProperties();\n\n} // PropertiesContainer" }, { "identifier": "NamedArchitectureElement", "path": "plugins/nl.esi.pps.architecture/src-gen/nl/esi/pps/architecture/NamedArchitectureElement.java", "snippet": "public interface NamedArchitectureElement extends PropertiesContainer {\n\t/**\n\t * Returns the value of the '<em><b>Name</b></em>' attribute.\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @return the value of the '<em>Name</em>' attribute.\n\t * @see #setName(String)\n\t * @see nl.esi.pps.architecture.ArchitecturePackage#getNamedArchitectureElement_Name()\n\t * @model\n\t * @generated\n\t */\n\tString getName();\n\n\t/**\n\t * Sets the value of the '{@link nl.esi.pps.architecture.NamedArchitectureElement#getName <em>Name</em>}' attribute.\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @param value the new value of the '<em>Name</em>' attribute.\n\t * @see #getName()\n\t * @generated\n\t */\n\tvoid setName(String value);\n\n} // NamedArchitectureElement" } ]
import nl.esi.emf.properties.PropertiesContainer; import nl.esi.pps.architecture.NamedArchitectureElement; import nl.esi.pps.architecture.instantiated.*; import org.eclipse.emf.common.notify.Adapter; import org.eclipse.emf.common.notify.Notifier; import org.eclipse.emf.common.notify.impl.AdapterFactoryImpl; import org.eclipse.emf.ecore.EObject;
1,082
/** */ package nl.esi.pps.architecture.instantiated.util; /** * <!-- begin-user-doc --> * The <b>Adapter Factory</b> for the model. * It provides an adapter <code>createXXX</code> method for each class of the model. * <!-- end-user-doc --> * @see nl.esi.pps.architecture.instantiated.InstantiatedPackage * @generated */ public class InstantiatedAdapterFactory extends AdapterFactoryImpl { /** * The cached model package. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected static InstantiatedPackage modelPackage; /** * Creates an instance of the adapter factory. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public InstantiatedAdapterFactory() { if (modelPackage == null) { modelPackage = InstantiatedPackage.eINSTANCE; } } /** * Returns whether this factory is applicable for the type of the object. * <!-- begin-user-doc --> * This implementation returns <code>true</code> if the object is either the model's package or is an instance object of the model. * <!-- end-user-doc --> * @return whether this factory is applicable for the type of the object. * @generated */ @Override public boolean isFactoryForType(Object object) { if (object == modelPackage) { return true; } if (object instanceof EObject) { return ((EObject) object).eClass().getEPackage() == modelPackage; } return false; } /** * The switch that delegates to the <code>createXXX</code> methods. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected InstantiatedSwitch<Adapter> modelSwitch = new InstantiatedSwitch<Adapter>() { @Override public Adapter caseExecutor(Executor object) { return createExecutorAdapter(); } @Override public Adapter caseExecutorGroup(ExecutorGroup object) { return createExecutorGroupAdapter(); } @Override
/** */ package nl.esi.pps.architecture.instantiated.util; /** * <!-- begin-user-doc --> * The <b>Adapter Factory</b> for the model. * It provides an adapter <code>createXXX</code> method for each class of the model. * <!-- end-user-doc --> * @see nl.esi.pps.architecture.instantiated.InstantiatedPackage * @generated */ public class InstantiatedAdapterFactory extends AdapterFactoryImpl { /** * The cached model package. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected static InstantiatedPackage modelPackage; /** * Creates an instance of the adapter factory. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public InstantiatedAdapterFactory() { if (modelPackage == null) { modelPackage = InstantiatedPackage.eINSTANCE; } } /** * Returns whether this factory is applicable for the type of the object. * <!-- begin-user-doc --> * This implementation returns <code>true</code> if the object is either the model's package or is an instance object of the model. * <!-- end-user-doc --> * @return whether this factory is applicable for the type of the object. * @generated */ @Override public boolean isFactoryForType(Object object) { if (object == modelPackage) { return true; } if (object instanceof EObject) { return ((EObject) object).eClass().getEPackage() == modelPackage; } return false; } /** * The switch that delegates to the <code>createXXX</code> methods. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected InstantiatedSwitch<Adapter> modelSwitch = new InstantiatedSwitch<Adapter>() { @Override public Adapter caseExecutor(Executor object) { return createExecutorAdapter(); } @Override public Adapter caseExecutorGroup(ExecutorGroup object) { return createExecutorGroupAdapter(); } @Override
public Adapter casePropertiesContainer(PropertiesContainer object) {
0
2023-10-30 16:00:25+00:00
2k
CERBON-MODS/Bosses-of-Mass-Destruction-FORGE
src/main/java/com/cerbon/bosses_of_mass_destruction/entity/custom/gauntlet/GauntletAttacks.java
[ { "identifier": "GauntletConfig", "path": "src/main/java/com/cerbon/bosses_of_mass_destruction/config/mob/GauntletConfig.java", "snippet": "public class GauntletConfig {\n public double health = 250.0;\n public double armor = 8.0;\n public double attack = 16.0;\n public float idleHealingPerTick = 0.5f;\n\n @ConfigEntry.BoundedDiscrete(min = 0, max = 10000)\n public int experienceDrop = 1000;\n public boolean spawnAncientDebrisOnDeath = true;\n public double energizedPunchExplosionSize = 4.5;\n public double normalPunchExplosionMultiplier = 1.5;\n}" }, { "identifier": "CooldownAction", "path": "src/main/java/com/cerbon/bosses_of_mass_destruction/entity/ai/action/CooldownAction.java", "snippet": "public class CooldownAction implements IAction, IActionStop {\n private final IActionWithCooldown action;\n private final int initialCooldown;\n private int currentTime;\n\n public CooldownAction(IActionWithCooldown action, int initialCooldown) {\n this.action = action;\n this.initialCooldown = initialCooldown;\n this.currentTime = initialCooldown;\n }\n\n @Override\n public void perform() {\n currentTime--;\n\n if (currentTime <= 0)\n currentTime = action.perform();\n }\n\n @Override\n public void stop() {\n currentTime = Math.max(currentTime, initialCooldown);\n }\n}" }, { "identifier": "IActionStop", "path": "src/main/java/com/cerbon/bosses_of_mass_destruction/entity/ai/action/IActionStop.java", "snippet": "public interface IActionStop {\n void stop();\n}" }, { "identifier": "IActionWithCooldown", "path": "src/main/java/com/cerbon/bosses_of_mass_destruction/entity/ai/action/IActionWithCooldown.java", "snippet": "public interface IActionWithCooldown {\n int perform();\n}" }, { "identifier": "ActionGoal", "path": "src/main/java/com/cerbon/bosses_of_mass_destruction/entity/ai/goals/ActionGoal.java", "snippet": "public class ActionGoal extends Goal {\n private final Supplier<Boolean> hasTarget;\n private final Supplier<Boolean> canContinue;\n private IAction tickAction = () -> {};\n private IAction startAction = () -> {};\n private IActionStop endAction = () -> {};\n\n public ActionGoal(Supplier<Boolean> hasTarget, Supplier<Boolean> canContinue, IAction tickAction, IAction startAction, IActionStop endAction) {\n this.hasTarget = hasTarget;\n this.canContinue = canContinue != null ? canContinue : hasTarget;\n this.tickAction = tickAction != null ? tickAction : this.tickAction;\n this.startAction = startAction != null ? startAction : this.startAction;\n this.endAction = endAction != null ? endAction : this.endAction;\n }\n\n @Override\n public boolean canUse() {\n return hasTarget.get();\n }\n\n @Override\n public boolean requiresUpdateEveryTick() {\n return true;\n }\n\n @Override\n public boolean canContinueToUse() {\n return canContinue.get();\n }\n\n @Override\n public void start() {\n startAction.perform();\n }\n\n @Override\n public void tick() {\n tickAction.perform();\n }\n\n @Override\n public void stop() {\n endAction.stop();\n }\n}" } ]
import com.cerbon.bosses_of_mass_destruction.config.mob.GauntletConfig; import com.cerbon.bosses_of_mass_destruction.entity.ai.action.CooldownAction; import com.cerbon.bosses_of_mass_destruction.entity.ai.action.IActionStop; import com.cerbon.bosses_of_mass_destruction.entity.ai.action.IActionWithCooldown; import com.cerbon.bosses_of_mass_destruction.entity.ai.goals.ActionGoal; import com.cerbon.cerbons_api.api.general.event.EventScheduler; import net.minecraft.server.level.ServerLevel; import java.util.Map; import java.util.function.Supplier;
1,275
package com.cerbon.bosses_of_mass_destruction.entity.custom.gauntlet; public class GauntletAttacks { private final GauntletEntity entity; private final GauntletMoveLogic moveLogic; public static final byte punchAttack = 4; public static final byte stopPunchAnimation = 5; public static final byte stopAttackAnimation = 6; public static final byte stopPoundAnimation = 7; public static final byte laserAttack = 8; public static final byte laserAttackStop = 9; public static final byte swirlPunchAttack = 10; public static final byte blindnessAttack = 11; public GauntletAttacks(GauntletEntity entity, EventScheduler eventScheduler, GauntletConfig mobConfig, ServerLevel serverLevel) { this.entity = entity; Supplier<Boolean> cancelAttackAction = () -> entity.isDeadOrDying() || entity.getTarget() == null; Map<Byte, IActionWithCooldown> statusRegistry = Map.of( punchAttack, new PunchAction(entity, eventScheduler, mobConfig, cancelAttackAction, serverLevel), laserAttack, new LaserAction(entity, eventScheduler, cancelAttackAction, serverLevel), swirlPunchAttack, new SwirlPunchAction(entity, eventScheduler, mobConfig, cancelAttackAction, serverLevel), blindnessAttack, new BlindnessAction(entity, eventScheduler, cancelAttackAction, serverLevel) ); this.moveLogic = new GauntletMoveLogic(statusRegistry, entity, entity.damageMemory); } public ActionGoal buildAttackGoal(){
package com.cerbon.bosses_of_mass_destruction.entity.custom.gauntlet; public class GauntletAttacks { private final GauntletEntity entity; private final GauntletMoveLogic moveLogic; public static final byte punchAttack = 4; public static final byte stopPunchAnimation = 5; public static final byte stopAttackAnimation = 6; public static final byte stopPoundAnimation = 7; public static final byte laserAttack = 8; public static final byte laserAttackStop = 9; public static final byte swirlPunchAttack = 10; public static final byte blindnessAttack = 11; public GauntletAttacks(GauntletEntity entity, EventScheduler eventScheduler, GauntletConfig mobConfig, ServerLevel serverLevel) { this.entity = entity; Supplier<Boolean> cancelAttackAction = () -> entity.isDeadOrDying() || entity.getTarget() == null; Map<Byte, IActionWithCooldown> statusRegistry = Map.of( punchAttack, new PunchAction(entity, eventScheduler, mobConfig, cancelAttackAction, serverLevel), laserAttack, new LaserAction(entity, eventScheduler, cancelAttackAction, serverLevel), swirlPunchAttack, new SwirlPunchAction(entity, eventScheduler, mobConfig, cancelAttackAction, serverLevel), blindnessAttack, new BlindnessAction(entity, eventScheduler, cancelAttackAction, serverLevel) ); this.moveLogic = new GauntletMoveLogic(statusRegistry, entity, entity.damageMemory); } public ActionGoal buildAttackGoal(){
CooldownAction attackAction = new CooldownAction(moveLogic, 80);
1
2023-10-25 16:28:17+00:00
2k
King-BR/Mindustry-Discord-Chat
src/discordchat/Discord/Commands/GameInfo.java
[ { "identifier": "worldLoad", "path": "src/discordchat/Mindustry/Events/worldLoad.java", "snippet": "public class worldLoad {\n public static boolean started = false;\n\n public static void run(DiscordApi bot, JSONObject config, EventType.WorldLoadEvent e) {\n if (started) return;\n started = true;\n\n String channelID = config.has(\"channel_announcement\") && !config.getString(\"channel_announcement\").isEmpty() ? config.getString(\"channel_announcement\") : config.getString(\"channel_chat\");\n\n Optional<ServerTextChannel> optionalChannel = bot.getServerTextChannelById(channelID);\n if (!optionalChannel.isPresent()) return;\n ServerTextChannel channel = optionalChannel.get();\n\n EmbedBuilder embed = new EmbedBuilder()\n .setTitle(\"Server online!\")\n .setColor(Color.green);\n\n if (config.has(\"server_ip\") && !config.getString(\"server_ip\").isEmpty()) embed.setDescription(\"**IP:** ```\" + config.getString(\"server_ip\") + \"```\");\n\n new MessageBuilder()\n .setEmbed(embed)\n .send(channel).join();\n }\n}" }, { "identifier": "Utils", "path": "src/discordchat/utils/Utils.java", "snippet": "public class Utils {\n public static String msToDuration(float millis, boolean shortTime) {\n if (millis < 0) throw new IllegalArgumentException(\"[DiscordChat] Duration must be greater than zero!\");\n\n if (!shortTime) {\n long hours = TimeUnit.MILLISECONDS.toHours((long) millis);\n millis -= TimeUnit.HOURS.toMillis(hours);\n long minutes = TimeUnit.MILLISECONDS.toMinutes((long) millis);\n millis -= TimeUnit.MINUTES.toMillis(minutes);\n long seconds = TimeUnit.MILLISECONDS.toSeconds((long) millis);\n\n return (hours + \" Hours \" + minutes + \" Minutes \" + seconds + \" Seconds\");\n } else {\n long minutes = TimeUnit.MILLISECONDS.toMinutes((long) millis);\n millis -= TimeUnit.MINUTES.toMillis(minutes);\n long seconds = TimeUnit.MILLISECONDS.toSeconds((long) millis);\n\n return (minutes + \" Minutes \" + seconds + \" Seconds\");\n }\n }\n}" } ]
import arc.util.Log; import arc.util.Strings; import discordchat.Mindustry.Events.worldLoad; import discordchat.utils.Utils; import mindustry.game.Team; import mindustry.game.Teams; import mindustry.gen.Groups; import mindustry.gen.Player; import mindustry.mod.Mods; import mindustry.world.blocks.storage.CoreBlock; import mindustry.world.modules.ItemModule; import org.javacord.api.DiscordApi; import org.javacord.api.entity.channel.ServerTextChannel; import org.javacord.api.entity.message.MessageBuilder; import org.javacord.api.entity.message.embed.EmbedBuilder; import org.javacord.api.event.message.MessageCreateEvent; import org.json.JSONObject; import java.awt.*; import static mindustry.Vars.mods; import static mindustry.Vars.state;
705
package discordchat.Discord.Commands; public class GameInfo { public GameInfo(DiscordApi bot, JSONObject config, MessageCreateEvent event, String[] args) { if (!event.getServerTextChannel().isPresent()) return; ServerTextChannel channel = event.getServerTextChannel().get();
package discordchat.Discord.Commands; public class GameInfo { public GameInfo(DiscordApi bot, JSONObject config, MessageCreateEvent event, String[] args) { if (!event.getServerTextChannel().isPresent()) return; ServerTextChannel channel = event.getServerTextChannel().get();
if (!worldLoad.started || !state.isPlaying()) {
0
2023-10-25 20:15:57+00:00
2k
RelativityMC/FlowSched
src/main/java/com/ishland/flowsched/executor/test/TestThroughput.java
[ { "identifier": "LockToken", "path": "src/main/java/com/ishland/flowsched/executor/LockToken.java", "snippet": "public interface LockToken {\n}" }, { "identifier": "ExecutorManager", "path": "src/main/java/com/ishland/flowsched/executor/ExecutorManager.java", "snippet": "public class ExecutorManager {\n\n private final DynamicPriorityQueue<Task> globalWorkQueue = new DynamicPriorityQueue<>(256);\n private final Object2ReferenceOpenHashMap<LockToken, Set<Task>> lockListeners = new Object2ReferenceOpenHashMap<>();\n private final SimpleObjectPool<Set<Task>> lockListenersPool = new SimpleObjectPool<>(\n pool -> new ReferenceArraySet<>(32),\n Set::clear,\n Set::clear,\n 4096\n );\n private final Object schedulingMutex = new Object();\n final Object workerMonitor = new Object();\n private final WorkerThread[] workerThreads;\n\n /**\n * Creates a new executor manager.\n *\n * @param workerThreadCount the number of worker threads.\n */\n public ExecutorManager(int workerThreadCount) {\n this(workerThreadCount, thread -> {});\n }\n\n /**\n * Creates a new executor manager.\n *\n * @param workerThreadCount the number of worker threads.\n * @param threadInitializer the thread initializer.\n */\n public ExecutorManager(int workerThreadCount, Consumer<Thread> threadInitializer) {\n workerThreads = new WorkerThread[workerThreadCount];\n for (int i = 0; i < workerThreadCount; i++) {\n final WorkerThread thread = new WorkerThread(this);\n threadInitializer.accept(thread);\n thread.start();\n workerThreads[i] = thread;\n }\n }\n\n /**\n * Attempt to lock the given tokens.\n * The caller should discard the task if this method returns false, as it reschedules the task.\n *\n * @return {@code true} if the lock is acquired, {@code false} otherwise.\n */\n boolean tryLock(Task task) {\n synchronized (this.schedulingMutex) {\n for (LockToken token : task.lockTokens()) {\n final Set<Task> listeners = this.lockListeners.get(token);\n if (listeners != null) {\n listeners.add(task);\n return false;\n }\n }\n for (LockToken token : task.lockTokens()) {\n assert !this.lockListeners.containsKey(token);\n this.lockListeners.put(token, this.lockListenersPool.alloc());\n }\n return true;\n }\n }\n\n /**\n * Release the locks held by the given task.\n * @param task the task.\n */\n void releaseLocks(Task task) {\n synchronized (this.schedulingMutex) {\n for (LockToken token : task.lockTokens()) {\n final Set<Task> listeners = this.lockListeners.remove(token);\n if (listeners != null) {\n for (Task listener : listeners) {\n this.schedule(listener);\n }\n this.lockListenersPool.release(listeners);\n } else {\n throw new IllegalStateException(\"Lock token \" + token + \" is not locked\");\n }\n }\n }\n }\n\n /**\n * Polls an executable task from the global work queue.\n * @return the task, or {@code null} if no task is executable.\n */\n Task pollExecutableTask() {\n synchronized (this.schedulingMutex) {\n Task task;\n while ((task = this.globalWorkQueue.dequeue()) != null) {\n if (this.tryLock(task)) {\n return task;\n }\n }\n }\n return null;\n }\n\n /**\n * Shuts down the executor manager.\n */\n public void shutdown() {\n for (WorkerThread workerThread : workerThreads) {\n workerThread.shutdown();\n }\n }\n\n /**\n * Schedules a task.\n * @param task the task.\n */\n public void schedule(Task task) {\n synchronized (this.schedulingMutex) {\n this.globalWorkQueue.enqueue(task, task.priority());\n }\n synchronized (this.workerMonitor) {\n this.workerMonitor.notify();\n }\n }\n\n /**\n * Schedules a runnable for execution with the given priority.\n *\n * @param runnable the runnable.\n * @param priority the priority.\n */\n public void schedule(Runnable runnable, int priority) {\n this.schedule(new SimpleTask(runnable, priority));\n }\n\n /**\n * Creates an executor that schedules runnables with the given priority.\n *\n * @param priority the priority.\n * @return the executor.\n */\n public Executor executor(int priority) {\n return runnable -> this.schedule(runnable, priority);\n }\n\n /**\n * Notifies the executor manager that the priority of the given task has changed.\n *\n * @param task the task.\n */\n public void notifyPriorityChange(Task task) {\n synchronized (this.schedulingMutex) {\n this.globalWorkQueue.changePriority(task, task.priority());\n }\n }\n\n}" }, { "identifier": "Task", "path": "src/main/java/com/ishland/flowsched/executor/Task.java", "snippet": "public interface Task {\n\n void run(Runnable releaseLocks);\n\n void propagateException(Throwable t);\n\n LockToken[] lockTokens();\n\n int priority();\n\n}" } ]
import com.ishland.flowsched.executor.LockToken; import com.ishland.flowsched.executor.ExecutorManager; import com.ishland.flowsched.executor.Task; import java.util.Arrays; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Semaphore; import java.util.concurrent.atomic.AtomicInteger;
1,412
package com.ishland.flowsched.executor.test; public class TestThroughput { private static final Semaphore semaphore = new Semaphore(1 << 7); public static volatile double accumulation = 0; public static volatile long[] latency = new long[1 << 20]; public static AtomicInteger counter = new AtomicInteger(); public static void main(String[] args) {
package com.ishland.flowsched.executor.test; public class TestThroughput { private static final Semaphore semaphore = new Semaphore(1 << 7); public static volatile double accumulation = 0; public static volatile long[] latency = new long[1 << 20]; public static AtomicInteger counter = new AtomicInteger(); public static void main(String[] args) {
final ExecutorManager manager = new ExecutorManager(4);
1
2023-10-25 10:07:17+00:00
2k
sinch/sinch-sdk-java
client/src/test/java/com/sinch/sdk/domains/verification/models/webhooks/VerificationRequestEventTest.java
[ { "identifier": "NumberIdentity", "path": "client/src/main/com/sinch/sdk/domains/verification/models/NumberIdentity.java", "snippet": "public class NumberIdentity extends Identity {\n\n private final String endpoint;\n\n public String getEndpoint() {\n return endpoint;\n }\n\n /**\n * @param endpoint An E.164-compatible phone number.\n */\n public NumberIdentity(String endpoint) {\n super(\"number\");\n this.endpoint = endpoint;\n }\n\n @Override\n public String toString() {\n return \"NumberIdentity{\" + \"endpoint='\" + endpoint + '\\'' + \"} \" + super.toString();\n }\n\n public static Builder builder() {\n return new Builder();\n }\n\n public static class Builder {\n\n String endpoint;\n\n private Builder() {}\n\n public Builder setEndpoint(String endpoint) {\n this.endpoint = endpoint;\n return this;\n }\n\n public NumberIdentity build() {\n return new NumberIdentity(endpoint);\n }\n }\n}" }, { "identifier": "Price", "path": "client/src/main/com/sinch/sdk/domains/verification/models/Price.java", "snippet": "public class Price {\n private final String currencyId;\n private final Float amount;\n\n /**\n * @param currencyId ISO 4217 currency code\n * @param amount The amount\n */\n public Price(String currencyId, Float amount) {\n this.currencyId = currencyId;\n this.amount = amount;\n }\n\n public String getCurrencyId() {\n return currencyId;\n }\n\n public Float getAmount() {\n return amount;\n }\n\n @Override\n public String toString() {\n return \"Price{\" + \"currencyId='\" + currencyId + '\\'' + \", amount=\" + amount + '}';\n }\n\n public static Builder builder() {\n return new Builder();\n }\n\n public static class Builder {\n\n String currencyId;\n Float amount;\n\n private Builder() {}\n\n public Builder setCurrencyId(String currencyId) {\n this.currencyId = currencyId;\n return this;\n }\n\n public Builder setAmount(Float amount) {\n this.amount = amount;\n return this;\n }\n\n public Price build() {\n return new Price(currencyId, amount);\n }\n }\n}" }, { "identifier": "VerificationId", "path": "client/src/main/com/sinch/sdk/domains/verification/models/VerificationId.java", "snippet": "public class VerificationId {\n\n public final String id;\n\n public VerificationId(String id) {\n this.id = id;\n }\n\n @Override\n public String toString() {\n return \"VerificationId{\" + \"id='\" + id + '\\'' + '}';\n }\n\n public String getId() {\n return id;\n }\n\n public static VerificationId valueOf(String id) {\n return new VerificationId(id);\n }\n}" }, { "identifier": "VerificationMethodType", "path": "client/src/main/com/sinch/sdk/domains/verification/models/VerificationMethodType.java", "snippet": "public class VerificationMethodType extends EnumDynamic<String, VerificationMethodType> {\n\n /** Verification by SMS message with a PIN code */\n public static final VerificationMethodType SMS = new VerificationMethodType(\"sms\");\n\n /**\n * Verification by placing a flashcall (missed call) and detecting the incoming calling number\n * (CLI).\n */\n public static final VerificationMethodType FLASH_CALL = new VerificationMethodType(\"flashcall\");\n\n /**\n * Verification by placing a PSTN call to the user's phone and playing an announcement, asking the\n * user to press a particular digit to verify the phone number.\n */\n public static final VerificationMethodType CALLOUT = new VerificationMethodType(\"callout\");\n\n /**\n * Data verification. Verification by accessing internal infrastructure of mobile carriers to\n * verify if given verification attempt was originated from device with matching phone number.\n */\n public static final VerificationMethodType SEAMLESS = new VerificationMethodType(\"seamless\");\n\n /** */\n private static final EnumSupportDynamic<String, VerificationMethodType> ENUM_SUPPORT =\n new EnumSupportDynamic<>(\n VerificationMethodType.class,\n VerificationMethodType::new,\n Arrays.asList(SMS, FLASH_CALL, CALLOUT, SEAMLESS));\n\n private VerificationMethodType(String value) {\n super(value);\n }\n\n public static Stream<VerificationMethodType> values() {\n return ENUM_SUPPORT.values();\n }\n\n public static VerificationMethodType from(String value) {\n return ENUM_SUPPORT.from(value);\n }\n\n public static String valueOf(VerificationMethodType e) {\n return ENUM_SUPPORT.valueOf(e);\n }\n}" }, { "identifier": "VerificationReference", "path": "client/src/main/com/sinch/sdk/domains/verification/models/VerificationReference.java", "snippet": "public class VerificationReference {\n\n public final String reference;\n\n public VerificationReference(String reference) {\n this.reference = reference;\n }\n\n @Override\n public String toString() {\n return \"VerificationReference{\" + \"reference='\" + reference + '\\'' + '}';\n }\n\n public String getReference() {\n return reference;\n }\n\n public static VerificationReference valueOf(String reference) {\n return new VerificationReference(reference);\n }\n}" } ]
import com.adelean.inject.resources.junit.jupiter.GivenJsonResource; import com.adelean.inject.resources.junit.jupiter.TestWithResources; import com.sinch.sdk.domains.verification.models.NumberIdentity; import com.sinch.sdk.domains.verification.models.Price; import com.sinch.sdk.domains.verification.models.VerificationId; import com.sinch.sdk.domains.verification.models.VerificationMethodType; import com.sinch.sdk.domains.verification.models.VerificationReference; import java.util.Collections; import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test;
1,448
package com.sinch.sdk.domains.verification.models.webhooks; @TestWithResources class VerificationRequestEventTest { @GivenJsonResource( "/client/sinch/sdk/domains/verification/models/webhooks/VerificationRequestEvent.json") static VerificationRequestEvent dto; @Test void getId() { Assertions.assertThat(dto.getId()) .usingRecursiveComparison()
package com.sinch.sdk.domains.verification.models.webhooks; @TestWithResources class VerificationRequestEventTest { @GivenJsonResource( "/client/sinch/sdk/domains/verification/models/webhooks/VerificationRequestEvent.json") static VerificationRequestEvent dto; @Test void getId() { Assertions.assertThat(dto.getId()) .usingRecursiveComparison()
.isEqualTo(VerificationId.valueOf("1234567890"));
2
2023-10-31 08:32:59+00:00
2k
SpCoGov/SpCoBot
src/main/java/top/spco/service/chat/Stage.java
[ { "identifier": "Bot", "path": "src/main/java/top/spco/api/Bot.java", "snippet": "public interface Bot extends Identifiable {\n /**\n * 当 BotSettings 在线 (可正常收发消息) 时返回 {@code true}.\n */\n boolean isOnline();\n\n /**\n * 全部的好友分组\n */\n FriendGroups getFriendGroups();\n\n /**\n * 好友列表\n */\n InteractiveList<Friend> getFriends();\n\n /**\n * 群列表\n */\n InteractiveList<Group> getGroups();\n\n /**\n * 获取一个好友对象, 在获取失败时返回 {@code null}\n *\n * @param id 对方 QQ 号码\n */\n Friend getFriend(long id);\n\n /**\n * 当 {@link Bot} 拥有 {@link Friend#getId()} 为 id 的好友时返回 {@code true}\n *\n * @param id 好友的id\n */\n boolean hasFriend(long id);\n\n /**\n * 当 {@link Bot} 拥有 {@link Group#getId()} 为 id 的群组时返回 {@code true}\n *\n * @param id 群组的id\n */\n boolean hasGroup(long id);\n\n User getUser(long id) throws UserFetchException;\n\n Group getGroup(long id);\n}" }, { "identifier": "Interactive", "path": "src/main/java/top/spco/api/Interactive.java", "snippet": "public interface Interactive extends Identifiable {\n void sendMessage(String message);\n\n void sendMessage(Message message);\n\n void handleException(Message sourceMessage, String message);\n\n void handleException(Message sourceMessage, String message, Throwable throwable);\n\n void handleException(Message sourceMessage, Throwable throwable);\n\n void handleException(String message, Throwable throwable);\n\n void handleException(Throwable throwable);\n\n void handleException(String message);\n\n /**\n * 回复并引用源消息。\n *\n * @param sourceMessage 源消息,用于引用\n * @param message 要发送的回复消息\n */\n void quoteReply(Message sourceMessage, Message message);\n\n /**\n * 回复并引用源消息。\n *\n * @param sourceMessage 源消息,用于引用\n * @param message 要发送的回复消息\n */\n void quoteReply(Message sourceMessage, String message);\n\n void sendImage(File image);\n}" }, { "identifier": "Message", "path": "src/main/java/top/spco/api/message/Message.java", "snippet": "public interface Message extends Codable{\n /**\n * 转为接近官方格式的字符串, 即 \"内容\". 如 At(member) + \"test\" 将转为 \"@QQ test\"\n *\n * @return 转化后的文本\n */\n String toMessageContext();\n}" } ]
import top.spco.api.Bot; import top.spco.api.Interactive; import top.spco.api.message.Message; import java.util.function.Supplier;
989
/* * Copyright 2023 SpCo * * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package top.spco.service.chat; /** * {@link Chat 对话}中的一个阶段 * * @see Chat * @author SpCo * @version 0.1.1 * @since 0.1.1 */ public class Stage { public final Supplier<String> startMessage; public final StageExecuter stageExecuter; public Stage(Supplier<String> startMessage, StageExecuter executer) { this.startMessage = startMessage; this.stageExecuter = executer; } public interface StageExecuter {
/* * Copyright 2023 SpCo * * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package top.spco.service.chat; /** * {@link Chat 对话}中的一个阶段 * * @see Chat * @author SpCo * @version 0.1.1 * @since 0.1.1 */ public class Stage { public final Supplier<String> startMessage; public final StageExecuter stageExecuter; public Stage(Supplier<String> startMessage, StageExecuter executer) { this.startMessage = startMessage; this.stageExecuter = executer; } public interface StageExecuter {
void onMessage(Chat chat, Bot bot, Interactive source, Interactive sender, Message message, int time);
0
2023-10-26 10:27:47+00:00
2k
cty1928/GreenTravel
src/Android/Maps-master/app/src/main/java/org/zarroboogs/maps/presenters/MarkerInteractorImpl.java
[ { "identifier": "MapsApplication", "path": "src/Android/Maps-master/app/src/main/java/org/zarroboogs/maps/MapsApplication.java", "snippet": "public class MapsApplication extends Application {\n\n private static Context sContext;\n private static DaoMaster sDaoMaster;\n private static DaoSession sDaoSession;\n\n\n @Override\n public void onCreate() {\n super.onCreate();\n sContext = this;\n TTSController ttsController = TTSController.getInstance(this.getApplicationContext());\n ttsController.init();\n\n AMapNavi navi = AMapNavi.getInstance(sContext);\n\n if (!FileUtils.readBooleanFromSharedPreference(Constants.PreferenceKeys.KEY_INIT, false)){\n ArrayList<BJCamera> cameraBeans = JsonUtils.prasePaperCameras(FileUtils.readStringFromAsset(MapsApplication.getAppContext(), \"beijing_paper.json\"));\n for (BJCamera camera: cameraBeans){\n getDaoSession().insert(camera);\n }\n FileUtils.writeBooleanToSharedPreference(Constants.PreferenceKeys.KEY_INIT,true);\n }\n\n }\n\n public static Context getAppContext() {\n return sContext;\n }\n\n public static DaoMaster getDaoMaster() {\n if (sDaoMaster == null) {\n DaoMaster.OpenHelper helper = new DaoMaster.DevOpenHelper(sContext, \"maps.db\", null);\n sDaoMaster = new DaoMaster(helper.getWritableDatabase());\n }\n return sDaoMaster;\n }\n\n public static DaoSession getDaoSession() {\n if (sDaoSession == null) {\n sDaoSession = getDaoMaster().newSession();\n }\n return sDaoSession;\n }\n\n}" }, { "identifier": "BJCamera", "path": "src/Android/Maps-master/app/src/main/java-gen/org/zarroboogs/maps/beans/BJCamera.java", "snippet": "public class BJCamera {\n\n private Long id;\n /** Not-null value. */\n private String name;\n private String address;\n private Double latitude;\n private Double longtitude;\n private String direction;\n\n public BJCamera() {\n }\n\n public BJCamera(Long id) {\n this.id = id;\n }\n\n public BJCamera(Long id, String name, String address, Double latitude, Double longtitude, String direction) {\n this.id = id;\n this.name = name;\n this.address = address;\n this.latitude = latitude;\n this.longtitude = longtitude;\n this.direction = direction;\n }\n\n public Long getId() {\n return id;\n }\n\n public void setId(Long id) {\n this.id = id;\n }\n\n /** Not-null value. */\n public String getName() {\n return name;\n }\n\n /** Not-null value; ensure this value is available before it is saved to the database. */\n public void setName(String name) {\n this.name = name;\n }\n\n public String getAddress() {\n return address;\n }\n\n public void setAddress(String address) {\n this.address = address;\n }\n\n public Double getLatitude() {\n return latitude;\n }\n\n public void setLatitude(Double latitude) {\n this.latitude = latitude;\n }\n\n public Double getLongtitude() {\n return longtitude;\n }\n\n public void setLongtitude(Double longtitude) {\n this.longtitude = longtitude;\n }\n\n public String getDirection() {\n return direction;\n }\n\n public void setDirection(String direction) {\n this.direction = direction;\n }\n\n}" } ]
import com.amap.api.maps.model.BitmapDescriptor; import com.amap.api.maps.model.BitmapDescriptorFactory; import com.amap.api.maps.model.LatLng; import com.amap.api.maps.model.MarkerOptions; import org.zarroboogs.maps.MapsApplication; import org.zarroboogs.maps.R; import org.zarroboogs.maps.beans.BJCamera; import java.util.ArrayList;
1,201
package org.zarroboogs.maps.presenters; /** * Created by andforce on 15/7/19. */ public class MarkerInteractorImpl implements MarkerInteractor { private BitmapDescriptor mMarkerDesc = BitmapDescriptorFactory.fromResource(R.drawable.icon_camera_location); @Override public void createMarkers(OnMarkerCreatedListener listener) { if (null != listener){ listener.onMarkerCreated(createMarkerOptions()); } } @Override public void readCameras(OnReadCamerasListener listener) { if (listener != null) { listener.onReadCameras(readCameras()); } } private ArrayList<MarkerOptions> createMarkerOptions(){ ArrayList<MarkerOptions> markerOptions = new ArrayList<>(); ArrayList<BJCamera> cameraBeans = readCameras(); for (BJCamera cameraBean : cameraBeans) { LatLng latLng = new LatLng(cameraBean.getLatitude(), cameraBean.getLongtitude()); MarkerOptions mo = new MarkerOptions().position(latLng).draggable(true).icon(mMarkerDesc); markerOptions.add(mo); } return markerOptions; } private ArrayList<BJCamera> readCameras(){
package org.zarroboogs.maps.presenters; /** * Created by andforce on 15/7/19. */ public class MarkerInteractorImpl implements MarkerInteractor { private BitmapDescriptor mMarkerDesc = BitmapDescriptorFactory.fromResource(R.drawable.icon_camera_location); @Override public void createMarkers(OnMarkerCreatedListener listener) { if (null != listener){ listener.onMarkerCreated(createMarkerOptions()); } } @Override public void readCameras(OnReadCamerasListener listener) { if (listener != null) { listener.onReadCameras(readCameras()); } } private ArrayList<MarkerOptions> createMarkerOptions(){ ArrayList<MarkerOptions> markerOptions = new ArrayList<>(); ArrayList<BJCamera> cameraBeans = readCameras(); for (BJCamera cameraBean : cameraBeans) { LatLng latLng = new LatLng(cameraBean.getLatitude(), cameraBean.getLongtitude()); MarkerOptions mo = new MarkerOptions().position(latLng).draggable(true).icon(mMarkerDesc); markerOptions.add(mo); } return markerOptions; } private ArrayList<BJCamera> readCameras(){
return (ArrayList<BJCamera>) MapsApplication.getDaoSession().loadAll(BJCamera.class);
0
2023-10-31 01:21:54+00:00
2k