├── settings.gradle ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── .gitignore ├── src ├── main │ └── java │ │ └── com │ │ └── masterdevskills │ │ ├── cha1 │ │ ├── ext4 │ │ │ ├── FrenchDeck.java │ │ │ ├── ItalianDeck.java │ │ │ ├── TODO.md │ │ │ ├── Deck.java │ │ │ ├── PlayingCard.java │ │ │ ├── StandardDeck.java │ │ │ └── Card.java │ │ ├── ext5 │ │ │ ├── Log.java │ │ │ ├── DidThatWork.java │ │ │ └── Logger.java │ │ ├── ext2 │ │ │ ├── Status.java │ │ │ ├── User.java │ │ │ └── Users.java │ │ ├── ext1 │ │ │ ├── LambdaExpression2.java │ │ │ ├── LambdaExpression1.java │ │ │ └── FileProcessor.java │ │ └── ext3 │ │ │ ├── Person.java │ │ │ └── Exercises.java │ │ └── cha2 │ │ ├── ext2 │ │ ├── DidThatWork.java │ │ ├── model │ │ │ ├── Rating.java │ │ │ └── Movie.java │ │ ├── service │ │ │ ├── InMemoryMovieService.java │ │ │ └── RealMovieService.java │ │ └── http │ │ │ └── HttpMovieService.java │ │ ├── ext3 │ │ ├── PagePrinter.java │ │ ├── Document.java │ │ └── Documents.java │ │ └── ext1 │ │ └── NumericStreams.java └── test │ └── java │ └── com │ └── masterdevskills │ ├── cha2 │ ├── ext1 │ │ └── NumericStreamsTest.java │ ├── ext3 │ │ └── DocumentsTest.java │ └── ext2 │ │ └── service │ │ └── RealMovieServiceTest.java │ ├── cha1 │ ├── ext5 │ │ └── LoggerTest.java │ ├── ext1 │ │ ├── LambdaExpression1Test.java │ │ ├── LambdaExpression2Test.java │ │ └── FileProcessorTest.java │ ├── ext2 │ │ └── UsersTest.java │ └── ext3 │ │ └── ExercisesTest.java │ └── util │ ├── StringWithComparisonMatcher.java │ ├── FeatureMatchers.java │ ├── HasConcreteMethod.java │ └── CodeUsesMethodReferencesMatcher.java ├── .github └── workflows │ └── gradle.yml ├── gradlew.bat └── gradlew /settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'avancejava-exercise' 2 | 3 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nowshad-hasan/advancejava-exercise/master/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | 2 | # User-specific stuff 3 | .idea/** 4 | 5 | # File-based project format 6 | *.iws 7 | 8 | # IntelliJ 9 | out/ 10 | .gradle/** 11 | build -------------------------------------------------------------------------------- /src/main/java/com/masterdevskills/cha1/ext4/FrenchDeck.java: -------------------------------------------------------------------------------- 1 | package com.masterdevskills.cha1.ext4; 2 | 3 | /** 4 | * @author A N M Bazlur Rahman @bazlur_rahman 5 | * @since 08 August 2020 6 | */ 7 | public class FrenchDeck { 8 | } 9 | -------------------------------------------------------------------------------- /src/main/java/com/masterdevskills/cha1/ext4/ItalianDeck.java: -------------------------------------------------------------------------------- 1 | package com.masterdevskills.cha1.ext4; 2 | 3 | /** 4 | * @author A N M Bazlur Rahman @bazlur_rahman 5 | * @since 08 August 2020 6 | */ 7 | public class ItalianDeck { 8 | } 9 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Fri Aug 07 09:24:58 EDT 2020 2 | distributionUrl=https\://services.gradle.org/distributions/gradle-6.5.1-all.zip 3 | distributionBase=GRADLE_USER_HOME 4 | distributionPath=wrapper/dists 5 | zipStorePath=wrapper/dists 6 | zipStoreBase=GRADLE_USER_HOME 7 | -------------------------------------------------------------------------------- /src/main/java/com/masterdevskills/cha1/ext5/Log.java: -------------------------------------------------------------------------------- 1 | package com.masterdevskills.cha1.ext5; 2 | 3 | import java.util.function.Supplier; 4 | 5 | public interface Log { 6 | boolean isLoggable(); 7 | 8 | void enableLogging(); 9 | 10 | void info(String message, Object... params); 11 | 12 | void info(String message, Supplier params); 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/com/masterdevskills/cha2/ext2/DidThatWork.java: -------------------------------------------------------------------------------- 1 | package com.masterdevskills.cha2.ext2; 2 | 3 | 4 | import com.masterdevskills.cha2.ext2.service.InMemoryMovieService; 5 | 6 | public class DidThatWork { 7 | public static void main(String[] args) { 8 | var allMovies = InMemoryMovieService.getInstance().findAllMovies(); 9 | System.out.println("Total Movies: " + allMovies.size()); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/com/masterdevskills/cha1/ext4/TODO.md: -------------------------------------------------------------------------------- 1 | # Go wild with playing card 2 | 3 | You have an interface Card and Deck. 4 | Let's say you have a game board. You can play many types of games. 5 | 6 | There could be several implementations of Deck, eg. French, Italian, German 7 | 8 | Implement the deck differently, and then add a default method in Deck.java so that its implemented 9 | classes don't have to implement the method. 10 | -------------------------------------------------------------------------------- /src/test/java/com/masterdevskills/cha2/ext1/NumericStreamsTest.java: -------------------------------------------------------------------------------- 1 | package com.masterdevskills.cha2.ext1; 2 | 3 | import org.junit.jupiter.api.Test; 4 | 5 | import java.util.List; 6 | 7 | import static org.hamcrest.MatcherAssert.assertThat; 8 | import static org.junit.jupiter.api.Assertions.*; 9 | import static org.hamcrest.Matchers.contains; 10 | 11 | /** 12 | * @author A N M Bazlur Rahman @bazlur_rahman 13 | * @since 07 August 2020 14 | */ 15 | class NumericStreamsTest { 16 | 17 | @Test 18 | void generate() { 19 | List fib = NumericStreams.generate(10); 20 | 21 | assertThat(fib, contains(1, 1, 2, 3, 5, 8, 13, 21, 34, 55)); 22 | } 23 | } -------------------------------------------------------------------------------- /src/main/java/com/masterdevskills/cha1/ext4/Deck.java: -------------------------------------------------------------------------------- 1 | package com.masterdevskills.cha1.ext4; 2 | 3 | import java.util.Comparator; 4 | import java.util.List; 5 | import java.util.Map; 6 | 7 | public interface Deck { 8 | List getCards(); 9 | 10 | Deck deckFactory(); 11 | 12 | int size(); 13 | 14 | void addCard(Card card); 15 | 16 | void addCards(List cards); 17 | 18 | void addDeck(Deck deck); 19 | 20 | void shuffle(); 21 | 22 | void sort(); 23 | 24 | void sort(Comparator c); 25 | 26 | String deckToString(); 27 | 28 | Map deal(int players, int numberOfCards) 29 | throws IllegalArgumentException; 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/com/masterdevskills/cha2/ext3/PagePrinter.java: -------------------------------------------------------------------------------- 1 | package com.masterdevskills.cha2.ext3; 2 | 3 | import static java.lang.String.format; 4 | 5 | /** 6 | * @author A N M Bazlur Rahman @bazlur_rahman 7 | * @since 07 August 2020 8 | */ 9 | public class PagePrinter { 10 | private final String pageBreak; 11 | 12 | public PagePrinter(String pageBreak) { 13 | this.pageBreak = pageBreak; 14 | } 15 | 16 | public String printTitlePage(Document document) { 17 | return format( 18 | "%s%n" + 19 | "%s%n", document.getTitle(), pageBreak); 20 | } 21 | 22 | public String printPage(Document.Page page) { 23 | return format( 24 | "%s%n" + 25 | "%s%n", page.getContent(), pageBreak); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /.github/workflows/gradle.yml: -------------------------------------------------------------------------------- 1 | # This workflow will build a Java project with Gradle 2 | # For more information see: https://help.github.com/actions/language-and-framework-guides/building-and-testing-java-with-gradle 3 | 4 | name: Java CI with Gradle 5 | 6 | on: 7 | push: 8 | branches: [ master ] 9 | pull_request: 10 | branches: [ master ] 11 | 12 | jobs: 13 | build: 14 | 15 | runs-on: ubuntu-latest 16 | 17 | steps: 18 | - uses: actions/checkout@v2 19 | - name: Set up JDK 14 20 | uses: actions/setup-java@v1 21 | with: 22 | java-version: 14 23 | - name: Grant execute permission for gradlew 24 | run: chmod +x gradlew 25 | - name: Build with Gradle 26 | run: ./gradlew build 27 | -------------------------------------------------------------------------------- /src/main/java/com/masterdevskills/cha1/ext4/PlayingCard.java: -------------------------------------------------------------------------------- 1 | package com.masterdevskills.cha1.ext4; 2 | 3 | public class PlayingCard implements Card { 4 | private final Suit suit; 5 | private final Rank rank; 6 | 7 | public PlayingCard(final Suit suit, final Rank rank) { 8 | this.suit = suit; 9 | this.rank = rank; 10 | } 11 | 12 | @Override 13 | public Suit getSuit() { 14 | return suit; 15 | } 16 | 17 | @Override 18 | public Rank getRank() { 19 | return rank; 20 | } 21 | 22 | public int hashCode() { 23 | return ((suit.value() - 1) * 13) + rank.value(); 24 | } 25 | 26 | public int compareTo(Card o) { 27 | return this.hashCode() - o.hashCode(); 28 | } 29 | 30 | @Override 31 | public String toString() { 32 | return suit + ":" + rank; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/test/java/com/masterdevskills/cha1/ext5/LoggerTest.java: -------------------------------------------------------------------------------- 1 | package com.masterdevskills.cha1.ext5; 2 | 3 | import org.junit.jupiter.api.Test; 4 | 5 | import java.lang.reflect.Method; 6 | import java.util.Arrays; 7 | 8 | import static org.junit.jupiter.api.Assertions.assertTrue; 9 | 10 | class LoggerTest { 11 | 12 | @Test 13 | void checkIfAllMethodImplemented() { 14 | Method[] methods = Logger.class.getMethods(); 15 | assertMethodExist(methods, "info"); 16 | assertMethodExist(methods, "trace"); 17 | assertMethodExist(methods, "debug"); 18 | assertMethodExist(methods, "warn"); 19 | } 20 | 21 | private void assertMethodExist(final Method[] methods, final String name) { 22 | var param = "java.util.function.Supplier"; 23 | boolean anyMatch = Arrays.stream(methods) 24 | .anyMatch(method -> method.getName().equals(name) 25 | && method.getParameterTypes()[1].getName().equals(param)); 26 | assertTrue(anyMatch); 27 | } 28 | } -------------------------------------------------------------------------------- /src/main/java/com/masterdevskills/cha1/ext5/DidThatWork.java: -------------------------------------------------------------------------------- 1 | package com.masterdevskills.cha1.ext5; 2 | 3 | public class DidThatWork { 4 | public static void main(String[] args) { 5 | Log logger = Logger.getLogger(); 6 | 7 | logger.enableLogging(); 8 | User user = new User("Bazlur", "Rahman"); 9 | // logger.info("user status: {}", getUserStatus(user)); 10 | logger.info("user status: {}", () -> new String[]{getUserStatus(user)}); 11 | } 12 | 13 | private static String getUserStatus(final User user) { 14 | System.out.println("Preparing user status"); 15 | 16 | return user.toString(); 17 | } 18 | 19 | static class User { 20 | final String firstName; 21 | final String lastName; 22 | 23 | public User(final String firstName, final String lastName) { 24 | this.firstName = firstName; 25 | this.lastName = lastName; 26 | } 27 | 28 | @Override 29 | public String toString() { 30 | 31 | return firstName + " " + lastName; 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/com/masterdevskills/cha1/ext2/Status.java: -------------------------------------------------------------------------------- 1 | /* 2 | * #%L 3 | * Advanced Java LIVE course-2020 4 | * %% 5 | * Copyright (C) 2020 MasterDevSkills.com 6 | * %% 7 | * This program is free software: you can redistribute it and/or modify 8 | * it under the terms of the GNU General Public License as 9 | * published by the Free Software Foundation, either version 2 of the 10 | * License, or (at your option) any later version. 11 | * 12 | * This program is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU General Public License for more details. 16 | * 17 | * You should have received a copy of the GNU General Public 18 | * License along with this program. If not, see 19 | * . 20 | * #L% 21 | */ 22 | 23 | package com.masterdevskills.cha1.ext2; 24 | 25 | /** 26 | * @author A N M Bazlur Rahman @bazlur_rahman 27 | * @since 03 August 2020 28 | */ 29 | public enum Status { 30 | CREATED, 31 | ACTIVATED, 32 | LOCKED, 33 | EXPIRED 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/com/masterdevskills/cha2/ext2/model/Rating.java: -------------------------------------------------------------------------------- 1 | /* 2 | * #%L 3 | * Advanced Java LIVE course-2020 4 | * %% 5 | * Copyright (C) 2020 MasterDevSkills.com 6 | * %% 7 | * This program is free software: you can redistribute it and/or modify 8 | * it under the terms of the GNU General Public License as 9 | * published by the Free Software Foundation, either version 2 of the 10 | * License, or (at your option) any later version. 11 | * 12 | * This program is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU General Public License for more details. 16 | * 17 | * You should have received a copy of the GNU General Public 18 | * License along with this program. If not, see 19 | * . 20 | * #L% 21 | */ 22 | 23 | package com.masterdevskills.cha2.ext2.model; 24 | 25 | import com.fasterxml.jackson.annotation.JsonProperty; 26 | import lombok.Data; 27 | 28 | /** 29 | * @author A N M Bazlur Rahman @bazlur_rahman 30 | * @since 07 August 2020 31 | */ 32 | @Data 33 | public class Rating { 34 | @JsonProperty("Source") 35 | private String source; 36 | @JsonProperty("Value") 37 | private String value; 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/com/masterdevskills/cha2/ext3/Document.java: -------------------------------------------------------------------------------- 1 | package com.masterdevskills.cha2.ext3; 2 | 3 | import lombok.Getter; 4 | import lombok.Setter; 5 | 6 | import java.util.List; 7 | import java.util.stream.Collectors; 8 | 9 | import static java.lang.String.format; 10 | import static java.util.stream.Collectors.collectingAndThen; 11 | 12 | /** 13 | * @author A N M Bazlur Rahman @bazlur_rahman 14 | * @since 07 August 2020 15 | */ 16 | @Getter 17 | public class Document { 18 | private final String title; 19 | private final List pages; 20 | 21 | public Document(String title, List pages) { 22 | this.title = title; 23 | this.pages = List.copyOf(pages); 24 | } 25 | 26 | private Page appendFooter(Page original) { 27 | String footer = "Document: " + getTitle(); 28 | return new Page(format("%s%n%s", original.getContent(), footer)); 29 | } 30 | 31 | private Document copyWithPages(List newPages) { 32 | return new Document(title, newPages); 33 | } 34 | 35 | public Document copyWithFooter() { 36 | return getPages().stream() 37 | .map(this::appendFooter) 38 | .collect(collectingAndThen(Collectors.toList(), this::copyWithPages)); 39 | } 40 | 41 | @Getter 42 | @Setter 43 | public static class Page { 44 | private final String content; 45 | 46 | public Page(String content) { 47 | this.content = content; 48 | } 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/main/java/com/masterdevskills/cha1/ext4/StandardDeck.java: -------------------------------------------------------------------------------- 1 | package com.masterdevskills.cha1.ext4; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Collections; 5 | import java.util.Comparator; 6 | import java.util.List; 7 | import java.util.Map; 8 | 9 | public class StandardDeck implements Deck { 10 | private final List entireDeck; 11 | 12 | public StandardDeck() { 13 | entireDeck = new ArrayList<>(); 14 | } 15 | 16 | public void sort() { 17 | Collections.sort(entireDeck); 18 | } 19 | 20 | @Override 21 | public void sort(final Comparator c) { 22 | 23 | } 24 | 25 | @Override 26 | public String deckToString() { 27 | return null; 28 | } 29 | 30 | @Override 31 | public Map deal(final int players, final int numberOfCards) throws IllegalArgumentException { 32 | return null; 33 | } 34 | 35 | @Override 36 | public List getCards() { 37 | return null; 38 | } 39 | 40 | @Override 41 | public Deck deckFactory() { 42 | return null; 43 | } 44 | 45 | @Override 46 | public int size() { 47 | return 0; 48 | } 49 | 50 | @Override 51 | public void addCard(final Card card) { 52 | 53 | } 54 | 55 | @Override 56 | public void addCards(final List cards) { 57 | 58 | } 59 | 60 | @Override 61 | public void addDeck(final Deck deck) { 62 | 63 | } 64 | 65 | public void shuffle() { 66 | Collections.shuffle(entireDeck); 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /src/main/java/com/masterdevskills/cha1/ext4/Card.java: -------------------------------------------------------------------------------- 1 | package com.masterdevskills.cha1.ext4; 2 | 3 | public interface Card extends Comparable { 4 | enum Suit { 5 | DIAMONDS(1, "Diamonds"), 6 | CLUBS(2, "Clubs"), 7 | HEARTS(3, "Hearts"), 8 | SPADES(4, "Spades"); 9 | 10 | private final int value; 11 | private final String text; 12 | 13 | Suit(int value, String text) { 14 | this.value = value; 15 | this.text = text; 16 | } 17 | 18 | public int value() { 19 | return value; 20 | } 21 | 22 | public String text() { 23 | return text; 24 | } 25 | } 26 | 27 | enum Rank { 28 | DEUCE(2, "Two"), 29 | THREE(3, "Three"), 30 | FOUR(4, "Four"), 31 | FIVE(5, "Five"), 32 | SIX(6, "Six"), 33 | SEVEN(7, "Seven"), 34 | EIGHT(8, "Eight"), 35 | NINE(9, "Nine"), 36 | TEN(10, "Ten"), 37 | JACK(11, "Jack"), 38 | QUEEN(12, "Queen"), 39 | KING(13, "King"), 40 | ACE(14, "Ace"); 41 | 42 | private final int value; 43 | private final String text; 44 | 45 | Rank(int value, String text) { 46 | this.value = value; 47 | this.text = text; 48 | } 49 | 50 | public int value() { 51 | return value; 52 | } 53 | 54 | public String text() { 55 | return text; 56 | } 57 | } 58 | 59 | Card.Suit getSuit(); 60 | 61 | Card.Rank getRank(); 62 | 63 | } 64 | -------------------------------------------------------------------------------- /src/main/java/com/masterdevskills/cha1/ext1/LambdaExpression2.java: -------------------------------------------------------------------------------- 1 | /* 2 | * #%L 3 | * Advanced Java LIVE course-2020 4 | * %% 5 | * Copyright (C) 2020 MasterDevSkills.com 6 | * %% 7 | * This program is free software: you can redistribute it and/or modify 8 | * it under the terms of the GNU General Public License as 9 | * published by the Free Software Foundation, either version 2 of the 10 | * License, or (at your option) any later version. 11 | * 12 | * This program is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU General Public License for more details. 16 | * 17 | * You should have received a copy of the GNU General Public 18 | * License along with this program. If not, see 19 | * . 20 | * #L% 21 | */ 22 | 23 | package com.masterdevskills.cha1.ext1; 24 | 25 | /** 26 | * @author A N M Bazlur Rahman @bazlur_rahman 27 | * @since 04 August 2020 28 | */ 29 | public class LambdaExpression2 { 30 | 31 | /** 32 | * TODO Create a functional interface called Executable 33 | * Add a method called execute() 34 | * it doesn't take anything and returns void 35 | * use this functional interface as argument of the following method and log 36 | * the time it takes to execute the method 37 | */ 38 | public void executionTime() { 39 | //TODO add your code here; 40 | } 41 | 42 | /* TODO: use the above of method here 43 | */ 44 | public void run() { 45 | //executionTime(); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/main/java/com/masterdevskills/cha2/ext1/NumericStreams.java: -------------------------------------------------------------------------------- 1 | /* 2 | * #%L 3 | * Advanced Java LIVE course-2020 4 | * %% 5 | * Copyright (C) 2020 MasterDevSkills.com 6 | * %% 7 | * This program is free software: you can redistribute it and/or modify 8 | * it under the terms of the GNU General Public License as 9 | * published by the Free Software Foundation, either version 2 of the 10 | * License, or (at your option) any later version. 11 | * 12 | * This program is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU General Public License for more details. 16 | * 17 | * You should have received a copy of the GNU General Public 18 | * License along with this program. If not, see 19 | * . 20 | * #L% 21 | */ 22 | 23 | package com.masterdevskills.cha2.ext1; 24 | 25 | import java.util.List; 26 | import java.util.function.Function; 27 | import java.util.function.UnaryOperator; 28 | import java.util.stream.Collector; 29 | import java.util.stream.Stream; 30 | 31 | /** 32 | * @author A N M Bazlur Rahman @bazlur_rahman 33 | * @since 07 August 2020 34 | */ 35 | public class NumericStreams { 36 | 37 | /** 38 | * TODO write a method that will return a fibonacci series 39 | * Use stream api and lambda expression 40 | * 41 | * @see Stream#iterate(Object, UnaryOperator) 42 | * @see Stream#limit(long) 43 | * @see Stream#map(Function) 44 | * @see Stream#collect(Collector) 45 | */ 46 | public static List generate(int series) { 47 | 48 | throw new RuntimeException("TODO://ImplementIt"); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/main/java/com/masterdevskills/cha1/ext2/User.java: -------------------------------------------------------------------------------- 1 | /* 2 | * #%L 3 | * Advanced Java LIVE course-2020 4 | * %% 5 | * Copyright (C) 2020 MasterDevSkills.com 6 | * %% 7 | * This program is free software: you can redistribute it and/or modify 8 | * it under the terms of the GNU General Public License as 9 | * published by the Free Software Foundation, either version 2 of the 10 | * License, or (at your option) any later version. 11 | * 12 | * This program is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU General Public License for more details. 16 | * 17 | * You should have received a copy of the GNU General Public 18 | * License along with this program. If not, see 19 | * . 20 | * #L% 21 | */ 22 | 23 | package com.masterdevskills.cha1.ext2; 24 | 25 | import java.util.StringJoiner; 26 | 27 | /** 28 | * @author A N M Bazlur Rahman @bazlur_rahman 29 | * @since 03 August 2020 30 | */ 31 | public class User { 32 | private String username; 33 | private String email; 34 | private Status status = Status.CREATED; 35 | 36 | public User(String username) { 37 | this.username = username; 38 | } 39 | 40 | public String getUsername() { 41 | return username; 42 | } 43 | 44 | public void setUsername(String username) { 45 | this.username = username; 46 | } 47 | 48 | public String getEmail() { 49 | return email; 50 | } 51 | 52 | public void setEmail(String email) { 53 | this.email = email; 54 | } 55 | 56 | public Status getStatus() { 57 | return status; 58 | } 59 | 60 | public void setStatus(Status status) { 61 | this.status = status; 62 | } 63 | 64 | @Override 65 | public String toString() { 66 | return username; 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /src/main/java/com/masterdevskills/cha1/ext3/Person.java: -------------------------------------------------------------------------------- 1 | /* 2 | * #%L 3 | * Advanced Java LIVE course-2020 4 | * %% 5 | * Copyright (C) 2020 MasterDevSkills.com 6 | * %% 7 | * This program is free software: you can redistribute it and/or modify 8 | * it under the terms of the GNU General Public License as 9 | * published by the Free Software Foundation, either version 2 of the 10 | * License, or (at your option) any later version. 11 | * 12 | * This program is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU General Public License for more details. 16 | * 17 | * You should have received a copy of the GNU General Public 18 | * License along with this program. If not, see 19 | * . 20 | * #L% 21 | */ 22 | 23 | package com.masterdevskills.cha1.ext3; 24 | 25 | import java.util.StringJoiner; 26 | 27 | /** 28 | * @author A N M Bazlur Rahman @bazlur_rahman 29 | * @since 04 August 2020 30 | */ 31 | public class Person { 32 | private final String firstName; 33 | private final String lastName; 34 | private final int age; 35 | 36 | public Person(String firstName, String lastName, int age) { 37 | this.firstName = firstName; 38 | this.lastName = lastName; 39 | this.age = age; 40 | } 41 | 42 | public String getFirstName() { 43 | return firstName; 44 | } 45 | 46 | public String getLastName() { 47 | return lastName; 48 | } 49 | 50 | public int getAge() { 51 | return age; 52 | } 53 | 54 | @Override 55 | public String toString() { 56 | return new StringJoiner(", ", Person.class.getSimpleName() + "[", "]") 57 | .add("firstName='" + firstName + "'") 58 | .add("lastName='" + lastName + "'") 59 | .add("age=" + age) 60 | .toString(); 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /src/main/java/com/masterdevskills/cha1/ext5/Logger.java: -------------------------------------------------------------------------------- 1 | package com.masterdevskills.cha1.ext5; 2 | 3 | import java.util.function.Supplier; 4 | 5 | //TODO: implement info, trace, debug, warn 6 | public class Logger implements Log { 7 | private static final String DELIM = "{}"; 8 | private volatile boolean enabled; 9 | 10 | private Logger() { 11 | } 12 | 13 | public static Log getLogger() { 14 | return new Logger(); 15 | } 16 | 17 | @Override 18 | public boolean isLoggable() { 19 | return enabled; 20 | } 21 | 22 | @Override 23 | public void enableLogging() { 24 | this.enabled = true; 25 | } 26 | 27 | @Override 28 | public void info(final String message, final Object... params) { 29 | if (isLoggable()) { 30 | System.out.println(formatMessage(message, params)); 31 | } 32 | } 33 | 34 | private String formatMessage(final String message, final Object[] params) { 35 | if (message != null && params != null) { 36 | StringBuilder sbMessage = new StringBuilder(message); 37 | 38 | for (Object arg : params) { 39 | int index = sbMessage.indexOf(DELIM); 40 | if (index == -1) { 41 | break; 42 | } 43 | sbMessage.replace(index, index + DELIM.length(), arg == null ? "null" : arg.toString()); 44 | } 45 | 46 | return sbMessage.toString(); 47 | } 48 | return message; 49 | } 50 | 51 | @Override 52 | public void info(final String message, final Supplier params) { 53 | if (isLoggable()) { 54 | System.out.println(formatMessage(message, params.get())); 55 | } 56 | } 57 | 58 | public Logger setEnabled(final boolean enabled) { 59 | this.enabled = enabled; 60 | return this; 61 | } 62 | } 63 | 64 | 65 | -------------------------------------------------------------------------------- /src/test/java/com/masterdevskills/cha1/ext1/LambdaExpression1Test.java: -------------------------------------------------------------------------------- 1 | /* 2 | * #%L 3 | * Advanced Java LIVE course-2020 4 | * %% 5 | * Copyright (C) 2020 MasterDevSkills.com 6 | * %% 7 | * This program is free software: you can redistribute it and/or modify 8 | * it under the terms of the GNU General Public License as 9 | * published by the Free Software Foundation, either version 2 of the 10 | * License, or (at your option) any later version. 11 | * 12 | * This program is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU General Public License for more details. 16 | * 17 | * You should have received a copy of the GNU General Public 18 | * License along with this program. If not, see 19 | * . 20 | * #L% 21 | */ 22 | 23 | package com.masterdevskills.cha1.ext1; 24 | 25 | import org.junit.jupiter.api.Test; 26 | 27 | import static org.junit.jupiter.api.Assertions.*; 28 | 29 | /** 30 | * @author A N M Bazlur Rahman @bazlur_rahman 31 | * @since 04 August 2020 32 | */ 33 | class LambdaExpression1Test { 34 | 35 | @Test 36 | void checkMoreThan5Chars() { 37 | assertTrue(LambdaExpression1.checkMoreThan5Chars("HelloWorld")); 38 | assertFalse(LambdaExpression1.checkMoreThan5Chars("hello")); 39 | assertFalse(LambdaExpression1.checkMoreThan5Chars("helo")); 40 | } 41 | 42 | @Test 43 | void isStringEmpty() { 44 | assertTrue(LambdaExpression1.isStringEmpty(" ")); 45 | assertFalse(LambdaExpression1.isStringEmpty("hello")); 46 | } 47 | 48 | @Test 49 | void convertToUpperCase() { 50 | assertEquals(LambdaExpression1.convertToUpperCase("hello"), "HELLO"); 51 | assertEquals(LambdaExpression1.convertToUpperCase("Abc"), "ABC"); 52 | assertEquals(LambdaExpression1.convertToUpperCase("Abc33"), "ABC33"); 53 | } 54 | } -------------------------------------------------------------------------------- /src/test/java/com/masterdevskills/util/StringWithComparisonMatcher.java: -------------------------------------------------------------------------------- 1 | package com.masterdevskills.util; 2 | 3 | /* 4 | * #%L 5 | * lambda-tutorial 6 | * %% 7 | * Copyright (C) 2013 Adopt OpenJDK 8 | * %% 9 | * This program is free software: you can redistribute it and/or modify 10 | * it under the terms of the GNU General Public License as 11 | * published by the Free Software Foundation, either version 2 of the 12 | * License, or (at your option) any later version. 13 | * 14 | * This program is distributed in the hope that it will be useful, 15 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 16 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 17 | * GNU General Public License for more details. 18 | * 19 | * You should have received a copy of the GNU General Public 20 | * License along with this program. If not, see 21 | * . 22 | * #L% 23 | */ 24 | 25 | import org.hamcrest.Description; 26 | import org.hamcrest.TypeSafeDiagnosingMatcher; 27 | import org.junit.ComparisonFailure; 28 | 29 | public class StringWithComparisonMatcher extends TypeSafeDiagnosingMatcher { 30 | private final String expected; 31 | 32 | private StringWithComparisonMatcher(String expected) { 33 | this.expected = expected; 34 | } 35 | 36 | public static StringWithComparisonMatcher isString(String expected) { 37 | return new StringWithComparisonMatcher(expected); 38 | } 39 | 40 | @Override 41 | public void describeTo(Description description) { 42 | description.appendText(expected); 43 | } 44 | 45 | @Override 46 | protected boolean matchesSafely(String actual, Description mismatchDescription) { 47 | if (!expected.equals(actual)) { 48 | String compactedMismatch = new ComparisonFailure("did not match:", expected, actual).getMessage(); 49 | mismatchDescription.appendText(compactedMismatch); 50 | return false; 51 | } 52 | return true; 53 | } 54 | 55 | } -------------------------------------------------------------------------------- /src/main/java/com/masterdevskills/cha2/ext2/service/InMemoryMovieService.java: -------------------------------------------------------------------------------- 1 | /* 2 | * #%L 3 | * Advanced Java LIVE course-2020 4 | * %% 5 | * Copyright (C) 2020 MasterDevSkills.com 6 | * %% 7 | * This program is free software: you can redistribute it and/or modify 8 | * it under the terms of the GNU General Public License as 9 | * published by the Free Software Foundation, either version 2 of the 10 | * License, or (at your option) any later version. 11 | * 12 | * This program is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU General Public License for more details. 16 | * 17 | * You should have received a copy of the GNU General Public 18 | * License along with this program. If not, see 19 | * . 20 | * #L% 21 | */ 22 | 23 | package com.masterdevskills.cha2.ext2.service; 24 | 25 | import com.fasterxml.jackson.core.type.TypeReference; 26 | import com.fasterxml.jackson.databind.ObjectMapper; 27 | import com.masterdevskills.cha2.ext2.model.Movie; 28 | 29 | import java.io.File; 30 | import java.io.IOException; 31 | import java.util.List; 32 | 33 | /** 34 | * @author A N M Bazlur Rahman @bazlur_rahman 35 | * @since 07 August 2020 36 | */ 37 | public class InMemoryMovieService { 38 | private final static InMemoryMovieService instance = new InMemoryMovieService(); 39 | 40 | private final ObjectMapper objectMapper = new ObjectMapper(); 41 | 42 | private InMemoryMovieService() { 43 | } 44 | 45 | public static InMemoryMovieService getInstance() { 46 | return instance; 47 | } 48 | 49 | public List findAllMovies() { 50 | try { 51 | var src = new File( 52 | getClass().getClassLoader().getResource("movies.json").getFile() 53 | ); 54 | return objectMapper.readValue(src, new TypeReference<>() { 55 | }); 56 | } catch (IOException ioException) { 57 | throw new RuntimeException("Unable to parse movie db", ioException); 58 | } 59 | } 60 | 61 | } 62 | -------------------------------------------------------------------------------- /src/main/java/com/masterdevskills/cha1/ext2/Users.java: -------------------------------------------------------------------------------- 1 | /* 2 | * #%L 3 | * Advanced Java LIVE course-2020 4 | * %% 5 | * Copyright (C) 2020 MasterDevSkills.com 6 | * %% 7 | * This program is free software: you can redistribute it and/or modify 8 | * it under the terms of the GNU General Public License as 9 | * published by the Free Software Foundation, either version 2 of the 10 | * License, or (at your option) any later version. 11 | * 12 | * This program is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU General Public License for more details. 16 | * 17 | * You should have received a copy of the GNU General Public 18 | * License along with this program. If not, see 19 | * . 20 | * #L% 21 | */ 22 | 23 | package com.masterdevskills.cha1.ext2; 24 | 25 | import java.util.List; 26 | import java.util.StringJoiner; 27 | 28 | /** 29 | * @author A N M Bazlur Rahman @bazlur_rahman 30 | * @since 03 August 2020 31 | */ 32 | public class Users { 33 | 34 | /** 35 | * TODO 1: activate all users - change the status of all the users 36 | *

37 | * Example- 38 | * given a list of users - User ("user1"), Users("User2") 39 | * by default status of users is Status.CREATED 40 | * 41 | * @param users list of users 42 | * @param status a new status 43 | * @see User#setStatus(Status) 44 | */ 45 | public static void activatedAll(List users, Status status) { 46 | throw new RuntimeException("NotImplemented"); 47 | } 48 | 49 | /** 50 | * TODO 2: Create a string representation of all users 51 | * use toString method of users to get String representation of user 52 | * 53 | * @param users list of string 54 | * @see User#toString() 55 | * @see StringJoiner#add(CharSequence) 56 | * @see StringJoiner#toString() 57 | */ 58 | 59 | public static String makeStringOfAllUsernames(List users) { 60 | 61 | throw new RuntimeException("NotImplemented"); 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /src/main/java/com/masterdevskills/cha1/ext1/LambdaExpression1.java: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * * #%L 4 | * * Advanced Java LIVE course-2020 5 | * * %% 6 | * * Copyright (C) 2020 MasterDevSkills.com 7 | * * %% 8 | * * This program is free software: you can redistribute it and/or modify 9 | * * it under the terms of the GNU General Public License as 10 | * * published by the Free Software Foundation, either version 2 of the 11 | * * License, or (at your option) any later version. 12 | * * 13 | * * This program is distributed in the hope that it will be useful, 14 | * * but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | * * GNU General Public License for more details. 17 | * * 18 | * * You should have received a copy of the GNU General Public 19 | * * License along with this program. If not, see 20 | * * . 21 | * * #L% 22 | * 23 | */ 24 | 25 | package com.masterdevskills.cha1.ext1; 26 | 27 | 28 | import java.util.function.Predicate; 29 | 30 | public class LambdaExpression1 { 31 | 32 | /** 33 | * TODO 1: Write a lambda expression using Predicate to check if a string has more then 5 characters or not 34 | * 35 | * @param value given value 36 | * @see Predicate 37 | */ 38 | public static boolean checkMoreThan5Chars(String value) { 39 | 40 | throw new RuntimeException("NotImplementedYet"); 41 | } 42 | 43 | /* TODO 2: Write a lambda expression using Predicate to check if string is empty or not 44 | * @param value given value 45 | * @see Predicate 46 | */ 47 | public static boolean isStringEmpty(String value) { 48 | throw new RuntimeException("NotImplementedYet"); 49 | } 50 | 51 | /** 52 | * TODO 3: Write lambda expression using Function to converter a text to uppercase 53 | * 54 | * @param text given value 55 | * @see Predicate 56 | */ 57 | public static String convertToUpperCase(String text) { 58 | throw new RuntimeException("NotImplementedYet"); 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /src/test/java/com/masterdevskills/util/FeatureMatchers.java: -------------------------------------------------------------------------------- 1 | package com.masterdevskills.util; 2 | 3 | /* 4 | * #%L 5 | * lambda-tutorial 6 | * %% 7 | * Copyright (C) 2013 Adopt OpenJDK 8 | * %% 9 | * This program is free software: you can redistribute it and/or modify 10 | * it under the terms of the GNU General Public License as 11 | * published by the Free Software Foundation, either version 2 of the 12 | * License, or (at your option) any later version. 13 | * 14 | * This program is distributed in the hope that it will be useful, 15 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 16 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 17 | * GNU General Public License for more details. 18 | * 19 | * You should have received a copy of the GNU General Public 20 | * License along with this program. If not, see 21 | * . 22 | * #L% 23 | */ 24 | 25 | import org.hamcrest.FeatureMatcher; 26 | import org.hamcrest.Matcher; 27 | 28 | import java.util.function.Function; 29 | 30 | /** 31 | * Helper utility for matching on features 32 | */ 33 | public final class FeatureMatchers { 34 | 35 | private FeatureMatchers() {} 36 | 37 | /** 38 | * TODO Explain this method 39 | * 40 | * @param 41 | * @param 42 | * @param featureMatcher - Matcher that contains a feature 43 | * @param description - the description of the feature 44 | * @param name - the name of the feature 45 | * @param extractor - the Function used to extract the feature 46 | * @return A Matcher 47 | */ 48 | public static Matcher from(Matcher featureMatcher, 49 | String description, 50 | String name, 51 | Function extractor) { 52 | return new FeatureMatcher(featureMatcher, description, name) { 53 | @Override 54 | protected FEATURE featureValueOf(FROM t) { 55 | return extractor.apply(t); 56 | } 57 | }; 58 | } 59 | 60 | } 61 | -------------------------------------------------------------------------------- /src/test/java/com/masterdevskills/cha1/ext2/UsersTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * #%L 3 | * Advanced Java LIVE course-2020 4 | * %% 5 | * Copyright (C) 2020 MasterDevSkills.com 6 | * %% 7 | * This program is free software: you can redistribute it and/or modify 8 | * it under the terms of the GNU General Public License as 9 | * published by the Free Software Foundation, either version 2 of the 10 | * License, or (at your option) any later version. 11 | * 12 | * This program is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU General Public License for more details. 16 | * 17 | * You should have received a copy of the GNU General Public 18 | * License along with this program. If not, see 19 | * . 20 | * #L% 21 | */ 22 | 23 | package com.masterdevskills.cha1.ext2; 24 | 25 | import org.junit.jupiter.api.BeforeEach; 26 | import org.junit.jupiter.api.Test; 27 | 28 | import java.util.List; 29 | 30 | import static org.hamcrest.MatcherAssert.assertThat; 31 | import static org.hamcrest.Matchers.*; 32 | import static org.junit.jupiter.api.Assertions.assertEquals; 33 | 34 | /** 35 | * @author A N M Bazlur Rahman @bazlur_rahman 36 | * @since 03 August 2020 37 | */ 38 | class UsersTest { 39 | 40 | @BeforeEach 41 | void setUp() { 42 | } 43 | 44 | @Test 45 | void activatedAll() { 46 | var users = getUsers(); 47 | //method under test 48 | Users.activatedAll(users, Status.ACTIVATED); 49 | 50 | assertThat(users, everyItem(hasProperty("status", is(equalTo(Status.ACTIVATED))))); 51 | users.forEach(user -> assertEquals(user.getStatus(), Status.ACTIVATED)); 52 | } 53 | 54 | @Test 55 | void makeStringOfAllUsernames() { 56 | var users = getUsers(); 57 | 58 | //Method under test 59 | final String allUsernames = Users.makeStringOfAllUsernames(users); 60 | 61 | assertThat(allUsernames, equalTo("user1,user2,user3")); 62 | } 63 | 64 | private List getUsers() { 65 | return List.of(new User("user1"), new User("user2"), new User("user3")); 66 | } 67 | } -------------------------------------------------------------------------------- /src/main/java/com/masterdevskills/cha1/ext1/FileProcessor.java: -------------------------------------------------------------------------------- 1 | /* 2 | * #%L 3 | * Advanced Java LIVE course-2020 4 | * %% 5 | * Copyright (C) 2020 MasterDevSkills.com 6 | * %% 7 | * This program is free software: you can redistribute it and/or modify 8 | * it under the terms of the GNU General Public License as 9 | * published by the Free Software Foundation, either version 2 of the 10 | * License, or (at your option) any later version. 11 | * 12 | * This program is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU General Public License for more details. 16 | * 17 | * You should have received a copy of the GNU General Public 18 | * License along with this program. If not, see 19 | * . 20 | * #L% 21 | */ 22 | 23 | package com.masterdevskills.cha1.ext1; 24 | 25 | import java.util.List; 26 | import java.util.function.Predicate; 27 | 28 | /** 29 | * TODO : Write a file processor that would read text from a text file. 30 | * Discard the empty line 31 | * Log the count of the lines of the file 32 | * Write in another file 33 | */ 34 | 35 | public class FileProcessor { 36 | 37 | /** 38 | * Add your code in the following method 39 | * This method is supposed to read text from given file 40 | * and return the all the lines as a List of string 41 | * 42 | * @param fileName the filename 43 | *

44 | * hints: 45 | * @see List#removeIf(Predicate) 46 | */ 47 | public List readFileFrom(String fileName) { 48 | 49 | throw new RuntimeException("Not Yet Implemented"); 50 | } 51 | 52 | /** 53 | * TODO: Implement this method that takes a list of string and write in a file 54 | * 55 | * @param lines list of string 56 | * @param fileName fileName to write 57 | *

58 | * hints 59 | * @see String#join(CharSequence, CharSequence...) 60 | */ 61 | public void writeToFile(List lines, String fileName) { 62 | 63 | throw new RuntimeException("Not Yet Implemented"); 64 | } 65 | } 66 | 67 | -------------------------------------------------------------------------------- /src/test/java/com/masterdevskills/cha1/ext1/LambdaExpression2Test.java: -------------------------------------------------------------------------------- 1 | /* 2 | * #%L 3 | * Advanced Java LIVE course-2020 4 | * %% 5 | * Copyright (C) 2020 MasterDevSkills.com 6 | * %% 7 | * This program is free software: you can redistribute it and/or modify 8 | * it under the terms of the GNU General Public License as 9 | * published by the Free Software Foundation, either version 2 of the 10 | * License, or (at your option) any later version. 11 | * 12 | * This program is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU General Public License for more details. 16 | * 17 | * You should have received a copy of the GNU General Public 18 | * License along with this program. If not, see 19 | * . 20 | * #L% 21 | */ 22 | 23 | package com.masterdevskills.cha1.ext1; 24 | 25 | import org.junit.jupiter.api.Test; 26 | import org.mockito.Mockito; 27 | 28 | import java.io.File; 29 | import java.io.IOException; 30 | import java.nio.file.Files; 31 | import java.nio.file.Path; 32 | import java.nio.file.Paths; 33 | import java.util.stream.Stream; 34 | 35 | import static org.junit.jupiter.api.Assertions.assertTrue; 36 | 37 | /** 38 | * @author A N M Bazlur Rahman @bazlur_rahman 39 | * @since 04 August 2020 40 | */ 41 | class LambdaExpression2Test { 42 | 43 | @Test 44 | void executionTime() throws IOException { 45 | var resources = LambdaExpression2.class.getClassLoader().getResources(""); 46 | var urlIterator = resources.asIterator(); 47 | 48 | var executable = Stream.generate(() -> null) 49 | .takeWhile(x -> urlIterator.hasNext()) 50 | .map(n -> urlIterator.next()) 51 | .filter(n -> n.getPath().contains("main")) 52 | .map(url -> new File(url.getPath())) 53 | .flatMap(this::walkThrough) 54 | .filter(path -> path.endsWith("Executable.class")) 55 | .findAny(); 56 | 57 | assertTrue(executable.isPresent(), "Functional Interface Executable don't exist in classpath"); 58 | 59 | var spy = Mockito.spy(new LambdaExpression2()); 60 | spy.run(); 61 | Mockito.verify(spy, Mockito.times(1)).executionTime(); 62 | } 63 | 64 | private Stream walkThrough(File file) { 65 | try { 66 | return Files.walk(Paths.get(file.getPath())); 67 | } catch (IOException ioException) { 68 | throw new RuntimeException(ioException); 69 | } 70 | } 71 | } -------------------------------------------------------------------------------- /src/test/java/com/masterdevskills/cha1/ext1/FileProcessorTest.java: -------------------------------------------------------------------------------- 1 | package com.masterdevskills.cha1.ext1; 2 | 3 | import org.junit.jupiter.api.AfterEach; 4 | import org.junit.jupiter.api.BeforeEach; 5 | import org.junit.jupiter.api.Test; 6 | 7 | import java.io.File; 8 | import java.io.IOException; 9 | import java.nio.file.Files; 10 | import java.nio.file.Paths; 11 | 12 | import static org.junit.jupiter.api.Assertions.*; 13 | 14 | class FileProcessorTest { 15 | private FileProcessor fileProcessor; 16 | private File readFrom; 17 | private File writeTo; 18 | 19 | @BeforeEach 20 | void setUp() throws IOException { 21 | fileProcessor = new FileProcessor(); 22 | readFrom = File.createTempFile("filename", ".txt"); 23 | var text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla\n" + 24 | "interdum nisl nec dui volutpat sodales. Vestibulum ac consequat justo, vel fermentum velit. Integer purus metus,\n " + 25 | "volutpat eu neque ut, commodo commodo dui. Mauris scelerisque tempor placerat. Aliquam non felis ut dui suscipit mattis\n" + 26 | "\n" + 27 | "\n" + 28 | "in in quam. Phasellus luctus ut nulla vel volutpat. Sed consequat ultrices commodo. Donec vel quam mollis, pellentesque \n" + 29 | "nulla quis, semper elit. Ut mollis, eros vel aliquet tincidunt, leo sem interdum risus, sed accumsan massa sem sit amet \n" + 30 | "felis. Maecenas aliquet, tellus a posuere tincidunt, arcu metus commodo enim, ac gravida libero diam eu ante. \n" + 31 | "\n" + 32 | "\n" + 33 | "Aenean malesuada tincidunt feugiat. Ut mollis lectus vitae massa maximus tempor. Mauris volutpat scelerisque sollicitudin.\n" + 34 | "Morbi sem nisi, vestibulum aliquam tincidunt nec, facilisis sed tellus. Fusce porta luctus neque, vel hendrerit dui \n" + 35 | "imperdiet at. Nulla iaculis euismod orci, sed dictum arcu fringilla in.\n"; 36 | Files.writeString(Paths.get(readFrom.getPath()), text); 37 | 38 | writeTo = File.createTempFile("filename", ".txt"); 39 | } 40 | 41 | @AfterEach 42 | void tearDown() { 43 | readFrom.deleteOnExit(); 44 | writeTo.deleteOnExit(); 45 | } 46 | 47 | @Test 48 | void testReadFileFrom() { 49 | System.out.println(readFrom.getPath()); 50 | var lines = fileProcessor.readFileFrom(readFrom.getPath()); 51 | 52 | assertEquals(lines.size(), 9); 53 | } 54 | 55 | @Test 56 | void testWriteToFile() { 57 | var lines = fileProcessor.readFileFrom(readFrom.getPath()); 58 | fileProcessor.writeToFile(lines, writeTo.getPath()); 59 | var writtenLine = fileProcessor.readFileFrom(writeTo.getPath()); 60 | 61 | assertEquals(writtenLine.size(), lines.size()); 62 | } 63 | } -------------------------------------------------------------------------------- /src/main/java/com/masterdevskills/cha2/ext3/Documents.java: -------------------------------------------------------------------------------- 1 | package com.masterdevskills.cha2.ext3; 2 | 3 | import java.util.Arrays; 4 | import java.util.List; 5 | 6 | import static java.util.stream.Collectors.toList; 7 | 8 | /** 9 | * @author A N M Bazlur Rahman @bazlur_rahman 10 | * @since 07 August 2020 11 | */ 12 | public class Documents { 13 | 14 | /** 15 | * TODO: Return the titles from a list of documents. 16 | * The Documents class has a method which transforms a list of Document into a list of 17 | * their titles. 18 | * Instead of using a lambda, use a method reference instead. 19 | * 20 | * @see Documents#titlesOf(Document...) 21 | * @see Document#getTitle() 22 | */ 23 | public static List titlesOf(Document... documents) { 24 | 25 | throw new RuntimeException("TODO//ImplementIt"); 26 | } 27 | 28 | /** 29 | * TODO: find the list of character Count of each page 30 | * The Documents class has a method which calculates a list of the character counts of Pages in a 31 | * Document. The method characterCount can be applied to each Page to calculate the number of 32 | * characters in that page. 33 | *
34 | * Use a method reference which uses the static characterCount method. 35 | * 36 | * @see Documents#pageCharacterCounts(Document) 37 | * @see Documents#characterCount(Document.Page) 38 | */ 39 | public static List pageCharacterCounts(Document document) { 40 | 41 | throw new RuntimeException("TODO//ImplementIt"); 42 | } 43 | 44 | public static Integer characterCount(Document.Page page) { 45 | return page.getContent().length(); 46 | } 47 | 48 | /** 49 | * The Documents class has a method which takes a PagePrinter and renders a 50 | * Document to text. 51 | * 52 | * TODO: The method uses two lambda expressions where method references can be used. Convert them to a method reference 53 | *
54 | * Change {@link Documents#print(Document, PagePrinter)} to use method references to invoke instance methods of 55 | * particular objects. 56 | * 57 | * @see Documents#print(Document, PagePrinter) 58 | * @see StringBuilder#append(String) 59 | * @see PagePrinter#printPage(Document.Page) 60 | */ 61 | 62 | public static String print(Document document, PagePrinter pagePrinter) { 63 | StringBuilder output = new StringBuilder(); 64 | 65 | output.append(pagePrinter.printTitlePage(document)); 66 | 67 | document.getPages().stream() 68 | .map(page -> pagePrinter.printPage(page)) 69 | .forEach(str -> output.append(str)); 70 | 71 | return output.toString(); 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /src/main/java/com/masterdevskills/cha2/ext2/model/Movie.java: -------------------------------------------------------------------------------- 1 | /* 2 | * #%L 3 | * Advanced Java LIVE course-2020 4 | * %% 5 | * Copyright (C) 2020 MasterDevSkills.com 6 | * %% 7 | * This program is free software: you can redistribute it and/or modify 8 | * it under the terms of the GNU General Public License as 9 | * published by the Free Software Foundation, either version 2 of the 10 | * License, or (at your option) any later version. 11 | * 12 | * This program is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU General Public License for more details. 16 | * 17 | * You should have received a copy of the GNU General Public 18 | * License along with this program. If not, see 19 | * . 20 | * #L% 21 | */ 22 | 23 | package com.masterdevskills.cha2.ext2.model; 24 | 25 | import com.fasterxml.jackson.annotation.JsonProperty; 26 | import lombok.Data; 27 | import lombok.EqualsAndHashCode; 28 | 29 | import java.util.ArrayList; 30 | import java.util.List; 31 | 32 | /** 33 | * @author A N M Bazlur Rahman @bazlur_rahman 34 | * @since 07 August 2020 35 | */ 36 | @Data 37 | @EqualsAndHashCode(of = {"title", "director"}) 38 | public class Movie { 39 | @JsonProperty("Title") 40 | private String title; 41 | @JsonProperty("Year") 42 | private String year; 43 | @JsonProperty("Rated") 44 | private String rated; 45 | @JsonProperty("Released") 46 | private String released; 47 | @JsonProperty("Runtime") 48 | private String runtime; 49 | @JsonProperty("Genre") 50 | private String genre; 51 | @JsonProperty("Director") 52 | private String director; 53 | @JsonProperty("Writer") 54 | private String writer; 55 | @JsonProperty("Actors") 56 | private String actors; 57 | @JsonProperty("Plot") 58 | private String plot; 59 | @JsonProperty("Language") 60 | private String language; 61 | @JsonProperty("Country") 62 | private String country; 63 | @JsonProperty("Awards") 64 | private String awards; 65 | @JsonProperty("Poster") 66 | private String poster; 67 | @JsonProperty("Ratings") 68 | private List ratings = new ArrayList<>(); 69 | @JsonProperty("Metascore") 70 | private Integer metascore; 71 | @JsonProperty("imdbRating") 72 | private Double imdbRating; 73 | @JsonProperty("imdbVotes") 74 | private String imdbVotes; 75 | @JsonProperty("imdbID") 76 | private String imdbID; 77 | @JsonProperty("Type") 78 | private String type; 79 | @JsonProperty("DVD") 80 | private String dVD; 81 | @JsonProperty("BoxOffice") 82 | private String boxOffice; 83 | @JsonProperty("Production") 84 | private String production; 85 | @JsonProperty("Website") 86 | private String website; 87 | @JsonProperty("Response") 88 | private String response; 89 | } 90 | -------------------------------------------------------------------------------- /src/test/java/com/masterdevskills/cha2/ext3/DocumentsTest.java: -------------------------------------------------------------------------------- 1 | package com.masterdevskills.cha2.ext3; 2 | 3 | import org.junit.jupiter.api.Test; 4 | 5 | import java.util.Arrays; 6 | 7 | import static com.masterdevskills.cha2.ext3.Document.Page; 8 | import static com.masterdevskills.util.CodeUsesMethodReferencesMatcher.usesMethodReferences; 9 | import static com.masterdevskills.util.StringWithComparisonMatcher.isString; 10 | import static java.lang.String.format; 11 | import static org.hamcrest.MatcherAssert.assertThat; 12 | import static org.hamcrest.Matchers.allOf; 13 | import static org.hamcrest.Matchers.contains; 14 | 15 | /** 16 | * @author A N M Bazlur Rahman @bazlur_rahman 17 | * @since 07 August 2020 18 | */ 19 | class DocumentsTest { 20 | 21 | @Test 22 | void getListOfDocumentTitlesUsingMethodReference() { 23 | Document expenses = new Document("Expenses", 24 | Arrays.asList(new Page("TTC : $3"), new Page("Subway: £100"))); 25 | 26 | Document toDoList = new Document("ToDo List", 27 | Arrays.asList(new Page("Learn Lambda expression for 2 hours "), new Page("Post a status on facebook that I konw lambda"))); 28 | Document certificates = new Document("My Certificates", 29 | Arrays.asList(new Page("MasterDevSkills Certified Lambda Expression Professional"), new Page("MasterDevSkills Certified Concurrency Professional"))); 30 | 31 | assertThat(Documents.titlesOf(expenses, toDoList, certificates), 32 | contains("Expenses", "ToDo List", "My Certificates")); 33 | assertThat("Use Method Reference", Documents.class, usesMethodReferences("getTitle")); 34 | } 35 | 36 | @Test 37 | public void getListOfPageCharacterCountsFromDocumentUsingMethodReference() { 38 | Document diary = new Document("Hello world", Arrays.asList( 39 | new Page("Java is the best programming language"), 40 | new Page("I love lambda Expression"), 41 | new Page("Stream API is the bested"))); 42 | 43 | assertThat(Documents.pageCharacterCounts(diary), contains(37, 24, 24)); 44 | assertThat(Documents.class, usesMethodReferences("characterCount")); 45 | } 46 | 47 | @Test 48 | public void printContentsOfDocumentUsingReferenceO() { 49 | Document diary = new Document("My Diary", Arrays.asList( 50 | new Page("Today I've learned Lambda Expression"), 51 | new Page("I'm so excited"), 52 | new Page("I'm looking forward to having more lessons"))); 53 | 54 | assertThat(Documents.print(diary, new PagePrinter("----")), 55 | isString(format("My Diary%n" + 56 | "----%n" + 57 | "Today I've learned Lambda Expression%n" + 58 | "----%n" + 59 | "I'm so excited%n" + 60 | "----%n" + 61 | "I'm looking forward to having more lessons%n" + 62 | "----%n"))); 63 | assertThat(Documents.class, allOf(usesMethodReferences("printPage"), usesMethodReferences("append"))); 64 | } 65 | 66 | } -------------------------------------------------------------------------------- /src/main/java/com/masterdevskills/cha1/ext3/Exercises.java: -------------------------------------------------------------------------------- 1 | /* 2 | * #%L 3 | * Advanced Java LIVE course-2020 4 | * %% 5 | * Copyright (C) 2020 MasterDevSkills.com 6 | * %% 7 | * This program is free software: you can redistribute it and/or modify 8 | * it under the terms of the GNU General Public License as 9 | * published by the Free Software Foundation, either version 2 of the 10 | * License, or (at your option) any later version. 11 | * 12 | * This program is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU General Public License for more details. 16 | * 17 | * You should have received a copy of the GNU General Public 18 | * License along with this program. If not, see 19 | * . 20 | * #L% 21 | */ 22 | 23 | package com.masterdevskills.cha1.ext3; 24 | 25 | 26 | import java.util.List; 27 | import java.util.function.UnaryOperator; 28 | 29 | /** 30 | * @author A N M Bazlur Rahman @bazlur_rahman 31 | * @since 04 August 2020 32 | */ 33 | 34 | //TODO all of the exercise must be done by using lambda expression 35 | public class Exercises { 36 | 37 | /** 38 | * TODO: given a list of integer, return a list of integer where each integer is multiplied by 2 39 | * 40 | * @param ints list of integer 41 | * @see List#replaceAll(UnaryOperator) 42 | */ 43 | public static List doubling(List ints) { 44 | throw new RuntimeException("NotYetImplemented"); 45 | } 46 | 47 | /** 48 | * TODO: given a list of string and a suffix, apply the suffix to all of them 49 | * 50 | * @param items List of string item 51 | * @param suffix suffix that needs to apply on each item 52 | * @see List#replaceAll(UnaryOperator) 53 | */ 54 | public static List addSuffix(List items, String suffix) { 55 | throw new RuntimeException("NotYetImplemented"); 56 | } 57 | 58 | /*** 59 | * TODO: sort the given list of person using their first Name in natural order 60 | * 61 | * @param people list of person 62 | * */ 63 | public static List sortItemByFirstNameOrderAscending(List people) { 64 | throw new RuntimeException("NotYetImplemented"); 65 | } 66 | 67 | /** 68 | * TODO: sort the given list of person using last name in reserved order 69 | * 70 | * @param people list of person 71 | */ 72 | public static List sortByLastNameOrderDescending(List people) { 73 | throw new RuntimeException("NotYetImplemented"); 74 | } 75 | 76 | /** 77 | * TODO: sort the given list of the person using the first name and then last name and then age 78 | * which means, if there is the first name of two-person is same, then they would be sorted by the last name 79 | * if the first name and last name are the same, then they would be sorted by age in the natural order 80 | * 81 | * @param people list of person 82 | */ 83 | public static List sortByFirstNameAndThenLastNameAndThenAge(List people) { 84 | throw new RuntimeException("NotYetImplemented"); 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 33 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 34 | 35 | @rem Find java.exe 36 | if defined JAVA_HOME goto findJavaFromJavaHome 37 | 38 | set JAVA_EXE=java.exe 39 | %JAVA_EXE% -version >NUL 2>&1 40 | if "%ERRORLEVEL%" == "0" goto init 41 | 42 | echo. 43 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 44 | echo. 45 | echo Please set the JAVA_HOME variable in your environment to match the 46 | echo location of your Java installation. 47 | 48 | goto fail 49 | 50 | :findJavaFromJavaHome 51 | set JAVA_HOME=%JAVA_HOME:"=% 52 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 53 | 54 | if exist "%JAVA_EXE%" goto init 55 | 56 | echo. 57 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 58 | echo. 59 | echo Please set the JAVA_HOME variable in your environment to match the 60 | echo location of your Java installation. 61 | 62 | goto fail 63 | 64 | :init 65 | @rem Get command-line arguments, handling Windows variants 66 | 67 | if not "%OS%" == "Windows_NT" goto win9xME_args 68 | 69 | :win9xME_args 70 | @rem Slurp the command line arguments. 71 | set CMD_LINE_ARGS= 72 | set _SKIP=2 73 | 74 | :win9xME_args_slurp 75 | if "x%~1" == "x" goto execute 76 | 77 | set CMD_LINE_ARGS=%* 78 | 79 | :execute 80 | @rem Setup the command line 81 | 82 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 83 | 84 | @rem Execute Gradle 85 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 86 | 87 | :end 88 | @rem End local scope for the variables with windows NT shell 89 | if "%ERRORLEVEL%"=="0" goto mainEnd 90 | 91 | :fail 92 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 93 | rem the _cmd.exe /c_ return code! 94 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 95 | exit /b 1 96 | 97 | :mainEnd 98 | if "%OS%"=="Windows_NT" endlocal 99 | 100 | :omega 101 | -------------------------------------------------------------------------------- /src/test/java/com/masterdevskills/util/HasConcreteMethod.java: -------------------------------------------------------------------------------- 1 | package com.masterdevskills.util; 2 | 3 | /* 4 | * #%L 5 | * lambda-tutorial 6 | * %% 7 | * Copyright (C) 2013 Adopt OpenJDK 8 | * %% 9 | * This program is free software: you can redistribute it and/or modify 10 | * it under the terms of the GNU General Public License as 11 | * published by the Free Software Foundation, either version 2 of the 12 | * License, or (at your option) any later version. 13 | * 14 | * This program is distributed in the hope that it will be useful, 15 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 16 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 17 | * GNU General Public License for more details. 18 | * 19 | * You should have received a copy of the GNU General Public 20 | * License along with this program. If not, see 21 | * . 22 | * #L% 23 | */ 24 | 25 | import org.hamcrest.Description; 26 | import org.hamcrest.Matcher; 27 | import org.hamcrest.TypeSafeDiagnosingMatcher; 28 | import org.objectweb.asm.ClassReader; 29 | import org.objectweb.asm.ClassVisitor; 30 | import org.objectweb.asm.MethodVisitor; 31 | import org.objectweb.asm.Opcodes; 32 | 33 | import java.io.IOException; 34 | 35 | public class HasConcreteMethod extends TypeSafeDiagnosingMatcher> { 36 | private final String methodName; 37 | 38 | public HasConcreteMethod(String defaultMethodName) { 39 | this.methodName = defaultMethodName; 40 | } 41 | 42 | public static Matcher> called(String defaultMethodName) { 43 | return new HasConcreteMethod(defaultMethodName); 44 | } 45 | 46 | @Override 47 | protected boolean matchesSafely(Class item, Description mismatchDescription) { 48 | if (!hasConcreteMethod(methodName, item)) { 49 | mismatchDescription.appendText("did not have default method named ").appendText(methodName); 50 | return false; 51 | } 52 | 53 | return true; 54 | } 55 | 56 | @Override 57 | public void describeTo(Description description) { 58 | description.appendText("a type with a default method called " + methodName); 59 | } 60 | 61 | private boolean hasConcreteMethod(String defaultMethodName, Class clazz) { 62 | try { 63 | 64 | String resourceName = clazz.getName().replace(".", "/").concat(".class"); 65 | ClassReader reader = new ClassReader(clazz.getClassLoader().getResourceAsStream(resourceName)); 66 | HasDefaultMethodVisitor sourceFileNameVisitor = new HasDefaultMethodVisitor(defaultMethodName); 67 | reader.accept(sourceFileNameVisitor, 0); 68 | 69 | return sourceFileNameVisitor.defaultMethodExists(); 70 | } catch (IOException e) { 71 | throw new RuntimeException(e); 72 | } 73 | } 74 | 75 | 76 | private static final class HasDefaultMethodVisitor extends ClassVisitor { 77 | 78 | private final String defaultMethodName; 79 | private boolean visitedYet = false; 80 | private boolean hasDefaultMethod = false; 81 | 82 | public HasDefaultMethodVisitor(String defaultMethodName) { 83 | super(Opcodes.ASM5); 84 | this.defaultMethodName = defaultMethodName; 85 | } 86 | 87 | @Override 88 | public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) { 89 | visitedYet = true; 90 | hasDefaultMethod |= name.equals(defaultMethodName) && ((access & Opcodes.ACC_ABSTRACT) == 0); 91 | return super.visitMethod(access, name, desc, signature, exceptions); 92 | } 93 | 94 | public boolean defaultMethodExists() { 95 | if (!visitedYet) throw new IllegalStateException("Must visit a class before asking for result"); 96 | return this.hasDefaultMethod; 97 | } 98 | } 99 | } 100 | -------------------------------------------------------------------------------- /src/test/java/com/masterdevskills/cha1/ext3/ExercisesTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * #%L 3 | * Advanced Java LIVE course-2020 4 | * %% 5 | * Copyright (C) 2020 MasterDevSkills.com 6 | * %% 7 | * This program is free software: you can redistribute it and/or modify 8 | * it under the terms of the GNU General Public License as 9 | * published by the Free Software Foundation, either version 2 of the 10 | * License, or (at your option) any later version. 11 | * 12 | * This program is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU General Public License for more details. 16 | * 17 | * You should have received a copy of the GNU General Public 18 | * License along with this program. If not, see 19 | * . 20 | * #L% 21 | */ 22 | 23 | package com.masterdevskills.cha1.ext3; 24 | 25 | import org.junit.jupiter.api.Test; 26 | 27 | import java.util.ArrayList; 28 | import java.util.Arrays; 29 | import java.util.Comparator; 30 | import java.util.List; 31 | 32 | import static org.hamcrest.MatcherAssert.assertThat; 33 | import static org.hamcrest.Matchers.*; 34 | 35 | /** 36 | * @author A N M Bazlur Rahman @bazlur_rahman 37 | * @since 04 August 2020 38 | */ 39 | class ExercisesTest { 40 | 41 | @Test 42 | void doubling() { 43 | var ints = Arrays.asList(1, 2, 3, 4, 5, 6); 44 | 45 | //method under test 46 | var doubled = Exercises.doubling(ints); 47 | 48 | assertThat(doubled, hasSize(ints.size())); 49 | assertThat(doubled, is(equalTo(List.of(2, 4, 6, 8, 10, 12)))); 50 | } 51 | 52 | @Test 53 | void addSuffix() { 54 | 55 | var items = Arrays.asList("a", "b", "c"); 56 | 57 | //method under test 58 | var withSuffix = Exercises.addSuffix(items, ":)"); 59 | 60 | assertThat(withSuffix, hasSize(items.size())); 61 | assertThat(withSuffix, is(equalTo(List.of("a:)", "b:)", "c:)")))); 62 | 63 | } 64 | 65 | @Test 66 | void sortItemByFirstNameOrderAscending() { 67 | var people = getPeople(); 68 | 69 | //method under test 70 | var sorted = Exercises.sortItemByFirstNameOrderAscending(copy(people)); 71 | 72 | sortByFirsName(people); 73 | assertThat(sorted, equalTo(people)); 74 | } 75 | 76 | @Test 77 | void sortByLastNameOrderDescending() { 78 | var people = getPeople(); 79 | 80 | //method under test 81 | var sorted = Exercises.sortByLastNameOrderDescending(copy(people)); 82 | 83 | sortByLastNameDescendingOrder(people); 84 | assertThat(sorted, equalTo(people)); 85 | } 86 | 87 | @Test 88 | void sortByFirstNameAndThenLastNameAndThenAge() { 89 | var people = getPeople(); 90 | 91 | //method under test 92 | var sorted = Exercises.sortByFirstNameAndThenLastNameAndThenAge(copy(people)); 93 | sortByFirstNameAndThenLastNameAndThenAge(people); 94 | assertThat(sorted, equalTo(people)); 95 | } 96 | 97 | private void sortByFirstNameAndThenLastNameAndThenAge(List people) { 98 | people.sort(Comparator.comparing(Person::getFirstName).thenComparing(Person::getLastName).thenComparing(Person::getAge)); 99 | } 100 | 101 | private void sortByLastNameDescendingOrder(List people) { 102 | people.sort(Comparator.comparing(Person::getLastName).reversed()); 103 | } 104 | 105 | private void sortByFirsName(List people) { 106 | people.sort(Comparator.comparing(Person::getFirstName)); 107 | } 108 | 109 | private List copy(List people) { 110 | 111 | return new ArrayList<>(people); 112 | } 113 | 114 | private List getPeople() { 115 | 116 | return Arrays.asList(new Person("Khatib", "Fahad", 20), 117 | new Person("Tahniat", "Ashraf", 21), 118 | new Person("Tahniat", "Ahmed", 45), 119 | new Person("Ashfaque", "Ahmed", 35), 120 | new Person("Abdullah", "Khan", 18), 121 | new Person("Abdullah", "Alam", 19), 122 | new Person("Ashraful", "Alam", 19), 123 | new Person("Ashraful", "Alam", 34), 124 | new Person("Sajid", "Samsad", 29), 125 | new Person("Ruhshan", "Ahmed", 40)); 126 | } 127 | } -------------------------------------------------------------------------------- /src/main/java/com/masterdevskills/cha2/ext2/http/HttpMovieService.java: -------------------------------------------------------------------------------- 1 | /* 2 | * #%L 3 | * Advanced Java LIVE course-2020 4 | * %% 5 | * Copyright (C) 2020 MasterDevSkills.com 6 | * %% 7 | * This program is free software: you can redistribute it and/or modify 8 | * it under the terms of the GNU General Public License as 9 | * published by the Free Software Foundation, either version 2 of the 10 | * License, or (at your option) any later version. 11 | * 12 | * This program is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU General Public License for more details. 16 | * 17 | * You should have received a copy of the GNU General Public 18 | * License along with this program. If not, see 19 | * . 20 | * #L% 21 | */ 22 | 23 | package com.masterdevskills.cha2.ext2.http; 24 | 25 | import java.net.URI; 26 | import java.net.http.HttpClient; 27 | import java.net.http.HttpRequest; 28 | import java.net.http.HttpResponse; 29 | import java.net.http.HttpResponse.BodyHandlers; 30 | import java.util.List; 31 | import java.util.concurrent.CompletableFuture; 32 | import java.util.concurrent.ExecutionException; 33 | import java.util.stream.Collectors; 34 | 35 | /** 36 | * @author A N M Bazlur Rahman @bazlur_rahman 37 | * @since 07 August 2020 38 | */ 39 | public class HttpMovieService { 40 | private final HttpClient httpClient; 41 | private final String[] movies = "tt6751668, tt6751668, tt6751668, tt6966692, tt6966692, tt6966692, tt5580390, tt5580390, tt5580390, tt4975722, tt4975722, tt4975722, tt1895587, tt1895587, tt1895587, tt2562232, tt2562232, tt2562232, tt2024544, tt2024544, tt2024544, tt1024648, tt1024648, tt1024648, tt1655442, tt1655442, tt1655442, tt1504320, tt1504320, tt1504320, tt1010048, tt1010048, tt1010048, tt0887912, tt0887912, tt0887912, tt0477348, tt0477348, tt0477348, tt0407887, tt0407887, tt0407887, tt0405159, tt0405159, tt0405159, tt0375679, tt0375679, tt0375679, tt0167260, tt0167260, tt0167260, tt0299658, tt0299658, tt0299658, tt0268978, tt0268978, tt0268978, tt0172495, tt0172495, tt0172495, tt0169547, tt0169547, tt0169547, tt0138097, tt0138097, tt0138097, tt0120338, tt0120338, tt0120338, tt0116209, tt0116209, tt0116209, tt0112573, tt0112573, tt0112573, tt0109830, tt0109830, tt0109830, tt0108052, tt0108052, tt0108052, tt0105695, tt0105695, tt0105695, tt0102926, tt0102926, tt0102926, tt0099348, tt0099348, tt0099348, tt0097239, tt0097239, tt0097239, tt0095953, tt0095953, tt0095953, tt0093389, tt0093389, tt0093389, tt0091763, tt0091763, tt0091763, tt0089755, tt0089755, tt0089755, tt0086879, tt0086879, tt0086879, tt0086425, tt0086425, tt0086425, tt0083987, tt0083987, tt0083987, tt0082158, tt0082158, tt0082158, tt0081283, tt0081283, tt0081283, tt0079417, tt0079417, tt0079417, tt0077416, tt0077416, tt0077416, tt0075686, tt0075686, tt0075686, tt0075148, tt0075148, tt0075148, tt0073486, tt0073486, tt0073486, tt0071562, tt0071562, tt0071562, tt0070735, tt0070735, tt0070735, tt0068646, tt0068646, tt0068646, tt0067116, tt0067116, tt0067116, tt0066206, tt0066206, tt0066206, tt0064665, tt0064665, tt0064665, tt0063385, tt0063385, tt0063385, tt0061811, tt0061811, tt0061811, tt0060665, tt0060665, tt0060665, tt0059742, tt0059742, tt0059742, tt0058385, tt0058385, tt0058385, tt0057590, tt0057590, tt0057590, tt0056172, tt0056172, tt0056172, tt0055614, tt0055614, tt0055614, tt0053604, tt0053604, tt0053604, tt0052618, tt0052618, tt0052618, tt0051658, tt0051658, tt0051658, tt0050212, tt0050212, tt0050212, tt0048960, tt0048960, tt0048960, tt0048356, tt0048356, tt0048356, tt0047296, tt0047296, tt0047296, tt0045793, tt0045793, tt0045793, tt0044672, tt0044672, tt0044672, tt0043278, tt0043278, tt0043278, tt0042192, tt0042192, tt0042192, tt0041113, tt0041113, tt0041113, tt0040416, tt0040416, tt0040416, tt0039416, tt0039416, tt0039416, tt0036868, tt0036868, tt0036868, tt0037884, tt0037884, tt0037884, tt0036872, tt0036872, tt0036872, tt0035093, tt0035093, tt0035093, tt0034583, tt0034583, tt0034583, tt0033729, tt0033729, tt0033729, tt0032976, tt0032976, tt0032976, tt0031381, tt0031381, tt0031381, tt0030993, tt0030993, tt0030993, tt0029146, tt0029146, tt0029146, tt0027698, tt0027698, tt0027698, tt0026752, tt0026752, tt0026752, tt0025316, tt0025316, tt0025316, tt0023876, tt0023876, tt0023876, tt0022958, tt0022958, tt0022958, tt0021746, tt0021746, tt0021746, tt0020629, tt0020629, tt0020629, tt0019729, tt0019729, tt0019729, tt0018578, tt0018578, tt0018578, tt0018455, tt0018455, tt0018455".split(","); 42 | 43 | private HttpMovieService() { 44 | httpClient = HttpClient.newBuilder().build(); 45 | } 46 | 47 | public static HttpMovieService getHttpClient() { 48 | return new HttpMovieService(); 49 | } 50 | 51 | public void downloadMovieDB() { 52 | var start = System.nanoTime(); 53 | var apiEndPoint = "http://www.omdbapi.com/?i=%s&apikey=e056203e"; 54 | var futures = List.of(movies) 55 | .parallelStream() 56 | .map(id -> HttpRequest.newBuilder() 57 | .uri(URI.create(String.format(apiEndPoint, id.trim()))) 58 | .build()).map(request -> httpClient.sendAsync(request, BodyHandlers.ofString())) 59 | .collect(Collectors.toList()); 60 | 61 | var result = CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])) 62 | .thenApply(f -> futures.stream().map(CompletableFuture::join) 63 | .map(HttpResponse::body) 64 | .collect(Collectors.toList())); 65 | try { 66 | System.out.println(result.get()); 67 | } catch (InterruptedException | ExecutionException e) { 68 | e.printStackTrace(); 69 | } 70 | System.out.println("total time: " + (System.nanoTime() - start) / 100_000); 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | # 4 | # Copyright 2015 the original author or authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | ## 21 | ## Gradle start up script for UN*X 22 | ## 23 | ############################################################################## 24 | 25 | # Attempt to set APP_HOME 26 | # Resolve links: $0 may be a link 27 | PRG="$0" 28 | # Need this for relative symlinks. 29 | while [ -h "$PRG" ] ; do 30 | ls=`ls -ld "$PRG"` 31 | link=`expr "$ls" : '.*-> \(.*\)$'` 32 | if expr "$link" : '/.*' > /dev/null; then 33 | PRG="$link" 34 | else 35 | PRG=`dirname "$PRG"`"/$link" 36 | fi 37 | done 38 | SAVED="`pwd`" 39 | cd "`dirname \"$PRG\"`/" >/dev/null 40 | APP_HOME="`pwd -P`" 41 | cd "$SAVED" >/dev/null 42 | 43 | APP_NAME="Gradle" 44 | APP_BASE_NAME=`basename "$0"` 45 | 46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 48 | 49 | # Use the maximum available, or set MAX_FD != -1 to use that value. 50 | MAX_FD="maximum" 51 | 52 | warn () { 53 | echo "$*" 54 | } 55 | 56 | die () { 57 | echo 58 | echo "$*" 59 | echo 60 | exit 1 61 | } 62 | 63 | # OS specific support (must be 'true' or 'false'). 64 | cygwin=false 65 | msys=false 66 | darwin=false 67 | nonstop=false 68 | case "`uname`" in 69 | CYGWIN* ) 70 | cygwin=true 71 | ;; 72 | Darwin* ) 73 | darwin=true 74 | ;; 75 | MINGW* ) 76 | msys=true 77 | ;; 78 | NONSTOP* ) 79 | nonstop=true 80 | ;; 81 | esac 82 | 83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 84 | 85 | # Determine the Java command to use to start the JVM. 86 | if [ -n "$JAVA_HOME" ] ; then 87 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 88 | # IBM's JDK on AIX uses strange locations for the executables 89 | JAVACMD="$JAVA_HOME/jre/sh/java" 90 | else 91 | JAVACMD="$JAVA_HOME/bin/java" 92 | fi 93 | if [ ! -x "$JAVACMD" ] ; then 94 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 95 | 96 | Please set the JAVA_HOME variable in your environment to match the 97 | location of your Java installation." 98 | fi 99 | else 100 | JAVACMD="java" 101 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 102 | 103 | Please set the JAVA_HOME variable in your environment to match the 104 | location of your Java installation." 105 | fi 106 | 107 | # Increase the maximum file descriptors if we can. 108 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 109 | MAX_FD_LIMIT=`ulimit -H -n` 110 | if [ $? -eq 0 ] ; then 111 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 112 | MAX_FD="$MAX_FD_LIMIT" 113 | fi 114 | ulimit -n $MAX_FD 115 | if [ $? -ne 0 ] ; then 116 | warn "Could not set maximum file descriptor limit: $MAX_FD" 117 | fi 118 | else 119 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 120 | fi 121 | fi 122 | 123 | # For Darwin, add options to specify how the application appears in the dock 124 | if $darwin; then 125 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 126 | fi 127 | 128 | # For Cygwin or MSYS, switch paths to Windows format before running java 129 | if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then 130 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 131 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 132 | JAVACMD=`cygpath --unix "$JAVACMD"` 133 | 134 | # We build the pattern for arguments to be converted via cygpath 135 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 136 | SEP="" 137 | for dir in $ROOTDIRSRAW ; do 138 | ROOTDIRS="$ROOTDIRS$SEP$dir" 139 | SEP="|" 140 | done 141 | OURCYGPATTERN="(^($ROOTDIRS))" 142 | # Add a user-defined pattern to the cygpath arguments 143 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 144 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 145 | fi 146 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 147 | i=0 148 | for arg in "$@" ; do 149 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 150 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 151 | 152 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 153 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 154 | else 155 | eval `echo args$i`="\"$arg\"" 156 | fi 157 | i=`expr $i + 1` 158 | done 159 | case $i in 160 | 0) set -- ;; 161 | 1) set -- "$args0" ;; 162 | 2) set -- "$args0" "$args1" ;; 163 | 3) set -- "$args0" "$args1" "$args2" ;; 164 | 4) set -- "$args0" "$args1" "$args2" "$args3" ;; 165 | 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 166 | 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 167 | 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 168 | 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 169 | 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 170 | esac 171 | fi 172 | 173 | # Escape application args 174 | save () { 175 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 176 | echo " " 177 | } 178 | APP_ARGS=`save "$@"` 179 | 180 | # Collect all arguments for the java command, following the shell quoting and substitution rules 181 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 182 | 183 | exec "$JAVACMD" "$@" 184 | -------------------------------------------------------------------------------- /src/test/java/com/masterdevskills/util/CodeUsesMethodReferencesMatcher.java: -------------------------------------------------------------------------------- 1 | package com.masterdevskills.util; 2 | 3 | /* 4 | * #%L 5 | * lambda-tutorial 6 | * %% 7 | * Copyright (C) 2013 Adopt OpenJDK 8 | * %% 9 | * This program is free software: you can redistribute it and/or modify 10 | * it under the terms of the GNU General Public License as 11 | * published by the Free Software Foundation, either version 2 of the 12 | * License, or (at your option) any later version. 13 | * 14 | * This program is distributed in the hope that it will be useful, 15 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 16 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 17 | * GNU General Public License for more details. 18 | * 19 | * You should have received a copy of the GNU General Public 20 | * License along with this program. If not, see 21 | * . 22 | * #L% 23 | */ 24 | 25 | import org.hamcrest.Description; 26 | import org.hamcrest.TypeSafeDiagnosingMatcher; 27 | import org.objectweb.asm.ClassReader; 28 | import org.objectweb.asm.ClassVisitor; 29 | import org.objectweb.asm.Opcodes; 30 | 31 | import java.io.File; 32 | import java.io.IOException; 33 | import java.nio.ByteBuffer; 34 | import java.nio.charset.StandardCharsets; 35 | import java.nio.file.Files; 36 | import java.nio.file.Path; 37 | import java.nio.file.Paths; 38 | import java.util.Arrays; 39 | import java.util.Optional; 40 | 41 | import static java.util.stream.Collectors.toList; 42 | 43 | public final class CodeUsesMethodReferencesMatcher extends TypeSafeDiagnosingMatcher> { 44 | 45 | private final String methodName; 46 | 47 | private CodeUsesMethodReferencesMatcher(String methodName) { 48 | this.methodName = methodName; 49 | } 50 | 51 | public static CodeUsesMethodReferencesMatcher usesMethodReferences(String methodName) { 52 | return new CodeUsesMethodReferencesMatcher(methodName); 53 | } 54 | 55 | @Override 56 | public void describeTo(Description description) { 57 | description.appendText("a source file using a method reference to invoke ").appendValue(methodName); 58 | } 59 | 60 | 61 | @Override 62 | protected boolean matchesSafely(Class clazz, Description mismatchDescription) { 63 | try { 64 | Optional sourceFileContent = getSourceContent(clazz); 65 | return sourceFileContent.map(c -> usesMethodReference(c, mismatchDescription)).orElseGet(() -> { 66 | mismatchDescription.appendText("could not read source file to discover if you used method references."); 67 | return false; 68 | }); 69 | } catch (IOException e) { 70 | mismatchDescription.appendText("could not read source file to discover if you used method references."); 71 | mismatchDescription.appendValue(e); 72 | return false; 73 | } 74 | } 75 | 76 | private boolean usesMethodReference(String sourceCode, Description mismatchDescription) { 77 | if (sourceCode.contains("::" + methodName)) { 78 | return true; 79 | } else { 80 | mismatchDescription.appendText("source code did not use a method reference to invoke " + methodName + ". "); 81 | context(sourceCode, methodName, mismatchDescription); 82 | return false; 83 | } 84 | } 85 | 86 | private void context(String sourceCode, String methodName, Description mismatchDescription) { 87 | if (!sourceCode.contains(methodName)) { 88 | mismatchDescription.appendText("You did not appear to invoke the method at all."); 89 | } else { 90 | String[] lines = sourceCode.split("\\n"); 91 | mismatchDescription.appendText("Actual invocations: "); 92 | mismatchDescription.appendValueList("[", ",", "]", 93 | Arrays.stream(lines).filter(l -> l.contains(methodName)).map(String::trim).collect(toList())); 94 | } 95 | } 96 | 97 | private Optional getSourceContent(Class clazz) throws IOException { 98 | String sourceFileName = getSourceFileName(clazz); 99 | Optional sourceFile = findPathTo(sourceFileName); 100 | 101 | return sourceFile.map(this::toContent); 102 | } 103 | 104 | private Optional findPathTo(String sourceFileName) throws IOException { 105 | File cwd = new File("."); 106 | File rootOfProject = findRootOfProject(cwd); 107 | return findSourceFile(rootOfProject, sourceFileName); 108 | } 109 | 110 | private String toContent(File file) { 111 | try { 112 | byte[] encoded = Files.readAllBytes(Paths.get(file.toURI())); 113 | return StandardCharsets.UTF_8.decode(ByteBuffer.wrap(encoded)).toString(); 114 | } catch (IOException e) { 115 | throw new RuntimeException("Could not read Java source file.", e); 116 | } 117 | } 118 | 119 | private Optional findSourceFile(File rootOfProject, String sourceFileName) throws IOException { 120 | Path startingDir = Paths.get(rootOfProject.toURI()); 121 | return Files.find(startingDir, 15, (path, attrs) -> path.endsWith(sourceFileName)) 122 | .map(p -> new File(p.toUri())) 123 | .findFirst(); 124 | } 125 | 126 | private File findRootOfProject(File cwd) { 127 | File[] pomFiles = cwd.listFiles((file, name) -> { 128 | return name.equals("build.gradle"); 129 | }); 130 | if (pomFiles != null && pomFiles.length == 1) { 131 | return cwd; 132 | } else if (cwd.getParentFile() == null) { 133 | throw new RuntimeException("Couldn't find directory containing build.gradle. Last looked in: " + cwd.getAbsolutePath()); 134 | } else { 135 | return findRootOfProject(cwd.getParentFile()); 136 | } 137 | } 138 | 139 | private String getSourceFileName(Class clazz) throws IOException { 140 | String resourceName = clazz.getName().replace(".", "/").concat(".class"); 141 | ClassReader reader = new ClassReader(clazz.getClassLoader().getResourceAsStream(resourceName)); 142 | SourceFileNameVisitor sourceFileNameVisitor = new SourceFileNameVisitor(); 143 | reader.accept(sourceFileNameVisitor, 0); 144 | 145 | return sourceFileNameVisitor.getSourceFile(); 146 | } 147 | 148 | 149 | private static final class SourceFileNameVisitor extends ClassVisitor { 150 | 151 | private String sourceFile = null; 152 | private boolean visitedYet = false; 153 | 154 | public SourceFileNameVisitor() { 155 | super(Opcodes.ASM9); 156 | } 157 | 158 | @Override 159 | public void visitSource(String source, String debug) { 160 | this.visitedYet = true; 161 | this.sourceFile = source; 162 | super.visitSource(source, debug); 163 | } 164 | 165 | public String getSourceFile() { 166 | if (!visitedYet) throw new IllegalStateException("Must visit a class before asking for source file"); 167 | return this.sourceFile; 168 | } 169 | } 170 | 171 | } 172 | -------------------------------------------------------------------------------- /src/test/java/com/masterdevskills/cha2/ext2/service/RealMovieServiceTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * #%L 3 | * Advanced Java LIVE course-2020 4 | * %% 5 | * Copyright (C) 2020 MasterDevSkills.com 6 | * %% 7 | * This program is free software: you can redistribute it and/or modify 8 | * it under the terms of the GNU General Public License as 9 | * published by the Free Software Foundation, either version 2 of the 10 | * License, or (at your option) any later version. 11 | * 12 | * This program is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU General Public License for more details. 16 | * 17 | * You should have received a copy of the GNU General Public 18 | * License along with this program. If not, see 19 | * . 20 | * #L% 21 | */ 22 | 23 | package com.masterdevskills.cha2.ext2.service; 24 | 25 | import com.masterdevskills.cha2.ext2.model.Movie; 26 | import org.junit.jupiter.api.BeforeEach; 27 | import org.junit.jupiter.api.Test; 28 | 29 | import java.util.HashMap; 30 | import java.util.List; 31 | import java.util.Map; 32 | import java.util.Optional; 33 | import java.util.stream.Collectors; 34 | 35 | import static java.util.Comparator.comparing; 36 | import static org.hamcrest.MatcherAssert.assertThat; 37 | import static org.hamcrest.Matchers.*; 38 | import static org.junit.jupiter.api.Assertions.*; 39 | 40 | /** 41 | * @author A N M Bazlur Rahman @bazlur_rahman 42 | * @since 07 August 2020 43 | */ 44 | class RealMovieServiceTest { 45 | private RealMovieService realMovieService; 46 | 47 | @BeforeEach 48 | public void setup() { 49 | realMovieService = new RealMovieService(); 50 | } 51 | 52 | @Test 53 | void findAllMoviesInYear() { 54 | assertThat(realMovieService.findAllMoviesInYear(2019), hasSize(3)); 55 | assertThat(realMovieService.findAllMoviesInYear(2020), hasSize(0)); 56 | } 57 | 58 | @Test 59 | void findAllMovieRated() { 60 | assertThat(realMovieService.findAllMovieRated("R"), hasSize(93)); 61 | assertThat(realMovieService.findAllMovieRated("PG-13"), hasSize(33)); 62 | } 63 | 64 | @Test 65 | void findMoviesWithIMdbRating() { 66 | assertThat(realMovieService.findMoviesWithImdbRatingEqualAndGreaterThan(7), hasSize(255)); 67 | assertThat(realMovieService.findMoviesWithImdbRatingEqualAndGreaterThan(8), hasSize(132)); 68 | assertThat(realMovieService.findMoviesWithImdbRatingEqualAndGreaterThan(8.5), hasSize(33)); 69 | assertThat(realMovieService.findMoviesWithImdbRatingEqualAndGreaterThan(9), hasSize(6)); 70 | } 71 | 72 | @Test 73 | void findMoviesOfDirector() { 74 | assertThat(realMovieService.findMoviesOfDirector("Barry Jenkins"), hasSize(3)); 75 | } 76 | 77 | @Test 78 | void listMovieTitleRated() { 79 | assertThat(realMovieService.listMovieTitleRated("PG-13"), hasSize(33)); 80 | } 81 | 82 | @Test 83 | void listUniqueMovieTitleRated() { 84 | var movieTitles = realMovieService.listUniqueMovieTitleRated("PG-13"); 85 | assertThat(movieTitles, hasSize(11)); 86 | } 87 | 88 | @Test 89 | void sortMovieByTitle() { 90 | var allMovies = InMemoryMovieService.getInstance().findAllMovies(); 91 | var moviesToTest = realMovieService.sortMovieByTitle(); 92 | var sortedMovies = allMovies.stream().sorted(comparing(Movie::getTitle)).collect(Collectors.toList()); 93 | 94 | assertThat(moviesToTest, equalTo(sortedMovies)); 95 | } 96 | 97 | @Test 98 | void sortByImdbRatingAndThenTitle() { 99 | var allMovies = InMemoryMovieService.getInstance().findAllMovies(); 100 | 101 | allMovies.sort(comparing(Movie::getImdbRating) 102 | .thenComparing(Movie::getTitle)); 103 | 104 | List moviesToTest = realMovieService.sortByImdbRatingAndThenTitle(); 105 | assertThat(moviesToTest, equalTo(allMovies)); 106 | } 107 | 108 | @Test 109 | void findAnyMovieTitleWithImdbRatingEqualOrGreater() { 110 | Optional movie = realMovieService.findAnyMovieTitleWithImdbRatingEqualOrGreater(8); 111 | assertTrue(movie.isPresent()); 112 | assertThat(movie.get(), is("The King's Speech")); 113 | 114 | assertFalse(realMovieService.findAnyMovieTitleWithImdbRatingEqualOrGreater(10).isPresent()); 115 | 116 | } 117 | 118 | @Test 119 | void findFirstMovieTitleWithImdbRatingEqualOrGreater() { 120 | var movie = realMovieService.findFirstMovieTitleWithImdbRatingEqualOrGreater(7); 121 | 122 | assertTrue(movie.isPresent()); 123 | assertThat(movie.get(), is("Going My Way")); 124 | 125 | assertFalse(realMovieService.findFirstMovieTitleWithImdbRatingEqualOrGreater(10).isPresent()); 126 | } 127 | 128 | @Test 129 | void findTopRatedMovie() { 130 | assertTrue(realMovieService.findTopRatedMovie().isPresent()); 131 | assertEquals(realMovieService.findTopRatedMovie().get().getImdbRating(), 9.2); 132 | } 133 | 134 | @Test 135 | void findMinRatedMovie() { 136 | assertTrue(realMovieService.findMinRatedMovie().isPresent()); 137 | assertEquals(realMovieService.findMinRatedMovie().get().getImdbRating(), 5.7); 138 | } 139 | 140 | @Test 141 | void getMoviesByYear() { 142 | //method under test 143 | Map moviesByYear = realMovieService.getMoviesByYear(); 144 | 145 | assertThat(moviesByYear, is(getMoviesByYearImperatively())); 146 | assertThat(moviesByYear.size(), is(89)); 147 | assertThat(moviesByYear, hasEntry("1976", "Rocky, Rocky, Rocky")); 148 | assertThat(moviesByYear, not(hasEntry("2020", "Extraction"))); 149 | assertThat(moviesByYear, hasKey("2013")); 150 | assertThat(moviesByYear, hasValue("Wings, Wings, Wings, Sunrise, Sunrise, Sunrise")); 151 | } 152 | 153 | @Test 154 | void findNumberOfDistinctMoviesOfEachDirector() { 155 | var numberOfDistinctMoviesOfEachDirector = realMovieService.findNumberOfDistinctMoviesOfEachDirector(); 156 | 157 | assertThat(numberOfDistinctMoviesOfEachDirector, is(findNumberOfDistinctMoviesOfEachDirectorImperatively())); 158 | 159 | } 160 | 161 | 162 | private Map getMoviesByYearImperatively() { 163 | var allMovies = InMemoryMovieService.getInstance().findAllMovies(); 164 | Map map = new HashMap<>(); 165 | for (Movie allMovie : allMovies) { 166 | String year = allMovie.getYear(); 167 | if (map.containsKey(year)) { 168 | map.put(year, map.get(year) + ", " + allMovie.getTitle()); 169 | } else { 170 | map.put(year, allMovie.getTitle()); 171 | } 172 | } 173 | return map; 174 | } 175 | 176 | private Map findNumberOfDistinctMoviesOfEachDirectorImperatively() { 177 | var movies = InMemoryMovieService.getInstance().findAllMovies().stream().distinct().collect(Collectors.toList()); 178 | Map map = new HashMap<>(); 179 | for (Movie allMovie : movies) { 180 | String director = allMovie.getDirector(); 181 | if (map.containsKey(director)) { 182 | map.put(director, map.get(director) + 1); 183 | } else { 184 | map.put(director, 1L); 185 | } 186 | } 187 | return map; 188 | } 189 | } -------------------------------------------------------------------------------- /src/main/java/com/masterdevskills/cha2/ext2/service/RealMovieService.java: -------------------------------------------------------------------------------- 1 | /* 2 | * #%L 3 | * Advanced Java LIVE course-2020 4 | * %% 5 | * Copyright (C) 2020 MasterDevSkills.com 6 | * %% 7 | * This program is free software: you can redistribute it and/or modify 8 | * it under the terms of the GNU General Public License as 9 | * published by the Free Software Foundation, either version 2 of the 10 | * License, or (at your option) any later version. 11 | * 12 | * This program is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU General Public License for more details. 16 | * 17 | * You should have received a copy of the GNU General Public 18 | * License along with this program. If not, see 19 | * . 20 | * #L% 21 | */ 22 | 23 | package com.masterdevskills.cha2.ext2.service; 24 | 25 | import com.masterdevskills.cha2.ext2.model.Movie; 26 | 27 | import java.util.Comparator; 28 | import java.util.List; 29 | import java.util.Map; 30 | import java.util.Optional; 31 | import java.util.function.Function; 32 | import java.util.function.Predicate; 33 | import java.util.stream.Collector; 34 | import java.util.stream.Stream; 35 | 36 | /** 37 | * @author A N M Bazlur Rahman @bazlur_rahman 38 | * @since 07 August 2020 39 | */ 40 | public class RealMovieService { 41 | 42 | 43 | /** 44 | * TODO: count the Movie object stored in InMemoryMovieService 45 | * 46 | * @return number of movies stored in the InMemoryMovieService 47 | * @see Stream#count() 48 | */ 49 | public long countMovies() { 50 | var allMovies = InMemoryMovieService.getInstance().findAllMovies(); 51 | return allMovies.stream() 52 | .count(); 53 | } 54 | 55 | /** 56 | * TODO: find all the movies released in a particular year 57 | * 58 | * @param year given year 59 | * @return list of Movies in a particular year 60 | * @see java.util.stream.Stream#filter(Predicate) 61 | * @see java.util.stream.Stream#collect(Collector) 62 | */ 63 | public List findAllMoviesInYear(int year) { 64 | 65 | throw new RuntimeException("TODO://ImplementIt"); 66 | } 67 | 68 | /** 69 | * TODO: given a rating, return the list of the movies of that rating 70 | * 71 | * @param rated given rating 72 | * @return list of movies of that rating 73 | * @see java.util.stream.Stream#filter(Predicate) 74 | * @see java.util.stream.Stream#collect(Collector) 75 | */ 76 | 77 | public List findAllMovieRated(String rated) { 78 | 79 | throw new RuntimeException("TODO://ImplementIt"); 80 | } 81 | 82 | /** 83 | * TODO: given a rating, return the count of the movies of that rating 84 | * 85 | * @param rated given rating 86 | * @return count of movies of that rating 87 | * @see java.util.stream.Stream#filter(Predicate) 88 | * @see java.util.stream.Stream#collect(Collector) 89 | */ 90 | 91 | public long countMoviesWithRated(String rated) { 92 | 93 | throw new RuntimeException("TODO://ImplementIt"); 94 | } 95 | 96 | /** 97 | * TODO: given a rating, return list of movies whose ratings are equal or greater than given rating 98 | * 99 | * @param rating given rating 100 | * @return list of movies whose ratings are equal or greater than given rating 101 | * @see java.util.stream.Stream#filter(Predicate) 102 | * @see java.util.stream.Stream#collect(Collector) 103 | */ 104 | public List findMoviesWithImdbRatingEqualAndGreaterThan(double rating) { 105 | 106 | throw new RuntimeException("TODO://ImplementIt"); 107 | } 108 | 109 | /** 110 | * TODO: return list of movies that are directed by given director name 111 | * 112 | * @param director name of director 113 | * @return list of movies that are directed by given director name 114 | * @see java.util.stream.Stream#filter(Predicate) 115 | * @see java.util.stream.Stream#collect(Collector) 116 | */ 117 | public List findMoviesOfDirector(String director) { 118 | 119 | throw new RuntimeException("TODO://ImplementIt"); 120 | } 121 | 122 | /** 123 | * TODO: return list of Movie Title of those movies whose rating is equal to given rating 124 | * 125 | * @param rated given rating 126 | * @return list of Movie Title of those movies whose rating is equal to given rating 127 | */ 128 | public List listMovieTitleRated(String rated) { 129 | 130 | throw new RuntimeException("TODO://ImplementIt"); 131 | } 132 | 133 | /** 134 | * TODO: return list of distinct movie title of that movie, whose rating is equal to given rating 135 | * 136 | * @param rated given rating 137 | * @return list of distinct movie title of that movie, whose rating is equal to given rating 138 | * @see java.util.stream.Stream#filter(Predicate) 139 | * @see java.util.stream.Stream#collect(Collector) 140 | * @see Stream#distinct() 141 | */ 142 | public List listUniqueMovieTitleRated(String rated) { 143 | 144 | throw new RuntimeException("TODO://ImplementIt"); 145 | } 146 | 147 | /** 148 | * TODO: return movie title of any movie whose rating is equal or greater than given rating 149 | * 150 | * @param rating given rating 151 | * @return movie title of any movie whose rating is equal or greater than given rating 152 | * @see Stream#findAny() 153 | */ 154 | public Optional findAnyMovieTitleWithImdbRatingEqualOrGreater(double rating) { 155 | 156 | throw new RuntimeException("TODO://ImplementIt"); 157 | } 158 | 159 | /** 160 | * TODO: return movie title of the first movie whose rating is equal or greater than given rating 161 | * 162 | * @param rating given rating 163 | * @return name of the first movie with given rating, empty if not 164 | * @see Stream#findFirst() 165 | * @see Stream#map(Function) 166 | */ 167 | public Optional findFirstMovieTitleWithImdbRatingEqualOrGreater(double rating) { 168 | 169 | throw new RuntimeException("TODO://ImplementIt"); 170 | } 171 | 172 | /** 173 | * TODO: sort all the movies by their title and return the sorted list 174 | * 175 | * @return the sorted list 176 | * @see Stream#sorted(Comparator) 177 | */ 178 | public List sortMovieByTitle() { 179 | throw new RuntimeException("TODO://ImplementIt"); 180 | } 181 | 182 | /** 183 | * TODO: sort all the movies by their imdb rating, then by their title(if rating are equal) and return the sorted list 184 | * 185 | * @return the sorted list 186 | * @see Stream#sorted(Comparator) 187 | * @see Comparator#thenComparing(Function) 188 | */ 189 | public List sortByImdbRatingAndThenTitle() { 190 | 191 | throw new RuntimeException("TODO://ImplementIt"); 192 | } 193 | 194 | /** 195 | * TODO: find top rated movie from all the movies and return the Movie 196 | * 197 | * @return movie with maximum rating 198 | * @see Stream#max(Comparator) 199 | */ 200 | 201 | public Optional findTopRatedMovie() { 202 | throw new RuntimeException("TODO://ImplementIt"); 203 | } 204 | 205 | /** 206 | * TODO: find min rated movie from all the movies and return the Movie 207 | * 208 | * @return movie with minimum rating 209 | */ 210 | 211 | public Optional findMinRatedMovie() { 212 | throw new RuntimeException("TODO://ImplementIt"); 213 | } 214 | 215 | /** 216 | * TODO: find number of Distinct Movies of each director 217 | * 218 | * @return list of Distinct movies 219 | */ 220 | 221 | public Map findNumberOfDistinctMoviesOfEachDirector() { 222 | throw new RuntimeException("TODO://ImplementIt"); 223 | } 224 | 225 | /** 226 | * TODO: find number movies title by years comma separated 227 | * 228 | * @return map containing year and movie tiles comma separated 229 | */ 230 | public Map getMoviesByYear() { 231 | throw new RuntimeException("TODO://ImplementIt"); 232 | } 233 | } 234 | 235 | 236 | --------------------------------------------------------------------------------