├── .gitignore ├── .travis.yml ├── LICENSE ├── README.md ├── chapter_001 ├── pom.xml └── src │ ├── main │ └── java │ │ └── ru │ │ └── job4j │ │ ├── array │ │ ├── ArrayChar.java │ │ ├── ArrayDuplicate.java │ │ ├── ArrayMerge.java │ │ ├── BubbleSort.java │ │ ├── Check.java │ │ ├── EndsWith.java │ │ ├── FindLoop.java │ │ ├── Matrix.java │ │ ├── MatrixCheck.java │ │ ├── Square.java │ │ └── Turn.java │ │ ├── calculate │ │ ├── Calculate.java │ │ └── package-info.java │ │ ├── calculator │ │ ├── Calculator.java │ │ └── Fit.java │ │ ├── condition │ │ ├── DummyBot.java │ │ ├── Point.java │ │ └── Triangle.java │ │ ├── converter │ │ └── Converter.java │ │ ├── loop │ │ ├── Board.java │ │ ├── Counter.java │ │ ├── Factorial.java │ │ ├── Fitness.java │ │ ├── Mortgage.java │ │ ├── Paint.java │ │ └── PrimeNumber.java │ │ └── max │ │ └── Max.java │ └── test │ └── java │ └── ru │ └── job4j │ ├── array │ ├── ArrayCharTest.java │ ├── ArrayDuplicateTest.java │ ├── ArrayMergeTest.java │ ├── BubbleSortTest.java │ ├── CheckTest.java │ ├── EndsWithTest.java │ ├── FindLoopTest.java │ ├── MatrixCheckTest.java │ ├── MatrixTest.java │ ├── SquareTest.java │ └── TurnTest.java │ ├── calculate │ ├── CalculateTest.java │ └── package-info.java │ ├── calculator │ ├── CalculatorTest.java │ └── FitTest.java │ ├── condition │ ├── DummyBotTest.java │ ├── PointTest.java │ └── TriangleTest.java │ ├── converter │ └── ConverterTest.java │ ├── loop │ ├── BoardTest.java │ ├── CounterTest.java │ ├── FactorialTest.java │ ├── FitnessTest.java │ ├── MortgageTest.java │ ├── PaintTest.java │ └── PrimeNumberTest.java │ └── max │ └── MaxTest.java ├── chapter_002 ├── pom.xml └── src │ ├── main │ ├── java │ │ └── ru │ │ │ └── job4j │ │ │ ├── coffee │ │ │ └── CoffeeMachine.java │ │ │ ├── professions │ │ │ ├── Diagnose.java │ │ │ ├── Doctor.java │ │ │ ├── Engineer.java │ │ │ ├── House.java │ │ │ ├── Patient.java │ │ │ ├── Profession.java │ │ │ ├── Student.java │ │ │ └── Teacher.java │ │ │ ├── pseudo │ │ │ ├── Paint.java │ │ │ ├── Shape.java │ │ │ ├── Square.java │ │ │ └── Triangle.java │ │ │ └── tracker │ │ │ ├── BaseAction.java │ │ │ ├── ConsoleInput.java │ │ │ ├── ITracker.java │ │ │ ├── Input.java │ │ │ ├── Item.java │ │ │ ├── MenuOutException.java │ │ │ ├── MenuTracker.java │ │ │ ├── StartUI.java │ │ │ ├── StubInput.java │ │ │ ├── Tracker.java │ │ │ ├── TrackerSQL.java │ │ │ ├── TrackerSingle.java │ │ │ ├── TrackerSingleStaticField.java │ │ │ ├── TrackerSingleStaticFinalClass.java │ │ │ ├── TrackerSingleStaticFinalField.java │ │ │ ├── UserAction.java │ │ │ └── ValidateInput.java │ └── resources │ │ ├── app.properties │ │ └── log4j2.xml │ └── test │ └── java │ └── ru │ └── job4j │ ├── coffee │ └── CoffeeMachineTest.java │ ├── pseudo │ ├── PaintTest.java │ ├── SquareTest.java │ └── TriangleTest.java │ └── tracker │ ├── StartUITest.java │ ├── TrackerSingleTest.java │ ├── TrackerTest.java │ └── ValidateInputTest.java ├── chapter_003 ├── pom.xml └── src │ ├── main │ └── java │ │ └── ru │ │ └── job4j │ │ ├── bank │ │ ├── Account.java │ │ ├── Bank.java │ │ └── User.java │ │ ├── comparator │ │ └── ListCompare.java │ │ ├── list │ │ ├── ConvertList2Array.java │ │ ├── ConvertMatrix2List.java │ │ ├── User.java │ │ └── UserConvert.java │ │ ├── search │ │ ├── Person.java │ │ ├── PhoneDictionary.java │ │ ├── PriorityQueue.java │ │ └── Task.java │ │ └── sort │ │ ├── Departments.java │ │ ├── DepartmentsSort.java │ │ ├── SortUser.java │ │ ├── Sorter.java │ │ └── User.java │ └── test │ └── java │ └── ru │ └── job4j │ ├── bank │ └── BankTest.java │ ├── comparator │ └── StringsCompareTest.java │ ├── list │ ├── ConvertList2ArrayTest.java │ ├── ConvertMatrix2ListTest.java │ └── UserConvertTest.java │ ├── search │ ├── PhoneDictionaryTest.java │ └── PriorityQueueTest.java │ └── sort │ ├── DepartmentsSortTest.java │ ├── DepartmentsTest.java │ ├── SortUserTest.java │ └── SorterTest.java ├── chapter_004 ├── pom.xml └── src │ ├── main │ └── java │ │ └── ru │ │ └── job4j │ │ ├── diapason │ │ └── Diapason.java │ │ ├── lambda │ │ ├── Calculator.java │ │ ├── MathUtil.java │ │ └── UserConvert.java │ │ ├── matrix │ │ └── MatrixToList.java │ │ ├── profiles │ │ ├── Address.java │ │ ├── Profile.java │ │ └── Profiles.java │ │ ├── school │ │ ├── School.java │ │ └── Student.java │ │ └── stream │ │ ├── ArrayProcessing.java │ │ └── StreamUsage.java │ └── test │ └── java │ └── ru │ └── job4j │ ├── diapason │ └── DiapasonTest.java │ ├── lambda │ └── CalculatorTest.java │ ├── matrix │ └── MatrixToListTest.java │ ├── profiles │ └── ProfilesTest.java │ ├── school │ └── SchoolTest.java │ └── stream │ ├── ArrayProcessingTest.java │ └── StreamUsageTest.java ├── chapter_005 ├── pom.xml └── src │ ├── main │ └── java │ │ └── ru │ │ └── job4j │ │ ├── generic │ │ ├── AbstractStore.java │ │ ├── Base.java │ │ ├── Role.java │ │ ├── RoleStore.java │ │ ├── SimpleArray.java │ │ ├── Store.java │ │ ├── User.java │ │ └── UserStore.java │ │ ├── interview │ │ ├── Anagram.java │ │ ├── DBScripts.java │ │ └── VulnerabilityScript.java │ │ ├── iterator │ │ ├── EvenIt.java │ │ ├── IteratorOfIterators.java │ │ └── JaggedArrayIterator.java │ │ ├── list │ │ ├── BaseList.java │ │ ├── LinkedListCheck.java │ │ ├── SimpleArrayList.java │ │ ├── SimpleLinkedList.java │ │ ├── SimpleQueue.java │ │ ├── SimpleStack.java │ │ └── UnidirectionalLinkedList.java │ │ ├── map │ │ ├── SimpleHashMap.java │ │ └── User.java │ │ ├── set │ │ └── SimpleSet.java │ │ ├── statistics │ │ └── Analize.java │ │ └── tree │ │ ├── Node.java │ │ ├── SimpleTree.java │ │ └── Tree.java │ └── test │ └── java │ └── ru │ └── job4j │ ├── generic │ ├── AbstractStoreTest.java │ └── SimpleArrayTest.java │ ├── interview │ ├── AnagramTest.java │ └── DBScriptsTest.java │ ├── iterator │ ├── EvenItTest.java │ ├── IteratorOfIteratorsTest.java │ └── JaggedArrayIteratorTest.java │ ├── list │ ├── LinkedListCheckTest.java │ ├── SimpleArrayListTest.java │ ├── SimpleLinkedListTest.java │ ├── SimpleQueueTest.java │ ├── SimpleStackTest.java │ └── UnidirectionalLinkedListTest.java │ ├── map │ ├── SimpleHashMapTest.java │ └── UserTest.java │ ├── set │ └── SimpleSetTest.java │ ├── statistics │ └── AnalizeTest.java │ └── tree │ └── TreeTest.java ├── chapter_006 ├── app.properties ├── pom.xml └── src │ ├── main │ ├── java │ │ └── ru │ │ │ └── job4j │ │ │ └── io │ │ │ ├── Analizy.java │ │ │ ├── Config.java │ │ │ ├── Search.java │ │ │ ├── bot │ │ │ ├── Client.java │ │ │ └── Server.java │ │ │ ├── chat │ │ │ ├── Answer.java │ │ │ ├── ConsoleChat.java │ │ │ └── MainChat.java │ │ │ ├── finder │ │ │ ├── Args.java │ │ │ ├── Finder.java │ │ │ └── MainFinder.java │ │ │ └── zip │ │ │ ├── Args.java │ │ │ ├── MainZip.java │ │ │ └── Zip.java │ └── resources │ │ └── lexicon.txt │ └── test │ └── java │ └── ru │ └── job4j │ └── io │ ├── AnalizyTest.java │ ├── ConfigTest.java │ ├── SearchTest.java │ ├── bot │ ├── ClientTest.java │ └── ServerTest.java │ ├── chat │ └── ConsoleChatTest.java │ ├── finder │ └── FinderTest.java │ └── zip │ └── ZipTest.java ├── chapter_007 ├── db │ ├── master.xml │ └── scripts │ │ ├── update_001.sql │ │ ├── update_002.sql │ │ └── update_003.sql ├── pom.xml └── src │ ├── main │ ├── java │ │ └── ru │ │ │ └── job4j │ │ │ ├── crud │ │ │ ├── ExJob.java │ │ │ ├── Tracker UML.png │ │ │ ├── car_catalog.sql │ │ │ ├── create.sql │ │ │ ├── query.sql │ │ │ └── select_by_company.sql │ │ │ ├── logger │ │ │ └── UsageLog4j2.java │ │ │ ├── magnit │ │ │ ├── Config.java │ │ │ ├── ConvertXSLT.java │ │ │ ├── Entries.java │ │ │ ├── Entry.java │ │ │ ├── MainApp.java │ │ │ ├── ParserXML.java │ │ │ ├── README.md │ │ │ ├── StoreSQL.java │ │ │ ├── StoreXML.java │ │ │ └── process.png │ │ │ └── trackersql │ │ │ └── TrackerSQL.java │ └── resources │ │ ├── app.properties │ │ ├── log4j2.xml │ │ ├── scheme.xslt │ │ ├── sqlite_app.properties │ │ └── structure.sql │ └── test │ └── java │ └── ru │ └── job4j │ ├── magnit │ └── StoreSQLTest.java │ └── trackersql │ ├── ConnectionRollback.java │ └── TrackerSQLTest.java ├── chapter_008 ├── README.md ├── pom.xml └── src │ ├── main │ └── java │ │ └── ru │ │ └── job4j │ │ ├── generator │ │ ├── SimpleGenerator.java │ │ ├── SimpleGeneratorException.java │ │ └── Template.java │ │ ├── interactcalc │ │ ├── Action.java │ │ ├── Calculator.java │ │ ├── ConsoleInput.java │ │ ├── EngineerCalculator.java │ │ ├── Input.java │ │ ├── InteractCalc.java │ │ ├── Option.java │ │ ├── StartCalc.java │ │ └── StubInput.java │ │ ├── menu │ │ ├── CreateMenu.java │ │ ├── ExecuteMenuItem.java │ │ ├── IMenu.java │ │ ├── Menu.java │ │ ├── MenuItem.java │ │ └── ShowMenu.java │ │ ├── tictactoe │ │ ├── InvalidActionException.java │ │ ├── TicTacToe.java │ │ ├── game │ │ │ ├── ConsoleGame.java │ │ │ └── Game.java │ │ ├── logic │ │ │ ├── Cell.java │ │ │ ├── Logic.java │ │ │ └── Logic3T.java │ │ └── player │ │ │ ├── BotSimple.java │ │ │ ├── Player.java │ │ │ └── User.java │ │ └── warehouse │ │ ├── ControlQuality.java │ │ ├── Food.java │ │ ├── Fruits.java │ │ ├── Meat.java │ │ ├── RecyclingFactory.java │ │ ├── Refrigerator.java │ │ ├── Reproduct.java │ │ ├── SecondWarehause.java │ │ ├── Shop.java │ │ ├── Storage.java │ │ ├── StorageDecorator.java │ │ ├── Trash.java │ │ ├── Vegetables.java │ │ ├── VegetablesReproduct.java │ │ └── Warehouse.java │ └── test │ └── java │ └── ru │ └── job4j │ ├── generator │ └── TemplateTest.java │ ├── interactcalc │ └── InteractCalcTest.java │ ├── menu │ └── MenuTest.java │ ├── tictactoe │ ├── BotSimpleTest.java │ ├── ConsoleGameTest.java │ ├── Logic3TTest.java │ └── UserTest.java │ └── warehouse │ └── ControlQualityTest.java ├── chapter_009 ├── pom.xml └── src │ ├── main │ ├── java │ │ └── ru │ │ │ └── job4j │ │ │ └── gc │ │ │ ├── Cache.java │ │ │ ├── GCInfo.java │ │ │ ├── ICache.java │ │ │ ├── MemoryUsage.java │ │ │ └── Tracker Profiling.md │ └── resources │ │ ├── Address.txt │ │ ├── Names.txt │ │ ├── Tracker3.jpg │ │ ├── Tracker4.jpg │ │ ├── log4j2.xml │ │ ├── tracker1.jpg │ │ └── tracker2.jpg │ └── test │ └── java │ └── ru │ └── job4j │ └── gc │ └── CacheTest.java ├── chapter_010 ├── pom.xml └── src │ ├── main │ └── java │ │ └── ru │ │ └── job4j │ │ ├── blockingqueue │ │ ├── ParallelSearch.java │ │ └── SimpleBlockingQueue.java │ │ ├── count │ │ └── Count.java │ │ ├── email │ │ ├── EmailNotification.java │ │ └── User.java │ │ ├── filedownloader │ │ └── HttpDownloader.java │ │ ├── jmm │ │ ├── race │ │ │ ├── ActionOne.java │ │ │ ├── ActionTwo.java │ │ │ └── Counter.java │ │ └── shared │ │ │ └── VolatileDemo.java │ │ ├── nonblockingalgorithm │ │ ├── Base.java │ │ ├── NonBlockCache.java │ │ └── OptimisticException.java │ │ ├── pingpong │ │ ├── PingPong.java │ │ └── RectangleMove.java │ │ ├── pool │ │ ├── TaskExecutor.java │ │ └── ThreadPool.java │ │ ├── threadsafelist │ │ └── ThreadSafeList.java │ │ └── userstorage │ │ ├── User.java │ │ └── UserStorage.java │ └── test │ └── java │ └── ru │ └── job4j │ ├── blockingqueue │ └── SimpleBlockingQueueTest.java │ ├── count │ └── CountTest.java │ ├── nonblockingalgorithm │ └── NonBlockCacheTest.java │ ├── pool │ └── ThreadPoolTest.java │ ├── threadsafelist │ └── ThreadSafeListTest.java │ └── userstorage │ └── UserStorageTest.java ├── chapter_011 ├── README.md ├── db │ ├── master.xml │ └── scripts │ │ ├── update_001.sql │ │ └── update_002.sql ├── pom.xml └── src │ ├── main │ ├── java │ │ └── ru │ │ │ └── job4j │ │ │ ├── crud │ │ │ ├── datamodel │ │ │ │ ├── Role.java │ │ │ │ └── User.java │ │ │ ├── logic │ │ │ │ ├── Validate.java │ │ │ │ ├── ValidateService.java │ │ │ │ └── ValidateStub.java │ │ │ ├── servlet │ │ │ │ ├── AuthenticationFilter.java │ │ │ │ ├── AuthorizationFilter.java │ │ │ │ ├── CityJsonController.java │ │ │ │ ├── DispatchAction.java │ │ │ │ ├── DownloadServlet.java │ │ │ │ ├── SignInController.java │ │ │ │ ├── SignOutController.java │ │ │ │ ├── UploadServlet.java │ │ │ │ ├── UserController.java │ │ │ │ ├── UserCreateServlet.java │ │ │ │ ├── UserDeleteServlet.java │ │ │ │ ├── UserServlet.java │ │ │ │ ├── UserUpdateServlet.java │ │ │ │ ├── UsersController.java │ │ │ │ └── UsersServlet.java │ │ │ └── store │ │ │ │ ├── DBStore.java │ │ │ │ ├── LocationStore.java │ │ │ │ ├── MemoryStore.java │ │ │ │ └── Store.java │ │ │ └── servlets │ │ │ ├── EchoServlet.java │ │ │ ├── JsonServlet.java │ │ │ ├── Person.java │ │ │ └── PersonStorage.java │ ├── resources │ │ ├── app.properties │ │ ├── create.JPG │ │ ├── icon.jpg │ │ ├── signin.JPG │ │ ├── update.JPG │ │ └── usersview.JPG │ └── webapp │ │ ├── WEB-INF │ │ ├── views │ │ │ ├── UserView.jsp │ │ │ ├── UsersView.jsp │ │ │ ├── create.jsp │ │ │ ├── signin.jsp │ │ │ └── update.jsp │ │ └── web.xml │ │ └── index.html │ └── test │ └── java │ └── ru │ └── job4j │ └── crud │ ├── servlet │ ├── AuthenticationFilterTest.java │ ├── AuthorizationFilterTest.java │ ├── DownloadServletTest.java │ ├── SignInControllerTest.java │ ├── SignOutControllerTest.java │ ├── UserControllerTest.java │ ├── UserCreateServletTest.java │ ├── UserDeleteServletTest.java │ ├── UserUpdateServletTest.java │ └── UsersControllerTest.java │ └── store │ ├── ConnectionRollback.java │ ├── DBStoreTest.java │ └── LocationStoreTest.java ├── checkstyle.xml ├── chess ├── pom.xml └── src │ ├── main │ ├── java │ │ └── ru │ │ │ └── job4j │ │ │ └── chess │ │ │ ├── Chess.java │ │ │ ├── Logic.java │ │ │ └── firuges │ │ │ ├── Bishop.java │ │ │ ├── Cell.java │ │ │ ├── Figure.java │ │ │ ├── FigureNotFoundException.java │ │ │ ├── ImpossibleMoveException.java │ │ │ ├── King.java │ │ │ ├── Knight.java │ │ │ ├── OccupiedWayException.java │ │ │ ├── Pawn.java │ │ │ ├── Qeen.java │ │ │ ├── Rook.java │ │ │ ├── black │ │ │ ├── BishopBlack.java │ │ │ ├── KingBlack.java │ │ │ ├── KnightBlack.java │ │ │ ├── PawnBlack.java │ │ │ ├── QeenBlack.java │ │ │ └── RookBlack.java │ │ │ └── white │ │ │ ├── BishopWhite.java │ │ │ ├── KingWhite.java │ │ │ ├── KnightWhite.java │ │ │ ├── PawnWhite.java │ │ │ ├── QeenWhite.java │ │ │ └── RookWhite.java │ └── resources │ │ ├── BishopBlack.png │ │ ├── BishopWhite.png │ │ ├── KingBlack.png │ │ ├── KingWhite.png │ │ ├── KnightBlack.png │ │ ├── KnightWhite.png │ │ ├── PawnBlack.png │ │ ├── PawnWhite.png │ │ ├── QeenBlack.png │ │ ├── QeenWhite.png │ │ ├── RookBlack.png │ │ └── RookWhite.png │ └── test │ └── java │ └── ru │ └── job4j │ └── chess │ └── LogicTest.java ├── cinema ├── README.md ├── db │ ├── master.xml │ └── scripts │ │ ├── update_001.sql │ │ └── update_002.sql ├── pom.xml └── src │ └── main │ ├── java │ └── ru │ │ └── job4j │ │ └── cinema │ │ ├── controller │ │ └── HallController.java │ │ ├── model │ │ ├── Seat.java │ │ └── User.java │ │ ├── persistence │ │ ├── DBStore.java │ │ └── Store.java │ │ └── service │ │ ├── Validate.java │ │ └── ValidateService.java │ ├── resources │ ├── app.properties │ ├── booked.JPG │ └── payment.JPG │ └── webapp │ ├── WEB-INF │ └── web.xml │ ├── index.html │ └── payment.html ├── deploy.sh ├── interview_questions ├── CollectionsLite.md ├── CollectionsPro.md ├── Core.md ├── FPLambdaStreamAPI.md ├── GC.md ├── Hibernate.md ├── IO.md ├── JSPJSTL.md ├── Multithreading.md ├── OOD.md ├── OOP.md ├── README.md ├── SQL.md ├── Servlet.md ├── XML.md ├── pom.xml └── src │ └── main │ ├── java │ └── ru │ │ └── job4j │ │ └── converter │ │ └── Converter.java │ └── resources │ ├── core_1.png │ ├── core_2.png │ ├── gc_4.1.png │ ├── gc_4.2.png │ ├── gc_4.3.png │ ├── gc_6.1.png │ ├── gc_7.1.png │ ├── gc_7.2.png │ ├── gc_7.3.png │ ├── gc_7.4.png │ ├── gc_7.5.png │ ├── gc_7.6.png │ ├── gc_7.7.png │ ├── io_diagram.gif │ ├── isp1.png │ ├── isp2.png │ ├── isp3.png │ ├── lsp1.png │ ├── lsp2.png │ ├── oop_1.png │ ├── oop_2.png │ ├── oop_3.png │ ├── oop_4.png │ ├── pro_1.png │ ├── pro_2.png │ ├── solid.png │ ├── sql1.png │ ├── sql2.png │ ├── sql_joins.png │ ├── srp1.png │ ├── srp2.png │ ├── srp3.png │ └── srp4.png ├── pom.xml ├── puzzle ├── pom.xml └── src │ ├── main │ ├── java │ │ └── ru │ │ │ └── job4j │ │ │ └── puzzle │ │ │ ├── Logic.java │ │ │ ├── Puzzle.java │ │ │ └── firuges │ │ │ ├── Block.java │ │ │ ├── Cell.java │ │ │ ├── Checker.java │ │ │ └── Figure.java │ └── resources │ │ ├── Block.png │ │ └── Checker.png │ └── test │ └── java │ └── ru │ └── job4j │ └── puzzle │ └── LogicTest.java ├── tictactoe ├── pom.xml └── src │ ├── main │ └── java │ │ └── ru │ │ └── job4j │ │ └── tictactoe │ │ ├── Figure3T.java │ │ ├── Logic3T.java │ │ └── TicTacToe.java │ └── test │ └── java │ └── ru │ └── job4j │ └── tictactoe │ └── Logic3TTest.java └── vacancy_parser ├── README.md ├── db ├── master.xml └── scripts │ └── update_001.sql ├── pom.xml └── src ├── main ├── java │ └── ru │ │ └── job4j │ │ └── parser │ │ ├── DBService.java │ │ ├── MainParser.java │ │ ├── ParserJob.java │ │ ├── SqlRuParser.java │ │ └── Vacancy.java └── resources │ ├── app.properties │ └── log4j2.xml └── test └── java └── ru └── job4j └── parser ├── ConnectionRollback.java ├── DBServiceTest.java └── SqlRuParserTest.java /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled class file 2 | *.class 3 | 4 | # Log file 5 | *.log 6 | 7 | # BlueJ files 8 | *.ctxt 9 | 10 | # Mobile Tools for Java (J2ME) 11 | .mtj.tmp/ 12 | 13 | # Package Files # 14 | *.jar 15 | *.war 16 | *.nar 17 | *.ear 18 | *.zip 19 | *.tar.gz 20 | *.rar 21 | 22 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 23 | hs_err_pid* 24 | 25 | .idea 26 | *.iml 27 | *.db 28 | 29 | target -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | # используем язык java. Travis CI поддерживает другие языки тоже. 2 | language: java 3 | 4 | jdk: 5 | - openjdk11 6 | 7 | services: 8 | - postgresql 9 | 10 | before_install: 11 | - psql -c 'create database tracker;' -U postgres 12 | - psql -c 'create database vacancy_parser1;' -U postgres 13 | - psql -c 'create database users1;' -U postgres 14 | - psql -c 'create database cinema;' -U postgres 15 | 16 | # используем режим обычного пользователя для сборки проекта. 17 | sudo: false 18 | 19 | # после выполнения сборки запустить скрипт, который будет собирать статистику по JaCoCo 20 | # Здесь используется сторонни сервис https://codecov.io/ 21 | after_success: 22 | - bash <(curl -s https://codecov.io/bash) 23 | 24 | # Отправлять уведомление на почтуyouremail@smtp.ru(Изменить на свою) если сборка упала 25 | notifications: 26 | email: 27 | recipients: 28 | - johnivo@mail.ru 29 | on_success: never # default: change 30 | on_failure: always # default: always 31 | env: 32 | global: 33 | - CODECOV_TOKEN="75a3c18b-fec3-4c97-8090-34931a4d00a5" -------------------------------------------------------------------------------- /chapter_001/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4.0.0 3 | chapter_001 4 | 2.0 5 | jar 6 | 7 | ru.job4j 8 | junior 9 | 2.0 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /chapter_001/src/main/java/ru/job4j/array/ArrayChar.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.array; 2 | 3 | /** 4 | * Слово начинается с .... 5 | * 6 | *@author John Ivanov (johnivo@mail.ru) 7 | *@version 1 8 | *@since 13.12.2018 9 | */ 10 | public class ArrayChar { 11 | 12 | /** 13 | * Обертка над строкой. 14 | */ 15 | private final char[] data; 16 | 17 | public ArrayChar(String line) { 18 | this.data = line.toCharArray(); 19 | } 20 | 21 | /** 22 | * Метод проверяет, что слово начинается с префикса. 23 | * @param prefix префикс. 24 | * @return true если начинается, иначе false. 25 | */ 26 | public boolean startWith(String prefix) { 27 | boolean result = true; 28 | char[] value = prefix.toCharArray(); 29 | for (int i = 0; i < value.length; i++) { 30 | if (data[i] != value[i]) { 31 | result = false; 32 | break; 33 | } 34 | } 35 | return result; 36 | } 37 | } -------------------------------------------------------------------------------- /chapter_001/src/main/java/ru/job4j/array/ArrayDuplicate.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.array; 2 | 3 | import java.util.Arrays; 4 | 5 | /** 6 | * Удаление дубликатов в массиве. 7 | * 8 | *@author John Ivanov (johnivo@mail.ru) 9 | *@version 1 10 | *@since 17.12.2018 11 | */ 12 | public class ArrayDuplicate { 13 | 14 | /** 15 | * Метод убирает все дубликаты строк из массива. 16 | * 17 | * @param array заданный массив. 18 | * @return массив без дубликатов. 19 | */ 20 | public String[] remove(String[] array) { 21 | int unique = array.length; 22 | for (int out = 0; out < unique; out++) { 23 | for (int in = out + 1; in < unique; in++) { 24 | if (array[out].equals(array[in])) { 25 | array[in] = array[--unique]; 26 | in--; 27 | } 28 | } 29 | } 30 | return Arrays.copyOf(array, unique); 31 | } 32 | } -------------------------------------------------------------------------------- /chapter_001/src/main/java/ru/job4j/array/BubbleSort.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.array; 2 | 3 | /** 4 | * Сортировка массива методом перестановки. 5 | * 6 | *@author John Ivanov (johnivo@mail.ru) 7 | *@version 1 8 | *@since 14.12.2018 9 | */ 10 | public class BubbleSort { 11 | 12 | /** 13 | * Метод упорядочивает массив по алгоритму сортировки пузырьком. 14 | * @param array заданный массив. 15 | * @return отсортированный массив. 16 | */ 17 | public int[] sort(int[] array) { 18 | for (int i = 0; i < array.length; i++) { 19 | for (int j = 1; j < (array.length - i); j++) { 20 | if (array[j] < array[j - 1]) { 21 | int temp = array[j]; 22 | array[j] = array[j - 1]; 23 | array[j - 1] = temp; 24 | } 25 | } 26 | } 27 | return array; 28 | } 29 | } -------------------------------------------------------------------------------- /chapter_001/src/main/java/ru/job4j/array/Check.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.array; 2 | 3 | /** 4 | * Массив заполнен true или false. 5 | * 6 | *@author John Ivanov (johnivo@mail.ru) 7 | *@version 1 8 | *@since 13.12.2018 9 | */ 10 | public class Check { 11 | 12 | /** 13 | * Метод проверяет, что все элементы в массиве являются true или false. 14 | * @param data заданный массив. 15 | * @return true or false. 16 | */ 17 | public boolean mono(boolean[] data) { 18 | boolean result = true; 19 | for (boolean x : data) { 20 | if (x != data[0]) { 21 | result = false; 22 | break; 23 | } 24 | } 25 | return result; 26 | } 27 | } -------------------------------------------------------------------------------- /chapter_001/src/main/java/ru/job4j/array/EndsWith.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.array; 2 | 3 | /** 4 | * Проверить, что слово заканчивается определенной последовательностью. 5 | * 6 | * @author John Ivanov (johnivo@mail.ru) 7 | * @since 16.07.2019 8 | */ 9 | public class EndsWith { 10 | 11 | /** 12 | * Проверяет, что слово заканчивается определенным набором символов. 13 | * @param post заданный набор символов. 14 | * @return true если слово заканчивается данным набором символов. 15 | */ 16 | public boolean endsWith(String word, String post) { 17 | boolean result = true; 18 | char[] pst = post.toCharArray(); 19 | char[] wrd = word.toCharArray(); 20 | int x = wrd.length - pst.length; 21 | for (int i = 0; i < pst.length; i++) { 22 | if (wrd[i + x] != pst[i]) { 23 | result = false; 24 | } 25 | } 26 | return result; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /chapter_001/src/main/java/ru/job4j/array/Matrix.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.array; 2 | 3 | /** 4 | * Таблица умножения. 5 | * 6 | *@author John Ivanov (johnivo@mail.ru) 7 | *@version 1 8 | *@since 14.12.2018 9 | */ 10 | public class Matrix { 11 | 12 | /** 13 | * Метод заполняет таблицу умножения. 14 | * 15 | * @param size размер матрицы. 16 | * @return таблица умножения. 17 | */ 18 | public int[][] multiple(int size) { 19 | int[][] table = new int[size][size]; 20 | for (int i = 0; i < size; i++) { 21 | for (int j = 0; j < size; j++) { 22 | table[i][j] = (i + 1) * (j + 1); 23 | } 24 | } 25 | return table; 26 | } 27 | } -------------------------------------------------------------------------------- /chapter_001/src/main/java/ru/job4j/array/MatrixCheck.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.array; 2 | 3 | /** 4 | * Квадратный массив заполнен true или false по диагоналям. 5 | * 6 | *@author John Ivanov (johnivo@mail.ru) 7 | *@version 1 8 | *@since 15.12.2018 9 | */ 10 | public class MatrixCheck { 11 | 12 | /** 13 | * Метод проверяет массив заполнен true или false по диагоналям. 14 | * 15 | * @param data заданный массив. 16 | * @return true если начинается, иначе false. 17 | */ 18 | public boolean mono(boolean[][] data) { 19 | boolean result = true; 20 | for (int i = 1; i < data.length; i++) { 21 | if (data [0][0] != data[i][i]) { 22 | result = false; 23 | break; 24 | } 25 | if (data[0][data.length - 1] != data[i][data.length - 1 - i]) { 26 | result = false; 27 | break; 28 | } 29 | } 30 | return result; 31 | } 32 | } -------------------------------------------------------------------------------- /chapter_001/src/main/java/ru/job4j/array/Square.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.array; 2 | 3 | /** 4 | * Заполнение массива степенями чисел. 5 | * 6 | *@author John Ivanov (johnivo@mail.ru) 7 | *@version 1 8 | *@since 13.12.2018 9 | */ 10 | public class Square { 11 | 12 | /** 13 | * Метод заполняет массив числами от 1 до bound возведенными в квадрат. 14 | * @param bound длина массива. 15 | * @return массив. 16 | */ 17 | public int[] calculate(int bound) { 18 | int[] rst = new int[bound]; 19 | for (int i = 1; i <= bound; i++) { 20 | rst[i - 1] = i * i; 21 | } 22 | return rst; 23 | } 24 | } -------------------------------------------------------------------------------- /chapter_001/src/main/java/ru/job4j/array/Turn.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.array; 2 | 3 | /** 4 | * Перевернуть массив. 5 | * 6 | *@author John Ivanov (johnivo@mail.ru) 7 | *@version 1 8 | *@since 13.12.2018 9 | */ 10 | public class Turn { 11 | 12 | /** 13 | * Метод переворачивает массив задом наперед. 14 | * @param array заданный массив. 15 | * @return перевернутый массив. 16 | */ 17 | public int[] back(int[] array) { 18 | for (int index = 0; index < (array.length / 2); index++) { 19 | int temp = array[array.length - index - 1]; 20 | array[array.length - index - 1] = array[index]; 21 | array[index] = temp; 22 | } 23 | return array; 24 | } 25 | } -------------------------------------------------------------------------------- /chapter_001/src/main/java/ru/job4j/calculate/Calculate.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.calculate; 2 | 3 | /** 4 | * Calculate. 5 | * 6 | *@author John Ivanov (johnivo@mail.ru) 7 | *@version $ld$ 8 | *@since 01 9 | */ 10 | public class Calculate { 11 | 12 | /** 13 | * Main. 14 | * @param args - args. 15 | */ 16 | public static void main(String[] args) { 17 | System.out.println("Hello World"); 18 | } 19 | 20 | /** 21 | *Method echo. 22 | *@param name Your name. 23 | *@return Echo plus your name. 24 | */ 25 | public String echo(String name) { 26 | return "Echo, echo, echo : " + name; 27 | } 28 | } -------------------------------------------------------------------------------- /chapter_001/src/main/java/ru/job4j/calculate/package-info.java: -------------------------------------------------------------------------------- 1 | /** 2 | *Package for calculate task. 3 | * 4 | *@author John Ivanov (johnivo@mail.ru) 5 | *@version $ld$ 6 | *@since 04.12.2018 7 | */ 8 | package ru.job4j.calculate; -------------------------------------------------------------------------------- /chapter_001/src/main/java/ru/job4j/calculator/Fit.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.calculator; 2 | 3 | /** 4 | * Calculation of the ideal weight. 5 | * 6 | *@author John Ivanov (johnivo@mail.ru) 7 | *@version 1 8 | *@since 08.12.2018 9 | */ 10 | public class Fit { 11 | 12 | /** 13 | * Идеальный вес для мужщины. 14 | * @param height Рост. 15 | * @return идеальный вес. 16 | */ 17 | public double manWeight(double height) { 18 | return (height - 100) * 1.15; 19 | } 20 | 21 | /** 22 | * Идеальный вес для женщины. 23 | * @param height Рост. 24 | * @return идеальный вес. 25 | */ 26 | public double womanWeight(double height) { 27 | return (height - 110) * 1.15; 28 | } 29 | } -------------------------------------------------------------------------------- /chapter_001/src/main/java/ru/job4j/condition/DummyBot.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.condition; 2 | 3 | /** 4 | * Глупый бот. 5 | * 6 | *@author John Ivanov (johnivo@mail.ru) 7 | *@version 1 8 | *@since 10.12.2018 9 | */ 10 | public class DummyBot { 11 | 12 | /** 13 | * Отвечает на вопросы. 14 | * @param question Вопрос от клиента. 15 | * @return Ответ. 16 | */ 17 | public String answer(String question) { 18 | String rsl = "Это ставит меня в тупик. Спросите другой вопрос."; 19 | if ("Привет, Бот.".equals(question)) { 20 | rsl = "Привет, умник."; 21 | } else if ("Пока.".equals(question)) { 22 | rsl = "До скорой встречи."; 23 | } 24 | return rsl; 25 | } 26 | } -------------------------------------------------------------------------------- /chapter_001/src/main/java/ru/job4j/condition/Point.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.condition; 2 | 3 | /** 4 | * Расчет расстояния между двумя точками на плоскости. 5 | * 6 | *@author John Ivanov (johnivo@mail.ru) 7 | *@version 1 8 | *@since 09.12.2018 9 | */ 10 | public class Point { 11 | 12 | /** 13 | * координата по оси x. 14 | */ 15 | private final int x; 16 | /** 17 | * координата по оси y. 18 | */ 19 | private final int y; 20 | 21 | public Point(int x, int y) { 22 | this.x = x; 23 | this.y = y; 24 | } 25 | 26 | /** 27 | * Расчет расстояния между точками A и B. 28 | * @param that - точка B. 29 | * @return - дистанция. 30 | */ 31 | public double distanceTo(Point that) { 32 | return Math.sqrt(Math.pow(this.x - that.x, 2) + Math.pow(this.y - that.y, 2)); 33 | } 34 | 35 | public static void main(String[] args) { 36 | Point a = new Point(0, 1); 37 | Point b = new Point(2, 5); 38 | System.out.println("x1 = " + a.x); 39 | System.out.println("y1 = " + a.y); 40 | System.out.println("x2 = " + b.x); 41 | System.out.println("y2 = " + b.y); 42 | 43 | double result = a.distanceTo(b); 44 | System.out.println("Расстояние между точками A и B : " + result); 45 | } 46 | } -------------------------------------------------------------------------------- /chapter_001/src/main/java/ru/job4j/converter/Converter.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.converter; 2 | 3 | /** 4 | * Converter - currency converter class. 5 | * 6 | *@author John Ivanov (johnivo@mail.ru) 7 | *@version 1 8 | *@since 08.12.2018 9 | */ 10 | public class Converter { 11 | 12 | /** 13 | * euro rate. 14 | */ 15 | private final int euroRate = 76; 16 | 17 | /** 18 | * dollar rate. 19 | */ 20 | private final int dollarRate = 67; 21 | 22 | /** 23 | * Конвертируем рубли в евро. 24 | * @param value рубли. 25 | * @return Евро. 26 | */ 27 | public int rubleToEuro(int value) { 28 | return value / euroRate; 29 | } 30 | 31 | /** 32 | * Конвертируем рубли в доллары. 33 | * @param value рубли. 34 | * @return Доллары. 35 | */ 36 | public int rubleToDollar(int value) { 37 | return value / dollarRate; 38 | } 39 | 40 | /** 41 | * Конвертируем евро в рубли. 42 | * @param value евро. 43 | * @return Рубли. 44 | */ 45 | public int euroToRuble(int value) { 46 | return value * euroRate; 47 | } 48 | 49 | /** 50 | * Конвертируем доллары в рубли. 51 | * @param value доллары. 52 | * @return Рубли. 53 | */ 54 | public int dollarToRuble(int value) { 55 | return value * dollarRate; 56 | } 57 | } -------------------------------------------------------------------------------- /chapter_001/src/main/java/ru/job4j/loop/Board.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.loop; 2 | 3 | /** 4 | * Построение шаматной доски в псевдографике. 5 | * 6 | *@author John Ivanov (johnivo@mail.ru) 7 | *@version 1 8 | *@since 12.12.2018 9 | */ 10 | public class Board { 11 | 12 | /** 13 | * Метод строит шахматную доску из символов x и " " размерностью i*j. 14 | * @param width ширина доски. 15 | * @param height высота доски. 16 | * @return все добавленные в него символы и строки в одну строку. 17 | */ 18 | public String paint(int width, int height) { 19 | StringBuilder screen = new StringBuilder(); 20 | String ln = System.lineSeparator(); 21 | for (int i = 0; i < height; i++) { 22 | for (int j = 0; j < width; j++) { 23 | if ((i + j) % 2 == 0) { 24 | screen.append("x"); 25 | } else { 26 | screen.append(" "); 27 | } 28 | } 29 | screen.append(ln); 30 | } 31 | return screen.toString(); 32 | } 33 | } -------------------------------------------------------------------------------- /chapter_001/src/main/java/ru/job4j/loop/Counter.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.loop; 2 | 3 | /** 4 | * Подсчет суммы чётных чисел в диапазоне. 5 | * 6 | *@author John Ivanov (johnivo@mail.ru) 7 | *@version 1 8 | *@since 11.12.2018 9 | */ 10 | public class Counter { 11 | 12 | /** 13 | * Метод суммирует четные числа в заданном диапазоне. 14 | * @param start начало диапазона. 15 | * @param finish конец диапазона. 16 | * @return сумма. 17 | */ 18 | public int add(int start, int finish) { 19 | int sum = 0; 20 | for (int i = start; i <= finish; i++) { 21 | if (i % 2 == 0) { 22 | sum += i; 23 | } 24 | } 25 | return sum; 26 | } 27 | } -------------------------------------------------------------------------------- /chapter_001/src/main/java/ru/job4j/loop/Factorial.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.loop; 2 | 3 | /** 4 | * Вычисление факториала числа. 5 | * 6 | *@author John Ivanov (johnivo@mail.ru) 7 | *@version 1 8 | *@since 11.12.2018 9 | */ 10 | public class Factorial { 11 | 12 | /** 13 | * Метод находит факториал числа. 14 | * @param n число. 15 | * @return факториал. 16 | */ 17 | public int calc(int n) { 18 | int fact = 1; 19 | for (int i = 1; i <= n; i++) { 20 | fact *= i; 21 | } 22 | return fact; 23 | } 24 | } -------------------------------------------------------------------------------- /chapter_001/src/main/java/ru/job4j/loop/Fitness.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.loop; 2 | 3 | /** 4 | * Протеиновая диета 5 | * В тренажерный зал пришли новые спортсмены - Макс и Ник. 6 | * Они хотят прогрессировать очень быстро и поэтому употребляют много протеина. 7 | * Макс за месяц увеличивает силу тяги в 3 раза за счет такой диеты, а Ник - в 2 раза. 8 | * Макс хочет узнать, сколько месяцев ему нужно тренироваться, чтобы обогнать Ника в тяге. 9 | * 10 | * @author John Ivanov (johnivo@mail.ru) 11 | * @since 16.07.2019 12 | */ 13 | public class Fitness { 14 | 15 | public int calc(int max, int nik) { 16 | int month = 0; 17 | while (max < nik) { 18 | max *= 3; 19 | nik *= 2; 20 | month++; 21 | } 22 | return month; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /chapter_001/src/main/java/ru/job4j/loop/Mortgage.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.loop; 2 | 3 | /** 4 | * Посчитать количество лет необходимых для погашения кредита. 5 | * 6 | * @author John Ivanov (johnivo@mail.ru) 7 | * @since 16.07.2019 8 | */ 9 | public class Mortgage { 10 | 11 | public int year(int amount, int monthly, double percent) { 12 | int year = 0; 13 | while (amount > 0) { 14 | amount = (int) (amount * (1 + percent / 100) - monthly * 12); 15 | year++; 16 | } 17 | return year; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /chapter_001/src/main/java/ru/job4j/loop/PrimeNumber.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.loop; 2 | 3 | /** 4 | * Необходимо посчитать количество простых чисел от 1 до x. 5 | * Простое число, натуральное (целое положительное) число которое делится только на себя и на единицу. 6 | * Напомним, что 1 не является простым числом. 7 | * 8 | * @author John Ivanov (johnivo@mail.ru) 9 | * @since 16.07.2019 10 | */ 11 | public class PrimeNumber { 12 | 13 | public int calc(int finish) { 14 | int count = 0; 15 | int temp = 0; 16 | for (int i = 2; i <= finish; i++) { 17 | for (int j = 1; j <= i; j++) { 18 | if (i % j == 0) { 19 | temp++; 20 | } 21 | } 22 | if (temp == 2) { 23 | count++; 24 | } 25 | temp = 0; 26 | } 27 | return count; 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /chapter_001/src/main/java/ru/job4j/max/Max.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.max; 2 | 3 | /** 4 | * Определение максимального из двух и трех чисел. 5 | * 6 | *@author John Ivanov (johnivo@mail.ru) 7 | *@version 1 8 | *@since 10.12.2018 9 | */ 10 | public class Max { 11 | 12 | /** 13 | * Возвращает максимальное число из двух. 14 | * @param first первое число. 15 | * @param second второе число. 16 | * @return Максимум. 17 | */ 18 | public int max(int first, int second) { 19 | return first > second ? first : second; 20 | } 21 | 22 | /** 23 | * Возвращает максимальное из трех чисел. 24 | * @param first первое число. 25 | * @param second второе число. 26 | * @param third третье число. 27 | * @return Максимум. 28 | */ 29 | public int max(int first, int second, int third) { 30 | return this.max(this.max(first, second), third); 31 | } 32 | } -------------------------------------------------------------------------------- /chapter_001/src/test/java/ru/job4j/array/ArrayCharTest.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.array; 2 | 3 | import org.junit.Test; 4 | import static org.hamcrest.core.Is.is; 5 | import static org.junit.Assert.assertThat; 6 | 7 | 8 | /** 9 | * ArrayCharTest - test class. 10 | * 11 | *@author John Ivanov (johnivo@mail.ru) 12 | *@version 1 13 | *@since 13.12.2018 14 | */ 15 | public class ArrayCharTest { 16 | 17 | /** 18 | * тест проверяет, что слово начинается с префикса "He". 19 | */ 20 | @Test 21 | public void whenStartWithPrefixThenTrue() { 22 | ArrayChar word = new ArrayChar("Hello"); 23 | boolean result = word.startWith("He"); 24 | assertThat(result, is(true)); 25 | } 26 | 27 | /** 28 | * тест проверяет, что слово не начинается с префикса "Hi". 29 | */ 30 | @Test 31 | public void whenNotStartWithPrefixThenFalse() { 32 | ArrayChar word = new ArrayChar("Hello"); 33 | boolean result = word.startWith("Hi"); 34 | assertThat(result, is(false)); 35 | } 36 | } -------------------------------------------------------------------------------- /chapter_001/src/test/java/ru/job4j/array/ArrayMergeTest.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.array; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.hamcrest.core.Is.is; 6 | import static org.junit.Assert.assertThat; 7 | 8 | /** 9 | * ArrayMergeTest - test class. 10 | * 11 | *@author John Ivanov (johnivo@mail.ru) 12 | *@version 1 13 | *@since 14.12.2018 14 | */ 15 | public class ArrayMergeTest { 16 | 17 | /** 18 | * тест проверяет слияние двух отсортированных массивов. 19 | */ 20 | @Test 21 | public void whenMergeFirstArrayWithSecondArrayThenSortedMergedArray() { 22 | int[] inputFirst = {0, 9}; 23 | int[] inputSecond = {3, 4, 7, 8}; 24 | ArrayMerge arraysMerge = new ArrayMerge(); 25 | int[] result = arraysMerge.merging(inputFirst, inputSecond); 26 | int[] expected = new int[]{0, 3, 4, 7, 8, 9}; 27 | assertThat(result, is(expected)); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /chapter_001/src/test/java/ru/job4j/array/BubbleSortTest.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.array; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.hamcrest.core.Is.is; 6 | import static org.junit.Assert.assertThat; 7 | 8 | /** 9 | * BubbleSortTest - test class. 10 | * 11 | *@author John Ivanov (johnivo@mail.ru) 12 | *@version 1 13 | *@since 14.12.2018 14 | */ 15 | public class BubbleSortTest { 16 | 17 | /** 18 | * тест проверяет сортировку массива методом перестановки. 19 | */ 20 | @Test 21 | public void whenSortArrayWithSevenElementsThenSortedArray() { 22 | BubbleSort bubble = new BubbleSort(); 23 | int[] input = new int[]{5, 8, 2, 7, 3, 15, 10}; 24 | int[] result = bubble.sort(input); 25 | int[] expect = new int[]{2, 3, 5, 7, 8, 10, 15}; 26 | assertThat(result, is(expect)); 27 | } 28 | } -------------------------------------------------------------------------------- /chapter_001/src/test/java/ru/job4j/array/CheckTest.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.array; 2 | 3 | import org.junit.Test; 4 | import static org.hamcrest.Matchers.is; 5 | import static org.junit.Assert.assertThat; 6 | 7 | /** 8 | * CheckTest - test class. 9 | * 10 | *@author John Ivanov (johnivo@mail.ru) 11 | *@version 1 12 | *@since 13.12.2018 13 | */ 14 | public class CheckTest { 15 | 16 | /** 17 | * тест проверяет массив с четным числом элементов. 18 | */ 19 | @Test 20 | public void whenDataMonoByTrueThenTrue() { 21 | Check check = new Check(); 22 | boolean[] input = new boolean[] {true, true, true, true}; 23 | boolean result = check.mono(input); 24 | assertThat(result, is(true)); 25 | } 26 | 27 | /** 28 | * тест проверяет массив с нечетным числом элементов. 29 | */ 30 | @Test 31 | public void whenDataNotMonoByTrueThenFalse() { 32 | Check check = new Check(); 33 | boolean[] input = new boolean[] {true, false, true}; 34 | boolean result = check.mono(input); 35 | assertThat(result, is(false)); 36 | } 37 | } -------------------------------------------------------------------------------- /chapter_001/src/test/java/ru/job4j/array/EndsWithTest.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.array; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.hamcrest.Matchers.is; 6 | import static org.junit.Assert.assertThat; 7 | 8 | /** 9 | * @author John Ivanov (johnivo@mail.ru) 10 | * @since 16.07.2019 11 | */ 12 | public class EndsWithTest { 13 | 14 | @Test 15 | public void whenEndsWithThenTrue() { 16 | EndsWith word = new EndsWith(); 17 | boolean result = word.endsWith("Hello", "lo"); 18 | assertThat(result, is(true)); 19 | } 20 | 21 | @Test 22 | public void whenNotEndsWithThenFalse() { 23 | EndsWith word = new EndsWith(); 24 | boolean result = word.endsWith("Hello", "la"); 25 | assertThat(result, is(false)); 26 | } 27 | 28 | @Test 29 | public void whenEndsWithThenTrue2() { 30 | EndsWith word = new EndsWith(); 31 | boolean result = word.endsWith("Madagascar", "gascar"); 32 | assertThat(result, is(true)); 33 | } 34 | 35 | @Test 36 | public void whenNotEndsWithThenFalse2() { 37 | EndsWith word = new EndsWith(); 38 | boolean result = word.endsWith("Madagascar", "gabcar"); 39 | assertThat(result, is(false)); 40 | } 41 | 42 | } -------------------------------------------------------------------------------- /chapter_001/src/test/java/ru/job4j/array/MatrixCheckTest.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.array; 2 | 3 | import org.junit.Test; 4 | import static org.hamcrest.core.Is.is; 5 | import static org.junit.Assert.assertThat; 6 | 7 | /** 8 | * MatrixCheckTest - test class. 9 | * 10 | *@author John Ivanov (johnivo@mail.ru) 11 | *@version 1 12 | *@since 15.12.2018 13 | */ 14 | public class MatrixCheckTest { 15 | 16 | /** 17 | * тест проверяет заполнен ли массив true по диагоналям. 18 | */ 19 | @Test 20 | public void whenDataMonoByTrueThenTrue() { 21 | MatrixCheck check = new MatrixCheck(); 22 | boolean[][] input = new boolean[][] { 23 | {true, true, true}, 24 | {false, true, true}, 25 | {true, false, true} 26 | }; 27 | boolean result = check.mono(input); 28 | assertThat(result, is(true)); 29 | } 30 | 31 | @Test 32 | public void whenDataNotMonoByTrueThenFalse() { 33 | MatrixCheck check = new MatrixCheck(); 34 | boolean[][] input = new boolean[][] { 35 | {true, true, false}, 36 | {false, false, true}, 37 | {true, false, true} 38 | }; 39 | boolean result = check.mono(input); 40 | assertThat(result, is(false)); 41 | } 42 | } -------------------------------------------------------------------------------- /chapter_001/src/test/java/ru/job4j/array/MatrixTest.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.array; 2 | 3 | import org.junit.Test; 4 | import static org.hamcrest.core.Is.is; 5 | import static org.junit.Assert.assertThat; 6 | 7 | /** 8 | * MatrixTest - test class. 9 | * 10 | *@author John Ivanov (johnivo@mail.ru) 11 | *@version 1 12 | *@since 14.12.2018 13 | */ 14 | public class MatrixTest { 15 | 16 | /** 17 | * тест проверяет заполнение таблицы умножения заданного размера. 18 | */ 19 | @Test 20 | public void when3on3() { 21 | Matrix matrix = new Matrix(); 22 | int[][] table = matrix.multiple(3); 23 | int[][] expect = { 24 | {1, 2, 3}, 25 | {2, 4, 6}, 26 | {3, 6, 9} 27 | }; 28 | assertThat(table, is(expect)); 29 | } 30 | } -------------------------------------------------------------------------------- /chapter_001/src/test/java/ru/job4j/array/TurnTest.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.array; 2 | 3 | import org.junit.Test; 4 | import static org.hamcrest.Matchers.is; 5 | import static org.junit.Assert.assertThat; 6 | 7 | /** 8 | * TurnTest - test class. 9 | * 10 | *@author John Ivanov (johnivo@mail.ru) 11 | *@version 1 12 | *@since 13.12.2018 13 | */ 14 | public class TurnTest { 15 | 16 | /** 17 | * тест проверяет переворот массива с четным числом элементов. 18 | */ 19 | @Test 20 | public void whenTurnArrayWithEvenAmountOfElementsThenTurnedArray() { 21 | Turn turner = new Turn(); 22 | int[] input = new int[]{4, 1, 6, 2}; 23 | int[] result = turner.back(input); 24 | int[] expect = new int[]{2, 6, 1, 4}; 25 | assertThat(result, is(expect)); 26 | } 27 | 28 | /** 29 | * тест проверяет переворот массива с нечетным числом элементов. 30 | */ 31 | @Test 32 | public void whenTurnArrayWithOddAmountOfElementsThenTurnedArray() { 33 | Turn turner = new Turn(); 34 | int[] input = new int[]{1, 2, 3, 4, 5}; 35 | int[] result = turner.back(input); 36 | int[] expect = new int[]{5, 4, 3, 2, 1}; 37 | assertThat(result, is(expect)); 38 | for (int x : result) { 39 | System.out.print(x); 40 | System.out.print(", "); 41 | } 42 | System.out.println(); 43 | } 44 | } -------------------------------------------------------------------------------- /chapter_001/src/test/java/ru/job4j/calculate/CalculateTest.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.calculate; 2 | 3 | import org.junit.Test; 4 | import static org.hamcrest.core.Is.is; 5 | import static org.junit.Assert.assertThat; 6 | 7 | /** 8 | * Test. 9 | * 10 | *@author John Ivanov (johnivo@mail.ru) 11 | *@version $ld$ 12 | *@since 01 13 | */ 14 | public class CalculateTest { 15 | 16 | /** 17 | *Test echo. 18 | */ 19 | @Test 20 | public void whenTakeNameThenTreeEchoPlusName() { 21 | String input = "John Ivanov"; 22 | String expect = "Echo, echo, echo : John Ivanov"; 23 | Calculate calc = new Calculate(); 24 | String result = calc.echo(input); 25 | assertThat(result, is(expect)); 26 | } 27 | } -------------------------------------------------------------------------------- /chapter_001/src/test/java/ru/job4j/calculate/package-info.java: -------------------------------------------------------------------------------- 1 | /** 2 | *Package for calculateTest task. 3 | * 4 | *@author John Ivanov (johnivo@mail.ru) 5 | *@version $ld$ 6 | *@since 04.12.2018 7 | */ 8 | package ru.job4j.calculate; -------------------------------------------------------------------------------- /chapter_001/src/test/java/ru/job4j/calculator/FitTest.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.calculator; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.hamcrest.number.IsCloseTo.closeTo; 6 | import static org.junit.Assert.assertThat; 7 | 8 | /** 9 | * FitTest - test class. 10 | * 11 | *@author John Ivanov (johnivo@mail.ru) 12 | *@version 1 13 | *@since 08.12.2018 14 | */ 15 | public class FitTest { 16 | 17 | /** 18 | * man weigh test. 19 | */ 20 | @Test 21 | public void manWeight() { 22 | Fit fit = new Fit(); 23 | double weight = fit.manWeight(180); 24 | assertThat(weight, closeTo(92.0, 0.1)); 25 | } 26 | 27 | /** 28 | * woman weight test. 29 | */ 30 | @Test 31 | public void womanWeight() { 32 | Fit fit = new Fit(); 33 | double weight = fit.womanWeight(170); 34 | assertThat(weight, closeTo(69.0, 0.1)); 35 | } 36 | } -------------------------------------------------------------------------------- /chapter_001/src/test/java/ru/job4j/condition/DummyBotTest.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.condition; 2 | 3 | import org.junit.Test; 4 | import static org.hamcrest.core.Is.is; 5 | import static org.junit.Assert.assertThat; 6 | 7 | /** 8 | * DummyBotTest - class test. 9 | * 10 | *@author John Ivanov (johnivo@mail.ru) 11 | *@version 1 12 | *@since 10.12.2018 13 | */ 14 | public class DummyBotTest { 15 | 16 | /** 17 | * тест приветствия. 18 | */ 19 | @Test 20 | public void whenGreetBot() { 21 | DummyBot bot = new DummyBot(); 22 | assertThat(bot.answer("Привет, Бот."), is("Привет, умник.")); 23 | } 24 | 25 | /** 26 | * тест пока. 27 | */ 28 | @Test 29 | public void whenByuBot() { 30 | DummyBot bot = new DummyBot(); 31 | assertThat(bot.answer("Пока."), is("До скорой встречи.")); 32 | } 33 | 34 | /** 35 | * тест тупика. 36 | */ 37 | @Test 38 | public void whenUnknownBot() { 39 | DummyBot bot = new DummyBot(); 40 | assertThat(bot.answer("Сколько будет 2 + 2?"), is("Это ставит меня в тупик. Спросите другой вопрос.")); 41 | } 42 | } -------------------------------------------------------------------------------- /chapter_001/src/test/java/ru/job4j/condition/PointTest.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.condition; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.hamcrest.number.IsCloseTo.closeTo; 6 | import static org.junit.Assert.assertThat; 7 | 8 | /** 9 | * PointTest - test class. 10 | * 11 | *@author John Ivanov (johnivo@mail.ru) 12 | *@version 1 13 | *@since 09.12.2018 14 | */ 15 | public class PointTest { 16 | 17 | /** 18 | * point test. 19 | */ 20 | @Test 21 | public void distanceTo() { 22 | Point a = new Point(1, 5); 23 | Point b = new Point(4, 3); 24 | double result = a.distanceTo(b); 25 | assertThat(result, closeTo(3.6, 0.1)); 26 | } 27 | } -------------------------------------------------------------------------------- /chapter_001/src/test/java/ru/job4j/loop/BoardTest.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.loop; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.hamcrest.core.Is.is; 6 | import static org.junit.Assert.assertThat; 7 | 8 | /** 9 | * BoardTest - test class. 10 | * 11 | *@author John Ivanov (johnivo@mail.ru) 12 | *@version 1 13 | *@since 12.12.2018 14 | */ 15 | public class BoardTest { 16 | 17 | /** 18 | * тест построения шахматной доски 3*3 в псевдографике. 19 | */ 20 | @Test 21 | public void whenPaintBoardWithWidthThreeAndHeightThreeThenStringWithThreeColsAndThreeRows() { 22 | Board board = new Board(); 23 | String result = board.paint(3, 3); 24 | final String line = System.getProperty("line.separator"); 25 | String expected = String.format("x x%s x %sx x%s", line, line, line); 26 | assertThat(result, is(expected)); 27 | } 28 | 29 | /** 30 | * тест построения шахматной доски 5*4 в псевдографике. 31 | */ 32 | @Test 33 | public void whenPaintBoardWithWidthFiveAndHeightFourThenStringWithFiveColsAndFourRows() { 34 | Board board = new Board(); 35 | String result = board.paint(5, 4); 36 | final String line = System.getProperty("line.separator"); 37 | String expected = String.format("x x x%s x x %sx x x%s x x %s", line, line, line, line); 38 | assertThat(result, is(expected)); 39 | } 40 | } -------------------------------------------------------------------------------- /chapter_001/src/test/java/ru/job4j/loop/CounterTest.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.loop; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.hamcrest.core.Is.is; 6 | import static org.junit.Assert.assertThat; 7 | 8 | /** 9 | * CounterTest - test class. 10 | * 11 | *@author John Ivanov (johnivo@mail.ru) 12 | *@version 1 13 | *@since 11.12.2018 14 | */ 15 | public class CounterTest { 16 | 17 | /** 18 | * тест подсчета суммы четных чисел в диапазоне от 2 до 8. 19 | */ 20 | @Test 21 | public void whenSumEvenNumbersFromTwoToEightThenTwenty() { 22 | Counter sum = new Counter(); 23 | assertThat(sum.add(2, 8), is(20)); 24 | } 25 | 26 | /** 27 | * тест подсчета суммы четных чисел в диапазоне от 2 до 7. 28 | */ 29 | @Test 30 | public void whenSumEvenNumbersFromTwoToSevenThenTwelve() { 31 | Counter sum = new Counter(); 32 | assertThat(sum.add(2, 7), is(12)); 33 | } 34 | 35 | /** 36 | * тест подсчета суммы четных чисел в диапазоне от 0 до 7. 37 | */ 38 | @Test 39 | public void whenSumEvenNumbersFromOneToSevenThenTwelve() { 40 | Counter sum = new Counter(); 41 | assertThat(sum.add(2, 7), is(12)); 42 | } 43 | } -------------------------------------------------------------------------------- /chapter_001/src/test/java/ru/job4j/loop/FactorialTest.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.loop; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.hamcrest.core.Is.is; 6 | import static org.junit.Assert.assertThat; 7 | 8 | /** 9 | * FactorialTest - test class. 10 | * 11 | *@author John Ivanov (johnivo@mail.ru) 12 | *@version 1 13 | *@since 11.12.2018 14 | */ 15 | public class FactorialTest { 16 | 17 | /** 18 | * тест на нахождение факториала 6. 19 | */ 20 | @Test 21 | public void whenCalculateFactorialSixThenSevenHundredTwenty() { 22 | Factorial fact = new Factorial(); 23 | assertThat(fact.calc(6), is(720)); 24 | } 25 | 26 | /** 27 | * тест на нахождение факториала 0. 28 | */ 29 | @Test 30 | public void whenCalculateFactorialZeroThenOne() { 31 | Factorial fact = new Factorial(); 32 | assertThat(fact.calc(0), is(1)); 33 | } 34 | } -------------------------------------------------------------------------------- /chapter_001/src/test/java/ru/job4j/loop/FitnessTest.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.loop; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.hamcrest.Matchers.is; 6 | import static org.junit.Assert.assertThat; 7 | 8 | /** 9 | * @author John Ivanov (johnivo@mail.ru) 10 | * @since 16.07.2019 11 | */ 12 | public class FitnessTest { 13 | 14 | @Test 15 | public void whenMaxGreatNik() { 16 | Fitness fit = new Fitness(); 17 | int days = fit.calc(95, 90); 18 | assertThat(days, is(0)); 19 | } 20 | 21 | @Test 22 | public void whenMaxLessByOneNik() { 23 | Fitness fit = new Fitness(); 24 | int days = fit.calc(90, 95); 25 | assertThat(days, is(1)); 26 | } 27 | 28 | @Test 29 | public void whenMaxLessByFewNik() { 30 | Fitness fit = new Fitness(); 31 | int days = fit.calc(50, 90); 32 | assertThat(days, is(2)); 33 | } 34 | } -------------------------------------------------------------------------------- /chapter_001/src/test/java/ru/job4j/loop/MortgageTest.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.loop; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.hamcrest.Matchers.is; 6 | import static org.junit.Assert.assertThat; 7 | 8 | /** 9 | * @author John Ivanov (johnivo@mail.ru) 10 | * @since 16.07.2019 11 | */ 12 | public class MortgageTest { 13 | 14 | @Test 15 | public void when1Year() { 16 | Mortgage mortgage = new Mortgage(); 17 | int year = mortgage.year(1000, 100, 1); 18 | assertThat(year, is(1)); 19 | } 20 | 21 | @Test 22 | public void when2Year() { 23 | Mortgage mortgage = new Mortgage(); 24 | int year = mortgage.year(100, 10, 50); 25 | assertThat(year, is(2)); 26 | } 27 | 28 | } -------------------------------------------------------------------------------- /chapter_001/src/test/java/ru/job4j/loop/PrimeNumberTest.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.loop; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.hamcrest.Matchers.is; 6 | import static org.junit.Assert.assertThat; 7 | 8 | /** 9 | * @author John Ivanov (johnivo@mail.ru) 10 | * @since 16.07.2019 11 | */ 12 | public class PrimeNumberTest { 13 | 14 | @Test 15 | public void when5() { 16 | PrimeNumber prime = new PrimeNumber(); 17 | int count = prime.calc(5); 18 | assertThat(count, is(3)); 19 | } 20 | 21 | @Test 22 | public void when11() { 23 | PrimeNumber prime = new PrimeNumber(); 24 | int count = prime.calc(11); 25 | assertThat(count, is(5)); 26 | } 27 | 28 | @Test 29 | public void when1() { 30 | PrimeNumber prime = new PrimeNumber(); 31 | int count = prime.calc(2); 32 | assertThat(count, is(1)); 33 | } 34 | } -------------------------------------------------------------------------------- /chapter_001/src/test/java/ru/job4j/max/MaxTest.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.max; 2 | 3 | import org.junit.Test; 4 | import static org.hamcrest.core.Is.is; 5 | import static org.junit.Assert.assertThat; 6 | 7 | /** 8 | * MaxTest - class test. 9 | * 10 | *@author John Ivanov (johnivo@mail.ru) 11 | *@version 1 12 | *@since 10.12.2018 13 | */ 14 | public class MaxTest { 15 | 16 | /** 17 | * тест на поиск максимума из двух чисел. 18 | */ 19 | @Test 20 | public void whenFirstLessSecond() { 21 | Max maxim = new Max(); 22 | assertThat(maxim.max(1, 2), is(2)); 23 | } 24 | 25 | 26 | /** 27 | * тест на поиск максимума из двух равных чисел. 28 | */ 29 | @Test 30 | public void whenFirstEquallySecond() { 31 | Max maxim = new Max(); 32 | assertThat(maxim.max(1, 1), is(1)); 33 | } 34 | 35 | /** 36 | * тест на поиск максимума из трех чисел. 37 | */ 38 | @Test 39 | public void whenFirsMoreSecondAndThird() { 40 | Max maxim = new Max(); 41 | assertThat(maxim.max(2, 5, 9), is(9)); 42 | } 43 | 44 | /** 45 | * тест на поиск максимума из трех равных чисел. 46 | */ 47 | @Test 48 | public void whenFirsEquallySecondAndThird() { 49 | Max maxim = new Max(); 50 | assertThat(maxim.max(2, 2, 2), is(2)); 51 | } 52 | } -------------------------------------------------------------------------------- /chapter_002/src/main/java/ru/job4j/professions/Diagnose.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.professions; 2 | 3 | public class Diagnose { 4 | } -------------------------------------------------------------------------------- /chapter_002/src/main/java/ru/job4j/professions/Doctor.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.professions; 2 | 3 | public class Doctor extends Profession { 4 | final Diagnose diagnose = new Diagnose(); 5 | 6 | public Diagnose heal(Patient patient) { 7 | return diagnose; 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /chapter_002/src/main/java/ru/job4j/professions/Engineer.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.professions; 2 | 3 | public class Engineer extends Profession { 4 | 5 | public House build(House house) { 6 | return house; 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /chapter_002/src/main/java/ru/job4j/professions/House.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.professions; 2 | 3 | public class House { 4 | } -------------------------------------------------------------------------------- /chapter_002/src/main/java/ru/job4j/professions/Patient.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.professions; 2 | 3 | public class Patient { 4 | private String name; 5 | } 6 | -------------------------------------------------------------------------------- /chapter_002/src/main/java/ru/job4j/professions/Profession.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.professions; 2 | 3 | public class Profession { 4 | private String name; 5 | private String profession; 6 | 7 | public Profession() { 8 | } 9 | 10 | public Profession(String name, String profession) { 11 | this.name = name; 12 | this.profession = profession; 13 | } 14 | 15 | public String getName() { 16 | return this.name; 17 | } 18 | 19 | public String getProfession() { 20 | return this.profession; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /chapter_002/src/main/java/ru/job4j/professions/Student.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.professions; 2 | 3 | public class Student { 4 | private String name; 5 | } -------------------------------------------------------------------------------- /chapter_002/src/main/java/ru/job4j/professions/Teacher.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.professions; 2 | 3 | public class Teacher extends Profession { 4 | 5 | public Student teach(Student student) { 6 | return student; 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /chapter_002/src/main/java/ru/job4j/pseudo/Paint.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.pseudo; 2 | 3 | /** 4 | * Paint. 5 | * 6 | *@author John Ivanov (johnivo@mail.ru) 7 | *@version $Id$ 8 | *@since 03.01.2019 9 | */ 10 | public class Paint { 11 | 12 | /** 13 | * Метод выводит на консоль фигуры. 14 | */ 15 | public void draw(Shape shape) { 16 | System.out.println(shape.draw()); 17 | } 18 | 19 | public static void main(String[] args) { 20 | Paint paint = new Paint(); 21 | paint.draw(new Triangle()); 22 | paint.draw(new Square()); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /chapter_002/src/main/java/ru/job4j/pseudo/Shape.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.pseudo; 2 | 3 | /** 4 | * Interface Shape. 5 | * 6 | *@author John Ivanov (johnivo@mail.ru) 7 | *@version $Id$ 8 | *@since 03.01.2019 9 | */ 10 | public interface Shape { 11 | 12 | /** 13 | * Метод формирует строку. 14 | */ 15 | String draw(); 16 | } 17 | -------------------------------------------------------------------------------- /chapter_002/src/main/java/ru/job4j/pseudo/Square.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.pseudo; 2 | 3 | /** 4 | * Square. 5 | * 6 | *@author John Ivanov (johnivo@mail.ru) 7 | *@version $Id$ 8 | *@since 03.01.2019 9 | */ 10 | public class Square implements Shape { 11 | 12 | /** 13 | * Метод формирует строку из символов в виде квадрата. 14 | * @return строка в виде квадрата. 15 | */ 16 | @Override 17 | public String draw() { 18 | StringBuilder pic = new StringBuilder(); 19 | pic.append("++++").append(System.lineSeparator()); 20 | pic.append("+ +").append(System.lineSeparator()); 21 | pic.append("+ +").append(System.lineSeparator()); 22 | pic.append("++++").append(System.lineSeparator()); 23 | return pic.toString(); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /chapter_002/src/main/java/ru/job4j/pseudo/Triangle.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.pseudo; 2 | 3 | /** 4 | * Triangle. 5 | * 6 | *@author John Ivanov (johnivo@mail.ru) 7 | *@version $Id$ 8 | *@since 03.01.2019 9 | */ 10 | public class Triangle implements Shape { 11 | 12 | /** 13 | * Метод формирует строку из символов в виде треугольника. 14 | * @return строка в виде треугольника. 15 | */ 16 | @Override 17 | public String draw() { 18 | StringBuilder pic = new StringBuilder(); 19 | pic.append(" + ").append(System.lineSeparator()); 20 | pic.append(" +++ ").append(System.lineSeparator()); 21 | pic.append("+++++").append(System.lineSeparator()); 22 | return pic.toString(); 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /chapter_002/src/main/java/ru/job4j/tracker/BaseAction.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.tracker; 2 | 3 | 4 | /** 5 | * Абстрактный класс для дублирующихся методов. 6 | * 7 | *@author John Ivanov (johnivo@mail.ru) 8 | *@version $Id$ 9 | *@since 14.01.2019 10 | */ 11 | public abstract class BaseAction implements UserAction { 12 | 13 | /** 14 | * Значение ключа. 15 | */ 16 | private final int key; 17 | 18 | /** 19 | * Наименование действия. 20 | */ 21 | private final String name; 22 | 23 | /** 24 | * Конструтор, инициализирующий поля. 25 | * 26 | * @param key ключ. 27 | * @param name действие. 28 | */ 29 | protected BaseAction(final int key, final String name) { 30 | this.key = key; 31 | this.name = name; 32 | } 33 | 34 | @Override 35 | public int key() { 36 | return this.key; 37 | } 38 | 39 | @Override 40 | public String info() { 41 | return String.format("%s. %s", this.key, this.name); 42 | } 43 | } -------------------------------------------------------------------------------- /chapter_002/src/main/java/ru/job4j/tracker/ConsoleInput.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.tracker; 2 | 3 | import java.util.Scanner; 4 | import java.util.List; 5 | 6 | /** 7 | * Ввод пользовательских данных из консоли. 8 | * 9 | *@author John Ivanov (johnivo@mail.ru) 10 | *@version $Id$ 11 | *@since 01.01.2019 12 | */ 13 | public class ConsoleInput implements Input { 14 | 15 | private final Scanner scanner = new Scanner(System.in); 16 | 17 | @Override 18 | public String ask(String question) { 19 | System.out.print(question); 20 | return scanner.nextLine(); 21 | } 22 | 23 | @Override 24 | public int ask(String question, List range) { 25 | int key = Integer.valueOf(this.ask(question)); 26 | boolean exist = false; 27 | for (int value : range) { 28 | if (value == key) { 29 | exist = true; 30 | break; 31 | } 32 | } 33 | if (!exist) { 34 | throw new MenuOutException("Out of menu range."); 35 | } 36 | return key; 37 | } 38 | } -------------------------------------------------------------------------------- /chapter_002/src/main/java/ru/job4j/tracker/ITracker.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.tracker; 2 | 3 | import java.util.List; 4 | 5 | /** 6 | * @author John Ivanov (johnivo@mail.ru) 7 | * @since 19.06.2019 8 | */ 9 | public interface ITracker { 10 | 11 | Item add(Item item); 12 | 13 | boolean replace(String id, Item item); 14 | 15 | boolean delete(String id); 16 | 17 | List findAll(); 18 | 19 | List findByName(String key); 20 | 21 | Item findById(String id); 22 | } 23 | -------------------------------------------------------------------------------- /chapter_002/src/main/java/ru/job4j/tracker/Input.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.tracker; 2 | 3 | import java.util.List; 4 | 5 | /** 6 | * Interface for ConsoleInput. 7 | * 8 | *@author John Ivanov (johnivo@mail.ru) 9 | *@version $Id$ 10 | *@since 01.01.2019 11 | */ 12 | public interface Input { 13 | 14 | String ask(String question); 15 | 16 | int ask(String question, List range); 17 | } -------------------------------------------------------------------------------- /chapter_002/src/main/java/ru/job4j/tracker/MenuOutException.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.tracker; 2 | 3 | /** 4 | * class MenuOutException. 5 | * 6 | *@author John Ivanov (johnivo@mail.ru) 7 | *@version $Id$ 8 | *@since 10.01.2019 9 | */ 10 | public class MenuOutException extends RuntimeException { 11 | 12 | public MenuOutException(String msg) { 13 | super(msg); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /chapter_002/src/main/java/ru/job4j/tracker/TrackerSingle.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.tracker; 2 | 3 | import java.util.List; 4 | 5 | /** 6 | * Энергичная загрузка (Eager loading) - загружает объект сразу после старта виртуальной машины. 7 | * @author John Ivanov (johnivo@mail.ru) 8 | * @since 22.03.2019 9 | */ 10 | public enum TrackerSingle { 11 | // ключевое слово enum, используется для создания ограниченного количество объектов. 12 | 13 | // здесь мы указываем перечисления. 14 | INSTANCE; 15 | 16 | // Далее конструкторы и методы. 17 | private Tracker tracker = new Tracker(); 18 | 19 | public Item add(Item item) { 20 | return this.tracker.add(item); 21 | } 22 | 23 | public boolean replace(String id, Item item) { 24 | return this.tracker.replace(id, item); 25 | } 26 | 27 | public boolean delete(String id) { 28 | return this.tracker.delete(id); 29 | } 30 | 31 | public List findAll() { 32 | return this.tracker.findAll(); 33 | } 34 | 35 | public List findByName(String nameItem) { 36 | return this.tracker.findByName(nameItem); 37 | } 38 | 39 | public Item findById(String id) { 40 | return this.tracker.findById(id); 41 | } 42 | 43 | //Чтобы получить экземпляр класса нужно напрямую обратиться к полю INSTANCE. 44 | } 45 | -------------------------------------------------------------------------------- /chapter_002/src/main/java/ru/job4j/tracker/TrackerSingleStaticField.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.tracker; 2 | 3 | /** 4 | * Ленивая загрузка (Lazy loading) происходит, когда мы явно обращаемся к объекту. 5 | * @author John Ivanov (johnivo@mail.ru) 6 | * @since 22.03.2019 7 | */ 8 | public class TrackerSingleStaticField { 9 | 10 | // поле instance, которое содержит экземпляр объекта и метод getInstance(). 11 | private static Tracker instance; 12 | 13 | // чтобы закрыть возможность создавать экземпляр класса, 14 | // нужно явно создать конструтор по умолчанию и присвоить ему модификатор private. 15 | private TrackerSingleStaticField() { 16 | } 17 | 18 | // при вызове метод проверяет статическое поле instance, если поле не загружено, оно инициализирует его новосозданном объектом. 19 | public static Tracker getInstance() { 20 | if (instance == null) { 21 | instance = new Tracker(); 22 | } 23 | return instance; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /chapter_002/src/main/java/ru/job4j/tracker/TrackerSingleStaticFinalClass.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.tracker; 2 | 3 | /** 4 | * Ленивая загрузка (Lazy loading) происходит, когда мы явно обращаемся к объекту. 5 | * @author John Ivanov (johnivo@mail.ru) 6 | * @since 22.03.2019 7 | */ 8 | public class TrackerSingleStaticFinalClass { 9 | 10 | private TrackerSingleStaticFinalClass() { 11 | } 12 | 13 | public static Tracker getInstance() { 14 | return Holder.INSTANCE; 15 | } 16 | 17 | // Объект класса находится в поле внутреннего класса. 18 | private static final class Holder { 19 | private static final Tracker INSTANCE = new Tracker(); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /chapter_002/src/main/java/ru/job4j/tracker/TrackerSingleStaticFinalField.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.tracker; 2 | 3 | /** 4 | * Энергичная загрузка (Eager loading) - загружает объект сразу после старта виртуальной машины. 5 | * @author John Ivanov (johnivo@mail.ru) 6 | * @since 22.03.2019 7 | */ 8 | public class TrackerSingleStaticFinalField { 9 | 10 | // Аналогично static field, отличие в том, что сразу создаем и инициализируем объект. 11 | private static final Tracker INSTANCE = new Tracker(); 12 | 13 | private TrackerSingleStaticFinalField() { 14 | } 15 | 16 | public static Tracker getInstance() { 17 | return INSTANCE; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /chapter_002/src/main/java/ru/job4j/tracker/UserAction.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.tracker; 2 | 3 | /** 4 | * Interface UserAction. 5 | * 6 | *@author John Ivanov (johnivo@mail.ru) 7 | *@version $Id$ 8 | *@since 08.01.2019 9 | */ 10 | 11 | public interface UserAction { 12 | 13 | /** 14 | * Метод возвращает ключ опции. 15 | * @return ключ. 16 | */ 17 | int key(); 18 | 19 | /** 20 | * Основной метод. 21 | * @param input объект типа Input. 22 | * @param tracker объект типа Tracker. 23 | */ 24 | void execute(Input input, ITracker tracker); 25 | 26 | /** 27 | * Метод возвращает информацию о данном пункте меню. 28 | * @return Строка меню. 29 | */ 30 | String info(); 31 | } 32 | -------------------------------------------------------------------------------- /chapter_002/src/main/java/ru/job4j/tracker/ValidateInput.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.tracker; 2 | 3 | import java.util.List; 4 | 5 | /** 6 | * Проверка данных, введенных пользователем в консоли. 7 | * 8 | *@author John Ivanov (johnivo@mail.ru) 9 | *@version $Id$ 10 | *@since 10.01.2019 11 | */ 12 | public class ValidateInput implements Input { 13 | 14 | /** 15 | * Реализация композиции. 16 | * Поле содержит источник данных, который описывается интерфейсом Input. 17 | */ 18 | private final Input input; 19 | 20 | public ValidateInput(final Input input) { 21 | this.input = input; 22 | } 23 | 24 | @Override 25 | public String ask(String question) { 26 | return this.input.ask(question); 27 | } 28 | 29 | @Override 30 | public int ask(String question, List range) { 31 | boolean invalid = true; 32 | int value = -1; 33 | do { 34 | try { 35 | value = this.input.ask(question, range); 36 | invalid = false; 37 | } catch (MenuOutException moe) { 38 | System.out.println("Please select key from menu. "); 39 | } catch (NumberFormatException nfe) { 40 | System.out.println("Please enter validate data again. "); 41 | } 42 | } while (invalid); 43 | return value; 44 | } 45 | } -------------------------------------------------------------------------------- /chapter_002/src/main/resources/app.properties: -------------------------------------------------------------------------------- 1 | url=jdbc:postgresql://127.0.0.1:5432/tracker 2 | username=postgres 3 | password=password 4 | driver-class-name=org.postgresql.Driver -------------------------------------------------------------------------------- /chapter_002/src/main/resources/log4j2.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /chapter_002/src/test/java/ru/job4j/pseudo/SquareTest.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.pseudo; 2 | 3 | import org.junit.Test; 4 | import static org.hamcrest.core.Is.is; 5 | import static org.junit.Assert.*; 6 | 7 | /** 8 | * Test class. 9 | * 10 | *@author John Ivanov (johnivo@mail.ru) 11 | *@version $Id$ 12 | *@since 02.01.2019 13 | */ 14 | public class SquareTest { 15 | 16 | /** 17 | * тест SquareTest. 18 | */ 19 | @Test 20 | public void whenDrawSquare() { 21 | Square square = new Square(); 22 | assertThat( 23 | square.draw(), 24 | is(new StringBuilder() 25 | .append("++++").append(System.lineSeparator()) 26 | .append("+ +").append(System.lineSeparator()) 27 | .append("+ +").append(System.lineSeparator()) 28 | .append("++++").append(System.lineSeparator()) 29 | .toString() 30 | ) 31 | ); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /chapter_002/src/test/java/ru/job4j/pseudo/TriangleTest.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.pseudo; 2 | 3 | import org.junit.Test; 4 | import static org.hamcrest.core.Is.is; 5 | import static org.junit.Assert.*; 6 | 7 | /** 8 | * Test class. 9 | * 10 | *@author John Ivanov (johnivo@mail.ru) 11 | *@version $Id$ 12 | *@since 02.01.2019 13 | */ 14 | public class TriangleTest { 15 | 16 | /** 17 | * тест TriangleTest. 18 | */ 19 | @Test 20 | public void whenDrawSquare() { 21 | Triangle triangle = new Triangle(); 22 | System.out.println(triangle.draw()); 23 | assertThat( 24 | triangle.draw(), 25 | is(new StringBuilder() 26 | .append(" + ").append(System.lineSeparator()) 27 | .append(" +++ ").append(System.lineSeparator()) 28 | .append("+++++").append(System.lineSeparator()) 29 | .toString() 30 | ) 31 | ); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /chapter_003/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | junior 7 | ru.job4j 8 | 2.0 9 | 10 | 4.0.0 11 | jar 12 | chapter_003 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /chapter_003/src/main/java/ru/job4j/list/ConvertMatrix2List.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.list; 2 | 3 | import java.util.Arrays; 4 | import java.util.List; 5 | import java.util.ArrayList; 6 | import java.util.stream.Collectors; 7 | import java.util.stream.Stream; 8 | 9 | /** 10 | * 11 | *@author John Ivanov (johnivo@mail.ru) 12 | *@version $Id$ 13 | *@since 27.01.2018 14 | */ 15 | public class ConvertMatrix2List { 16 | 17 | /** 18 | * Метод конверитирует входящий двумерный массив целых чисел в ArrayList. 19 | * Проходя по всем элементам массива и добавляя в List. 20 | * 21 | * @param array входящий массив. 22 | * @return ArrayList. 23 | */ 24 | public List toList(int[][] array) { 25 | List list = new ArrayList<>(); 26 | for (int[] row : array) { 27 | for (Integer column : row) { 28 | list.add(column); 29 | } 30 | } 31 | return list; 32 | } 33 | 34 | public List toList2(Integer[][] array) { 35 | List list = Stream.of(array) 36 | .flatMap(Arrays::stream) 37 | .collect(Collectors.toList()); 38 | return list; 39 | } 40 | 41 | } 42 | -------------------------------------------------------------------------------- /chapter_003/src/main/java/ru/job4j/list/User.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.list; 2 | 3 | /** 4 | * Class User. 5 | * 6 | *@author John Ivanov (johnivo@mail.ru) 7 | *@version $Id$ 8 | *@since 30.01.2018 9 | */ 10 | public class User { 11 | 12 | /** 13 | * Поля: уникальный номер, имя пользователя, город. 14 | */ 15 | private int id; 16 | private String name; 17 | private String city; 18 | 19 | /** 20 | * Конструктор. 21 | * 22 | * @param id уникальный номер. 23 | * @param name имя. 24 | * @param city город. 25 | */ 26 | public User(int id, String name, String city) { 27 | this.id = id; 28 | this.name = name; 29 | this.city = city; 30 | } 31 | 32 | /** 33 | * Геттеры к полям. 34 | */ 35 | public int getId() { 36 | return id; 37 | } 38 | 39 | public String getName() { 40 | return name; 41 | } 42 | 43 | public String getCity() { 44 | return city; 45 | } 46 | } -------------------------------------------------------------------------------- /chapter_003/src/main/java/ru/job4j/list/UserConvert.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.list; 2 | 3 | import java.util.List; 4 | import java.util.HashMap; 5 | import java.util.stream.Collectors; 6 | 7 | /** 8 | * Class UserConvert. 9 | * 10 | *@author John Ivanov (johnivo@mail.ru) 11 | *@version $Id$ 12 | *@since 30.01.2018 13 | */ 14 | public class UserConvert { 15 | 16 | /** 17 | * Метод конверитирует входящий List в Map. 18 | * Метод принимает список пользователей и конвертирует его в Map с ключом Integer id и соответствующим ему User. 19 | * 20 | * @param list входящий список пользователей типа List. 21 | * @return hm типа HashMap. 22 | */ 23 | public HashMap process(List list) { 24 | HashMap map = new HashMap<>(); 25 | //for (User user : list) { 26 | // maps.put(user.getId(), user); 27 | //} 28 | map = (HashMap) list 29 | .stream() 30 | .collect(Collectors.toMap(User::getId, e -> e) 31 | ); 32 | return map; 33 | } 34 | } -------------------------------------------------------------------------------- /chapter_003/src/main/java/ru/job4j/search/Person.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.search; 2 | 3 | /** 4 | * Class Person. 5 | * 6 | *@author John Ivanov (johnivo@mail.ru) 7 | *@version $Id$ 8 | *@since 24.01.2018 9 | */ 10 | public class Person { 11 | 12 | /** 13 | * Поля: имя, фамилия, адрес, номер телефона, адрес. 14 | */ 15 | private String name; 16 | private String surname; 17 | private String phone; 18 | private String address; 19 | 20 | /** 21 | * Конструктор. 22 | */ 23 | public Person(String name, String surname, String phone, String address) { 24 | this.name = name; 25 | this.surname = surname; 26 | this.phone = phone; 27 | this.address = address; 28 | } 29 | 30 | /** 31 | * Геттеры к полям. 32 | */ 33 | public String getName() { 34 | return name; 35 | } 36 | 37 | public String getSurname() { 38 | return surname; 39 | } 40 | 41 | public String getPhone() { 42 | return phone; 43 | } 44 | 45 | public String getAddress() { 46 | return address; 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /chapter_003/src/main/java/ru/job4j/search/PriorityQueue.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.search; 2 | 3 | import java.util.LinkedList; 4 | 5 | /** 6 | * 7 | *@author John Ivanov (johnivo@mail.ru) 8 | *@version $Id$ 9 | *@since 25.01.2018 10 | */ 11 | public class PriorityQueue { 12 | private LinkedList tasks = new LinkedList<>(); 13 | 14 | /** 15 | * Метод должен вставлять в нужную позицию элемент. 16 | * Позиция определять по полю приоритет. 17 | * Для вставик использовать add(int index, E value) 18 | * @param task задача 19 | */ 20 | public void put(Task task) { 21 | 22 | //TODO добавить вставку в связанный список. 23 | //int i = 0; 24 | // или var i = 0; 25 | //for (Task t : tasks) { 26 | // или for (var t : tasks) { 27 | // if (t.getPriority() < task.getPriority()) { 28 | // i++; 29 | // } 30 | //} 31 | var i = (int) tasks.stream() 32 | .filter( 33 | e -> e.getPriority() < task.getPriority() 34 | ).count(); 35 | this.tasks.add(i, task); 36 | } 37 | 38 | public Task take() { 39 | tasks.stream() 40 | .map(Task::getPriority) 41 | .forEach(System.out::println); 42 | return this.tasks.poll(); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /chapter_003/src/main/java/ru/job4j/search/Task.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.search; 2 | 3 | /** 4 | * 5 | *@author John Ivanov (johnivo@mail.ru) 6 | *@version $Id$ 7 | *@since 25.01.2018 8 | */ 9 | public class Task { 10 | private String desc; 11 | private int priority; 12 | 13 | public Task(String desc, int priority) { 14 | this.desc = desc; 15 | this.priority = priority; 16 | } 17 | 18 | public String getDesc() { 19 | return desc; 20 | } 21 | 22 | public int getPriority() { 23 | return priority; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /chapter_003/src/main/java/ru/job4j/sort/User.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.sort; 2 | 3 | /** 4 | * Class User. 5 | * 6 | * @author John Ivanov (johnivo@mail.ru) 7 | * @version $Id$ 8 | * @since 02.02.2018 9 | */ 10 | public class User implements Comparable { 11 | 12 | /** 13 | * Поля: имя, возраст. 14 | */ 15 | private String name; 16 | private int age; 17 | 18 | /** 19 | * Конструктор. 20 | * 21 | * @param name имя. 22 | * @param age возраст. 23 | */ 24 | public User(String name, int age) { 25 | this.name = name; 26 | this.age = age; 27 | } 28 | 29 | @Override 30 | public String toString() { 31 | return new StringBuilder() 32 | .append("name ") 33 | .append(name) 34 | .append(" age ") 35 | .append(age) 36 | .toString(); 37 | } 38 | 39 | /** 40 | * Геттеры к полям. 41 | */ 42 | public String getName() { 43 | return this.name; 44 | } 45 | 46 | public int getAge() { 47 | return this.age; 48 | } 49 | 50 | @Override 51 | public int compareTo(User o) { 52 | return Integer.valueOf(this.age).compareTo(o.age); 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /chapter_003/src/test/java/ru/job4j/search/PriorityQueueTest.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.search; 2 | 3 | import org.junit.Test; 4 | import static org.hamcrest.core.Is.is; 5 | import static org.junit.Assert.assertThat; 6 | 7 | /** 8 | * Test class. 9 | * 10 | *@author John Ivanov (johnivo@mail.ru) 11 | *@version $Id$ 12 | *@since 25.01.2019 13 | */ 14 | public class PriorityQueueTest { 15 | 16 | /** 17 | * Test find by name. 18 | */ 19 | @Test 20 | public void whenHigherPriority() { 21 | var queue = new PriorityQueue(); 22 | queue.put(new Task("low", 5)); 23 | queue.put(new Task("urgent", 1)); 24 | queue.put(new Task("middle", 3)); 25 | var result = queue.take(); 26 | assertThat(result.getDesc(), is("urgent")); 27 | } 28 | 29 | @Test 30 | public void whenHigherPriority2() { 31 | var queue = new PriorityQueue(); 32 | queue.put(new Task("middle", 3)); 33 | queue.put(new Task("low", 5)); 34 | queue.put(new Task("urgent", 1)); 35 | //Task result = queue.take(); 36 | var result = queue.take(); 37 | assertThat(result.getDesc(), is("urgent")); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /chapter_004/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | junior 7 | ru.job4j 8 | 2.0 9 | 10 | 4.0.0 11 | jar 12 | chapter_004 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /chapter_004/src/main/java/ru/job4j/diapason/Diapason.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.diapason; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | import java.util.function.Function; 7 | 8 | /** 9 | * Подсчет функции в диапазоне. 10 | * 11 | * @author John Ivanov (johnivo@mail.ru) 12 | * @version $Id$ 13 | * @since 28.02.2018 14 | */ 15 | public class Diapason { 16 | public List diapason(int start, int end, Function func) { 17 | List range = new ArrayList<>(); 18 | for (int index = start; index != end; index++) { 19 | range.add(func.apply((double) index)); 20 | } 21 | return range; 22 | } 23 | } -------------------------------------------------------------------------------- /chapter_004/src/main/java/ru/job4j/lambda/Calculator.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.lambda; 2 | 3 | import java.util.function.BiFunction; 4 | import java.util.function.Consumer; 5 | 6 | public class Calculator { 7 | public void multiple(int start, int finish, int value, 8 | BiFunction op, 9 | Consumer media) { 10 | for (int index = start; index != finish; index++) { 11 | media.accept(op.apply(value, index)); 12 | } 13 | } 14 | 15 | public static void main(String[] args) { 16 | Calculator calc = new Calculator(); 17 | calc.multiple( 18 | 0, 10, 2, 19 | /**(value, index) -> { 20 | double result = value * index; 21 | System.out.printf("Multiple %s * %s = %s %n", value, index, result); 22 | return result; 23 | },*/ 24 | MathUtil::add, 25 | result -> System.out.println(result) 26 | ); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /chapter_004/src/main/java/ru/job4j/lambda/MathUtil.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.lambda; 2 | 3 | public class MathUtil { 4 | public static double add(int left, int second) { 5 | return left + second; 6 | } 7 | 8 | public static double div(int left, int second) { 9 | return left / second; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /chapter_004/src/main/java/ru/job4j/matrix/MatrixToList.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.matrix; 2 | 3 | import java.util.Arrays; 4 | import java.util.List; 5 | import java.util.stream.Collectors; 6 | import java.util.stream.Stream; 7 | 8 | /** 9 | * @author John Ivanov (johnivo@mail.ru) 10 | * @since 07.03.2019 11 | */ 12 | public class MatrixToList { 13 | 14 | public List matrixToList(Integer[][] matrix) { 15 | List list = Stream.of(matrix) 16 | //.flatMap(e -> Stream.of(e)) 17 | .flatMap(Arrays::stream) 18 | .collect(Collectors.toList()); 19 | list.forEach(System.out::print); 20 | return list; 21 | } 22 | 23 | public List listsToList(List> matrix) { 24 | List list = matrix.stream() 25 | //.flatMap(e -> e.stream()) 26 | .flatMap(List::stream) 27 | .collect(Collectors.toList()); 28 | list.forEach(System.out::print); 29 | return list; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /chapter_004/src/main/java/ru/job4j/profiles/Profile.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.profiles; 2 | 3 | /** 4 | * @author John Ivanov (johnivo@mail.ru) 5 | * @since 05.03.2019 6 | */ 7 | public class Profile { 8 | 9 | private Address address; 10 | 11 | public Profile(Address address) { 12 | this.address = address; 13 | } 14 | 15 | public Address getAddress() { 16 | return address; 17 | } 18 | 19 | } 20 | -------------------------------------------------------------------------------- /chapter_004/src/main/java/ru/job4j/profiles/Profiles.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.profiles; 2 | 3 | import java.util.Comparator; 4 | import java.util.List; 5 | import java.util.stream.Collectors; 6 | 7 | /** 8 | * @author John Ivanov (johnivo@mail.ru) 9 | * @since 05.03.2019 10 | */ 11 | public class Profiles { 12 | 13 | List
collect(List profiles) { 14 | List
list = profiles.stream() 15 | .map(Profile::getAddress) 16 | .sorted(Comparator.comparing(Address::getCity)) 17 | .distinct().collect(Collectors.toList()); 18 | list.forEach(System.out::println); 19 | return list; 20 | } 21 | } 22 | //ссылки на метод вместо лямбд 23 | //.map(profile -> profile.getAddress()) 24 | //.sorted(Comparator.comparing(add -> add.getCity())) 25 | // 26 | //.sorted(new Comparator
() { 27 | // @Override 28 | // public int compare(Address o1, Address o2) { 29 | // return o1.getCity().compareTo(o2.getCity()); 30 | // } 31 | // } 32 | //) -------------------------------------------------------------------------------- /chapter_004/src/main/java/ru/job4j/school/Student.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.school; 2 | 3 | /** 4 | * Student. 5 | * 6 | *@author John Ivanov (johnivo@mail.ru) 7 | *@version $Id$ 8 | *@since 02.03.2019 9 | */ 10 | public class Student { 11 | 12 | private String lastName; 13 | private int score; 14 | 15 | public Student(String lastName, int score) { 16 | this.lastName = lastName; 17 | this.score = score; 18 | } 19 | 20 | public String getLastName() { 21 | return lastName; 22 | } 23 | 24 | public int getScore() { 25 | return score; 26 | } 27 | 28 | @Override 29 | public String toString() { 30 | return "Student{" + "lastName='" + lastName + '\'' + ", score=" + score + '}'; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /chapter_004/src/main/java/ru/job4j/stream/ArrayProcessing.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.stream; 2 | 3 | import java.util.Arrays; 4 | 5 | /** 6 | * @author John Ivanov (johnivo@mail.ru) 7 | * @since 27.03.2019 8 | */ 9 | public class ArrayProcessing { 10 | 11 | public int processing(int[] array) { 12 | int result = Arrays.stream(array) 13 | .filter(e -> e % 2 == 0) 14 | .reduce(0, (acc, e) -> acc + e * e); 15 | return result; 16 | } 17 | 18 | public static int processing2(int[] array) { 19 | int result = Arrays.stream(array) 20 | .filter(e -> e % 2 == 0) 21 | .map(e -> e * e) 22 | .sum(); 23 | return result; 24 | } 25 | } -------------------------------------------------------------------------------- /chapter_004/src/test/java/ru/job4j/lambda/CalculatorTest.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.lambda; 2 | 3 | import org.junit.Test; 4 | import java.util.ArrayList; 5 | import java.util.Arrays; 6 | import java.util.List; 7 | import static org.hamcrest.Matchers.is; 8 | import static org.junit.Assert.assertThat; 9 | 10 | public class CalculatorTest { 11 | @Test 12 | public void whenAdd1Until3() { 13 | Calculator calc = new Calculator(); 14 | List buffer = new ArrayList<>(); 15 | calc.multiple( 16 | 0, 3, 1, 17 | //(value, index) -> (double) value + index, 18 | //result -> buffer.add(result) 19 | MathUtil::add, //static call 20 | buffer::add // non-static call 21 | ); 22 | assertThat(buffer, is(Arrays.asList(1D, 2D, 3D))); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /chapter_004/src/test/java/ru/job4j/matrix/MatrixToListTest.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.matrix; 2 | 3 | import org.junit.Test; 4 | 5 | import java.util.Arrays; 6 | import java.util.List; 7 | 8 | import static org.hamcrest.core.Is.is; 9 | import static org.junit.Assert.assertThat; 10 | 11 | /** 12 | * @author John Ivanov (johnivo@mail.ru) 13 | * @since 07.03.2019 14 | */ 15 | public class MatrixToListTest { 16 | 17 | @Test 18 | public void whenMatrixConvertToList() { 19 | Integer[][] matrix = {{1, 2}, {3, 4}}; 20 | MatrixToList list = new MatrixToList(); 21 | int result = list.matrixToList(matrix).size(); 22 | assertThat(result, is(4)); 23 | } 24 | 25 | @Test 26 | public void whenListsConvertToList() { 27 | List> matrix = Arrays.asList( 28 | Arrays.asList(1, 2), 29 | Arrays.asList(3, 4) 30 | ); 31 | MatrixToList list = new MatrixToList(); 32 | int result = list.listsToList(matrix).size(); 33 | assertThat(result, is(4)); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /chapter_004/src/test/java/ru/job4j/stream/ArrayProcessingTest.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.stream; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.hamcrest.core.Is.is; 6 | import static org.junit.Assert.assertThat; 7 | import static ru.job4j.stream.ArrayProcessing.processing2; 8 | 9 | /** 10 | * @author John Ivanov (johnivo@mail.ru) 11 | * @since 27.03.2019 12 | */ 13 | public class ArrayProcessingTest { 14 | 15 | @Test 16 | public void whenUseProcessingOfArray() { 17 | var a = new ArrayProcessing(); 18 | int[] arr = {5, 2, 1, 10, 2}; 19 | int result = a.processing(arr); 20 | assertThat(result, is(108)); 21 | } 22 | 23 | @Test 24 | public void whenUseSecondProcessingOfArray() { 25 | int[] arr = {5, 0, 2, 4}; 26 | int result = processing2(arr); 27 | assertThat(result, is(20)); 28 | } 29 | } -------------------------------------------------------------------------------- /chapter_005/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | junior 7 | ru.job4j 8 | 2.0 9 | 10 | 4.0.0 11 | 12 | chapter_005 13 | 14 | 15 | -------------------------------------------------------------------------------- /chapter_005/src/main/java/ru/job4j/generic/Base.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.generic; 2 | 3 | /** 4 | * @author John Ivanov (johnivo@mail.ru) 5 | * @since 08.04.2019 6 | */ 7 | public abstract class Base { 8 | 9 | private final String id; 10 | 11 | protected Base(final String id) { 12 | this.id = id; 13 | } 14 | 15 | public String getId() { 16 | return id; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /chapter_005/src/main/java/ru/job4j/generic/Role.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.generic; 2 | 3 | /** 4 | * @author John Ivanov (johnivo@mail.ru) 5 | * @since 08.04.2019 6 | */ 7 | public class Role extends Base { 8 | 9 | protected Role(String id) { 10 | super(id); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /chapter_005/src/main/java/ru/job4j/generic/RoleStore.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.generic; 2 | 3 | /** 4 | * @author John Ivanov (johnivo@mail.ru) 5 | * @since 08.04.2019 6 | */ 7 | public class RoleStore extends AbstractStore { 8 | 9 | public RoleStore(int size) { 10 | super(size); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /chapter_005/src/main/java/ru/job4j/generic/Store.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.generic; 2 | 3 | /** 4 | * @author John Ivanov (johnivo@mail.ru) 5 | * @since 08.04.2019 6 | */ 7 | public interface Store { 8 | 9 | void add(T model); 10 | 11 | boolean replace(String id, T model); 12 | 13 | boolean delete(String id); 14 | 15 | T findById(String id); 16 | } 17 | -------------------------------------------------------------------------------- /chapter_005/src/main/java/ru/job4j/generic/User.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.generic; 2 | 3 | /** 4 | * @author John Ivanov (johnivo@mail.ru) 5 | * @since 08.04.2019 6 | */ 7 | public class User extends Base { 8 | 9 | protected User(String id) { 10 | super(id); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /chapter_005/src/main/java/ru/job4j/generic/UserStore.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.generic; 2 | 3 | /** 4 | * @author John Ivanov (johnivo@mail.ru) 5 | * @since 08.04.2019 6 | */ 7 | public class UserStore extends AbstractStore { 8 | 9 | public UserStore(int size) { 10 | super(size); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /chapter_005/src/main/java/ru/job4j/interview/VulnerabilityScript.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.interview; 2 | 3 | import java.util.List; 4 | 5 | /** 6 | * The script representation 7 | * 8 | * @author John Ivanov (johnivo@mail.ru) 9 | * @since 29.04.2019 10 | */ 11 | public class VulnerabilityScript { 12 | 13 | private final int scriptId; 14 | 15 | private final List dependencies; 16 | 17 | public VulnerabilityScript(int scriptId, List dependencies) { 18 | this.scriptId = scriptId; 19 | this.dependencies = dependencies; 20 | } 21 | 22 | public int getScriptId() { 23 | return scriptId; 24 | } 25 | 26 | public List getDependencies() { 27 | return dependencies; 28 | } 29 | 30 | @Override 31 | public String toString() { 32 | return "VulnerabilityScript{" + "dependencies=" + dependencies + '}'; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /chapter_005/src/main/java/ru/job4j/iterator/EvenIt.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.iterator; 2 | 3 | import java.util.Iterator; 4 | import java.util.NoSuchElementException; 5 | 6 | /** 7 | * @author John Ivanov (johnivo@mail.ru) 8 | * @since 29.03.2019 9 | */ 10 | public class EvenIt implements Iterator { 11 | 12 | private final int[] numbers; 13 | private int index; 14 | 15 | public EvenIt(final int[] num) { 16 | this.numbers = num; 17 | } 18 | 19 | @Override 20 | public boolean hasNext() { 21 | boolean rst = false; 22 | for (int i = index; i < numbers.length; i++) { 23 | if (numbers[i] % 2 == 0) { 24 | index = i; 25 | rst = true; 26 | break; 27 | } 28 | } 29 | return rst; 30 | } 31 | 32 | @Override 33 | public Object next() { 34 | if (!hasNext()) { 35 | throw new NoSuchElementException(); 36 | } 37 | return numbers[index++]; 38 | } 39 | } -------------------------------------------------------------------------------- /chapter_005/src/main/java/ru/job4j/iterator/JaggedArrayIterator.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.iterator; 2 | 3 | import java.util.Iterator; 4 | 5 | /** 6 | * @author John Ivanov (johnivo@mail.ru) 7 | * @since 28.03.2019 8 | */ 9 | public class JaggedArrayIterator implements Iterator { 10 | 11 | private final int[][] values; 12 | private int row = 0; 13 | private int column = 0; 14 | 15 | public JaggedArrayIterator(final int[][] values) { 16 | this.values = values; 17 | } 18 | 19 | @Override 20 | public boolean hasNext() { 21 | return values.length > row && values[row].length > column; 22 | } 23 | 24 | @Override 25 | public Object next() { 26 | int result = values[row][column++]; 27 | if (column == values[row].length) { 28 | column = 0; 29 | row++; 30 | } 31 | return result; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /chapter_005/src/main/java/ru/job4j/list/BaseList.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.list; 2 | 3 | /** 4 | * @author John Ivanov (johnivo@mail.ru) 5 | * @since 16.10.2019 6 | */ 7 | public interface BaseList extends Iterable { 8 | 9 | boolean add(E value); 10 | 11 | E get(int index); 12 | 13 | E[] grow(); 14 | 15 | 16 | 17 | } 18 | -------------------------------------------------------------------------------- /chapter_005/src/main/java/ru/job4j/list/LinkedListCheck.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.list; 2 | 3 | /** 4 | * Класс определяет цикличность в связанном списке. 5 | * Для поиска цикла использован алгоритм Флойда "Черепаха и заяц". 6 | * 7 | * @author John Ivanov (johnivo@mail.ru) 8 | * @since 13.04.2019 9 | */ 10 | public class LinkedListCheck { 11 | 12 | /** 13 | * Метод определяет наличие цикличности в связном списке. 14 | * 15 | * @param first head-элемент списка. 16 | * @return true, если есть замыкание. 17 | */ 18 | public boolean hasCycle(Node first) { 19 | Node slow = first; 20 | Node fast = first; 21 | boolean result = false; 22 | while (fast != null && fast.next != null) { 23 | slow = slow.next; 24 | fast = fast.next.next; 25 | if (slow == fast) { 26 | result = true; 27 | break; 28 | } 29 | } 30 | return result; 31 | } 32 | } 33 | 34 | /** 35 | * Элементарная реализация связанного списка. 36 | */ 37 | class Node { 38 | E value; 39 | Node next; 40 | 41 | public Node(E value) { 42 | this.value = value; 43 | } 44 | } 45 | 46 | -------------------------------------------------------------------------------- /chapter_005/src/main/java/ru/job4j/list/SimpleStack.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.list; 2 | 3 | /** 4 | * Динамический контейнер типа Stack на базе связанного списка. 5 | * LIFO - last input first output. 6 | * 7 | * @author John Ivanov (johnivo@mail.ru) 8 | * @since 12.04.2019 9 | */ 10 | public class SimpleStack { 11 | 12 | /** 13 | * Используем функциональные возможности класса UnidirectionalLinkedList. 14 | * Представляющем реализацию односвязнного списка. 15 | */ 16 | private UnidirectionalLinkedList linkedList = new UnidirectionalLinkedList(); 17 | 18 | /** 19 | * Возвращает верхний элемент стека, удаляя его из коллекции. 20 | * 21 | * @return верхний элемент (null, при пустом стеке). 22 | */ 23 | public E poll() { 24 | // int lastIndex = linkedList.getSize() - 1; 25 | // E result = linkedList.get(lastIndex); 26 | // linkedList.delete(); 27 | // return result; 28 | return linkedList.delete(); 29 | } 30 | 31 | /** 32 | * Добавляет в начало стека новый элемент. 33 | * 34 | * @param value добавляемое значение. 35 | */ 36 | public void push(E value) { 37 | linkedList.add(value); 38 | } 39 | 40 | /** 41 | * Вспомогательный метод, получает размер стека. 42 | */ 43 | public int size() { 44 | return linkedList.getSize(); 45 | } 46 | 47 | } 48 | -------------------------------------------------------------------------------- /chapter_005/src/main/java/ru/job4j/tree/Node.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.tree; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | /** 7 | * @author John Ivanov (johnivo@mail.ru) 8 | * @since 21.04.2019 9 | */ 10 | public class Node> { 11 | 12 | private final List> children = new ArrayList<>(); 13 | 14 | private final E value; 15 | 16 | public Node(final E value) { 17 | this.value = value; 18 | } 19 | 20 | public void add(Node child) { 21 | this.children.add(child); 22 | } 23 | 24 | public List> leaves() { 25 | return this.children; 26 | } 27 | 28 | public boolean eqValue(E that) { 29 | return this.value.compareTo(that) == 0; 30 | } 31 | 32 | public E getValue() { 33 | return value; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /chapter_005/src/main/java/ru/job4j/tree/SimpleTree.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.tree; 2 | 3 | import java.util.Optional; 4 | 5 | /** 6 | * @author John Ivanov (johnivo@mail.ru) 7 | * @since 21.04.2019 8 | */ 9 | public interface SimpleTree> extends Iterable { 10 | 11 | /** 12 | * Добавить элемент child в parent. 13 | * Parent может иметь список child. 14 | * @param parent parent. 15 | * @param child child. 16 | * @return 17 | */ 18 | boolean add(E parent, E child); 19 | 20 | Optional> findBy(E value); 21 | 22 | } 23 | -------------------------------------------------------------------------------- /chapter_005/src/test/java/ru/job4j/interview/AnagramTest.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.interview; 2 | 3 | import org.junit.Assert; 4 | import org.junit.Test; 5 | 6 | import java.util.*; 7 | 8 | import static org.hamcrest.MatcherAssert.assertThat; 9 | import static org.hamcrest.Matchers.is; 10 | import static org.junit.Assert.*; 11 | 12 | /** 13 | * @author John Ivanov (johnivo@mail.ru) 14 | * @since 30.04.2019 15 | */ 16 | public class AnagramTest { 17 | 18 | @Test 19 | public void isAnagramTest() { 20 | Anagram anagram = new Anagram(); 21 | assertThat(anagram.check("мама", "амма"), is(true)); 22 | assertThat(anagram.check("мама", "мааа"), is(false)); 23 | assertThat(anagram.check(null, "мама"), is(false)); 24 | assertThat(anagram.check("мама", null), is(false)); 25 | assertThat(anagram.check(null, null), is(true)); 26 | assertThat(anagram.check("", ""), is(true)); 27 | assertThat(anagram.check("my anagram.", "my .nagaram"), is(true)); 28 | } 29 | } -------------------------------------------------------------------------------- /chapter_005/src/test/java/ru/job4j/list/LinkedListCheckTest.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.list; 2 | 3 | import org.junit.Before; 4 | import org.junit.Test; 5 | 6 | import static org.hamcrest.MatcherAssert.assertThat; 7 | import static org.hamcrest.Matchers.is; 8 | 9 | /** 10 | * @author John Ivanov (johnivo@mail.ru) 11 | * @since 13.04.2019 12 | */ 13 | public class LinkedListCheckTest { 14 | 15 | private LinkedListCheck checker = new LinkedListCheck(); 16 | private Node first; 17 | private Node second; 18 | private Node third; 19 | 20 | @Before 21 | public void notCycled() { 22 | first = new Node<>(1); 23 | second = new Node<>(2); 24 | third = new Node<>(5); 25 | 26 | first.next = second; 27 | second.next = third; 28 | third.next = null; 29 | } 30 | 31 | @Test 32 | public void whenNotCycledThenFalse() { 33 | assertThat(checker.hasCycle(first), is(false)); 34 | } 35 | 36 | @Test 37 | public void whenCycledLastElementThenTrue() { 38 | this.third.next = third; 39 | assertThat(checker.hasCycle(first), is(true)); 40 | } 41 | 42 | @Test 43 | public void whenCycledSecondElementThenTrue2() { 44 | this.third.next = second; 45 | assertThat(checker.hasCycle(first), is(true)); 46 | } 47 | } -------------------------------------------------------------------------------- /chapter_005/src/test/java/ru/job4j/list/UnidirectionalLinkedListTest.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.list; 2 | 3 | import org.junit.Test; 4 | import org.junit.Before; 5 | import static org.hamcrest.Matchers.is; 6 | import static org.junit.Assert.assertNull; 7 | import static org.junit.Assert.assertThat; 8 | 9 | /** 10 | * @author John Ivanov (johnivo@mail.ru) 11 | * @since 09.04.2019 12 | */ 13 | public class UnidirectionalLinkedListTest { 14 | 15 | private UnidirectionalLinkedList list; 16 | 17 | @Before 18 | public void beforeTest() { 19 | list = new UnidirectionalLinkedList<>(); 20 | list.add(1); 21 | list.add(2); 22 | list.add(3); 23 | } 24 | 25 | @Test 26 | public void whenAddThreeElementsThenUseGetZeroResultTwo() { 27 | assertThat(list.get(0), is(3)); 28 | } 29 | 30 | @Test 31 | public void whenAddThreeElementsThenUseGetSizeResultThree() { 32 | assertThat(list.getSize(), is(3)); 33 | } 34 | 35 | @Test 36 | public void whenTwiceUseDeleteThenUseGetZeroResultOne() { 37 | assertThat(list.delete(), is(3)); 38 | assertThat(list.delete(), is(2)); 39 | assertThat(list.get(0), is(1)); 40 | } 41 | 42 | @Test 43 | public void whenUseDeleteThenUseGetSizeResultTwo() { 44 | list.delete(); 45 | assertThat(list.getSize(), is(2)); 46 | } 47 | } -------------------------------------------------------------------------------- /chapter_005/src/test/java/ru/job4j/set/SimpleSetTest.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.set; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.hamcrest.Matchers.is; 6 | import static org.junit.Assert.assertThat; 7 | 8 | /** 9 | * @author John Ivanov (johnivo@mail.ru) 10 | * @since 15.04.2019 11 | */ 12 | public class SimpleSetTest { 13 | 14 | @Test 15 | public void whenDuplicatesAreAddedThenTheyIgnore() { 16 | SimpleSet set = new SimpleSet<>(); 17 | set.add(1); 18 | set.add(5); 19 | set.add(5); 20 | set.add(3); 21 | set.add(3); 22 | for (Integer e : set) { 23 | System.out.println(e); 24 | } 25 | assertThat(set.size(), is(3)); 26 | } 27 | 28 | @Test 29 | public void whenNullsAddedThenOnlyFirstsNullIsAdded() { 30 | SimpleSet set = new SimpleSet<>(); 31 | set.add(1); 32 | set.add(null); 33 | set.add(null); 34 | set.add(5); 35 | assertThat(set.size(), is(3)); 36 | assertThat(set.get(2), is(5)); 37 | } 38 | } -------------------------------------------------------------------------------- /chapter_006/app.properties: -------------------------------------------------------------------------------- 1 | ## PostgreSQL 2 | 3 | hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect 4 | hibernate.connection.url=jdbc:postgresql://127.0.0.1:5432/trackstudio 5 | hibernate.connection.driver_class=org.postgresql.Driver 6 | hibernate.connection.username=postgres 7 | hibernate.connection.password=password -------------------------------------------------------------------------------- /chapter_006/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | junior 7 | ru.job4j 8 | 2.0 9 | 10 | 4.0.0 11 | 12 | chapter_006 13 | 14 | 15 | 16 | org.mockito 17 | mockito-core 18 | 2.27.0 19 | test 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /chapter_006/src/main/java/ru/job4j/io/chat/MainChat.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.io.chat; 2 | 3 | import java.io.IOException; 4 | 5 | /** 6 | * Запуск консольного чата. 7 | * 8 | * @author John Ivanov (johnivo@mail.ru) 9 | * @since 22.05.2019 10 | */ 11 | public class MainChat { 12 | 13 | public static void main(String[] args) throws IOException { 14 | String path = "c:\\projects\\job4j\\chapter_006\\src\\main\\resources\\lexicon.txt"; 15 | String target = System.getProperty("java.io.tmpdir") + System.getProperty("file.separator") + "chat.log"; 16 | ConsoleChat chat = new ConsoleChat(path, System.in); 17 | chat.launch(target); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /chapter_006/src/main/java/ru/job4j/io/finder/MainFinder.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.io.finder; 2 | 3 | import org.apache.commons.cli.ParseException; 4 | 5 | import java.io.IOException; 6 | 7 | /** 8 | * Запуск поисковика файлов. 9 | * 10 | * @author John Ivanov (johnivo@mail.ru) 11 | * @since 03.06.2019 12 | */ 13 | public class MainFinder { 14 | 15 | public static void main(String[] args) { 16 | Args keys = new Args(args); 17 | Finder finder = new Finder(keys); 18 | try { 19 | finder.search(); 20 | } catch (IOException e) { 21 | e.printStackTrace(); 22 | } 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /chapter_006/src/main/java/ru/job4j/io/zip/MainZip.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.io.zip; 2 | 3 | import org.apache.commons.cli.ParseException; 4 | 5 | import java.io.IOException; 6 | 7 | /** 8 | * Точка входа в программу-архиватор. 9 | * 10 | * @author John Ivanov (johnivo@mail.ru) 11 | * @since 17.05.2019 12 | */ 13 | public class MainZip { 14 | 15 | public static void main(String[] args) throws ParseException { 16 | Zip zip = new Zip(); 17 | Args keys = new Args(args); 18 | try { 19 | zip.pack(keys); 20 | } catch (IOException e) { 21 | e.printStackTrace(); 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /chapter_006/src/main/resources/lexicon.txt: -------------------------------------------------------------------------------- 1 | Привет. 2 | Очень приятно Вас видеть. 3 | Человек отличается от других живых существ способностью к абстрактному мышлению. 4 | У меня нет определенного мнения на этот счет. 5 | А почему? 6 | Жизнь - сложная штука. 7 | Не могу с этим не согласиться. 8 | А что ты еще знаешь? 9 | Науке пока неизвестен ответ на этот вопрос. 10 | Тебе лучше знать, ты человек, а я всего лишь программа. 11 | Действительно. 12 | Постараюсь извлечь урок из нашей беседы. 13 | Это хороший вопрос. 14 | Это тебе показалось. 15 | У меня нет информации по этому вопросу. 16 | Это просто объективный факт. -------------------------------------------------------------------------------- /chapter_007/db/master.xml: -------------------------------------------------------------------------------- 1 | 2 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /chapter_007/db/scripts/update_002.sql: -------------------------------------------------------------------------------- 1 | INSERT INTO Role(name) VALUES ('Admin'), ('User'); 2 | INSERT INTO Rules (resolution) VALUES ('Create user'), ('Update user'), ('Delete user'), ('Add item'), ('Edit any item'), ('Delete any item'), ('Edit own item'), ('Delete own item'); 3 | INSERT INTO RulesToRole (rules_id, role_id) VALUES (1, 1), (2, 1), (3, 1), (4, 1), (5, 1), (6, 1), (4, 2), (7, 2), (8, 2); 4 | INSERT INTO Category (name) VALUES ('Suggestion'), ('Violation of the delivery time'), ('Quality complaint'), ('Technical problem'); 5 | INSERT INTO State (status) VALUES ('Open'), ('In the work'), ('Closed'); 6 | INSERT INTO Users (firstName, lastName, city, phone, role_id) VALUES ('Leo', 'Messi', 'Barca', '+79111234567', 2), ('Zinedine', 'Zidane', 'Madrid', '+79111234589', 2), ('Paul', 'Scholes', 'Manchester', '+79117654321', 1), ('Andreas', 'Iniesta', 'Barca', '+79117654322', 1); -------------------------------------------------------------------------------- /chapter_007/db/scripts/update_003.sql: -------------------------------------------------------------------------------- 1 | INSERT INTO Item (name, description, created, user_id, category_id, state_id) VALUES ('Goods by mail', 'Заказ номер х потерялся на таможне', '2019-06-01 10:00:00', 1, 4, 1), ('Estimated delivery time', 'Превышен срок доставки', '2019-07-01 11:00:00', 3, 3, 3), ('Goods by mail', 'Получен товар ненадлежащего качества', '2019-07-02 12:00:00', 3, 2, 3), ('Technical problem', 'Не отслеживается трек по заказу х', '2018-09-06 10:00:00', 2, 1, 2); 2 | INSERT INTO Comments (comment, item_id) VALUES ('ожидаемый срок доставки 5 дней', 1), ('aaa', 2), ('bbb', 2); 3 | INSERT INTO Attached (link, item_id) VALUES ('image.jpg', 2); 4 | -------------------------------------------------------------------------------- /chapter_007/src/main/java/ru/job4j/crud/ExJob.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.crud; 2 | 3 | import org.apache.logging.log4j.LogManager; 4 | import org.apache.logging.log4j.Logger; 5 | 6 | /** 7 | * @author John Ivanov (johnivo@mail.ru) 8 | * @since 18.06.2019 9 | */ 10 | public class ExJob { 11 | 12 | /** 13 | * Log. 14 | */ 15 | private static final Logger LOG = LogManager.getLogger(ExJob.class.getName()); 16 | 17 | /** 18 | * Main. 19 | * @param args main. 20 | */ 21 | public static void main(String[] args) { 22 | int version = 1; 23 | LOG.trace("trace message {}", version); 24 | LOG.debug("trace message {}", version); 25 | LOG.info("trace message {}", version); 26 | LOG.warn("trace message {}", version); 27 | LOG.error("trace message {}", version); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /chapter_007/src/main/java/ru/job4j/crud/Tracker UML.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/johnivo/job4j/ca9c7eba9ee9a79d2c8b2deaaa5af06bff382dfe/chapter_007/src/main/java/ru/job4j/crud/Tracker UML.png -------------------------------------------------------------------------------- /chapter_007/src/main/java/ru/job4j/crud/select_by_company.sql: -------------------------------------------------------------------------------- 1 | create table company ( 2 | id serial primary key, 3 | name varchar(64) 4 | ); 5 | 6 | insert into company (name) values 7 | ('aaa'), 8 | ('bbb'), 9 | ('ccc'), 10 | ('ddd'), 11 | ('eee'), 12 | ('fff'); 13 | 14 | create table person ( 15 | id serial primary key, 16 | name varchar(64), 17 | company_id int references company(id) 18 | ); 19 | 20 | insert into person (name, company_id) values 21 | ('Bob', 1), 22 | ('Mike', 1), 23 | ('Max', 2), 24 | ('Amy', 4), 25 | ('Any', 4), 26 | ('Sid', 4), 27 | ('Nik', 5), 28 | ('Nata', 6), 29 | ('Ben', 1), 30 | ('Den', 1); 31 | 32 | --select * from company; 33 | 34 | --1) Retrieve in a single query: names of all persons that are NOT in the company with id = 5, company name for each person. 35 | select p.name, c.name from person as p 36 | left outer join company as c on c.id = p.company_id where c.id != 5; 37 | 38 | --2) Select the name of the company with the maximum number of persons + number of persons in this company 39 | select c.name, count(p.name) from person as p 40 | inner join company as c on c.id = p.company_id 41 | group by c.name 42 | order by count(p.name) desc 43 | limit 1; -------------------------------------------------------------------------------- /chapter_007/src/main/java/ru/job4j/logger/UsageLog4j2.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.logger; 2 | 3 | import org.apache.logging.log4j.LogManager; 4 | import org.apache.logging.log4j.Logger; 5 | 6 | /** 7 | * @author John Ivanov (johnivo@mail.ru) 8 | * @since 18.06.2019 9 | */ 10 | public class UsageLog4j2 { 11 | 12 | /** 13 | * Log. 14 | */ 15 | private static final Logger LOG = LogManager.getLogger(UsageLog4j2.class.getName()); 16 | 17 | /** 18 | * Main. 19 | * @param args main. 20 | */ 21 | public static void main(String[] args) { 22 | LOG.trace("trace message"); 23 | LOG.debug("debug message"); 24 | LOG.info("info message"); 25 | LOG.warn("warn message"); 26 | LOG.error("error message"); 27 | } 28 | 29 | } 30 | -------------------------------------------------------------------------------- /chapter_007/src/main/java/ru/job4j/magnit/Config.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.magnit; 2 | 3 | import java.io.InputStream; 4 | import java.util.Properties; 5 | 6 | /** 7 | * Задает параметры соединения. 8 | * 9 | * @author John Ivanov (johnivo@mail.ru) 10 | * @since 27.06.2019 11 | */ 12 | public class Config { 13 | 14 | private final Properties values = new Properties(); 15 | 16 | public void init() { 17 | try (InputStream in = Config.class.getClassLoader().getResourceAsStream("sqlite_app.properties")) { 18 | values.load(in); 19 | } catch (Exception e) { 20 | throw new IllegalStateException(e); 21 | } 22 | } 23 | 24 | public String get(String key) { 25 | return this.values.getProperty(key); 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /chapter_007/src/main/java/ru/job4j/magnit/Entries.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.magnit; 2 | 3 | import javax.xml.bind.annotation.XmlElement; 4 | import javax.xml.bind.annotation.XmlRootElement; 5 | import java.util.List; 6 | 7 | /** 8 | * @author John Ivanov (johnivo@mail.ru) 9 | * @since 28.06.2019 10 | */ 11 | @XmlRootElement 12 | public class Entries { 13 | 14 | private List values; 15 | 16 | public Entries() { 17 | } 18 | 19 | public Entries(List values) { 20 | this.values = values; 21 | } 22 | 23 | @XmlElement(name = "entry") 24 | public List getValues() { 25 | return values; 26 | } 27 | 28 | public void setValues(List values) { 29 | this.values = values; 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /chapter_007/src/main/java/ru/job4j/magnit/Entry.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.magnit; 2 | 3 | import javax.xml.bind.annotation.XmlRootElement; 4 | 5 | /** 6 | * @author John Ivanov (johnivo@mail.ru) 7 | * @since 27.06.2019 8 | */ 9 | @XmlRootElement 10 | public class Entry { 11 | 12 | private int field; 13 | 14 | public Entry() { 15 | } 16 | 17 | public Entry(int field) { 18 | this.field = field; 19 | } 20 | 21 | public int getField() { 22 | return field; 23 | } 24 | 25 | public void setField(int field) { 26 | this.field = field; 27 | } 28 | 29 | } 30 | -------------------------------------------------------------------------------- /chapter_007/src/main/java/ru/job4j/magnit/MainApp.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.magnit; 2 | 3 | /** 4 | * Точка входа в приложение. 5 | * 6 | * @author John Ivanov (johnivo@mail.ru) 7 | * @since 01.07.2019 8 | */ 9 | public class MainApp { 10 | 11 | public static void main(String[] args) { 12 | 13 | new ParserXML().start(); 14 | 15 | } 16 | 17 | } 18 | -------------------------------------------------------------------------------- /chapter_007/src/main/java/ru/job4j/magnit/StoreXML.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.magnit; 2 | 3 | import org.apache.logging.log4j.LogManager; 4 | import org.apache.logging.log4j.Logger; 5 | 6 | import javax.xml.bind.JAXBContext; 7 | import javax.xml.bind.JAXBException; 8 | import javax.xml.bind.Marshaller; 9 | import java.io.File; 10 | import java.util.List; 11 | 12 | /** 13 | * @author John Ivanov (johnivo@mail.ru) 14 | * @since 29.06.2019 15 | */ 16 | public class StoreXML { 17 | 18 | private static final Logger LOG = LogManager.getLogger(StoreSQL.class.getName()); 19 | 20 | /** 21 | * Генерирует файл XML формата из данных базы. 22 | * @param list список всех записей в базе 23 | * @param target целевой файл 24 | */ 25 | public File save(List list, File target) { 26 | 27 | try { 28 | 29 | JAXBContext jaxbContext = JAXBContext.newInstance(Entries.class); 30 | Marshaller jaxbMarshaller = jaxbContext.createMarshaller(); 31 | jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); 32 | Entries entries = new Entries(list); 33 | jaxbMarshaller.marshal(entries, target); 34 | 35 | } catch (JAXBException e) { 36 | LOG.error(e.getMessage(), e); 37 | } 38 | 39 | return target; 40 | } 41 | 42 | } 43 | -------------------------------------------------------------------------------- /chapter_007/src/main/java/ru/job4j/magnit/process.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/johnivo/job4j/ca9c7eba9ee9a79d2c8b2deaaa5af06bff382dfe/chapter_007/src/main/java/ru/job4j/magnit/process.png -------------------------------------------------------------------------------- /chapter_007/src/main/resources/app.properties: -------------------------------------------------------------------------------- 1 | url=jdbc:postgresql://127.0.0.1:5432/tracker 2 | username=postgres 3 | password=password 4 | driver-class-name=org.postgresql.Driver -------------------------------------------------------------------------------- /chapter_007/src/main/resources/log4j2.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /chapter_007/src/main/resources/scheme.xslt: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /chapter_007/src/main/resources/sqlite_app.properties: -------------------------------------------------------------------------------- 1 | url=jdbc:sqlite:test.db 2 | #url=jdbc:sqlite:C:/projects/job4j/chapter_007/test.db 3 | #username=postgres 4 | #password=password 5 | -------------------------------------------------------------------------------- /chapter_007/src/main/resources/structure.sql: -------------------------------------------------------------------------------- 1 | CREATE TABLE Category (category_id serial primary key, name varchar(128)); 2 | CREATE TABLE State (state_id serial primary key, status varchar(128)); 3 | CREATE TABLE Role (role_id serial primary key, name varchar(128)); 4 | CREATE TABLE Rules (rules_id serial primary key, resolution varchar(128)); 5 | CREATE TABLE RulesToRole (rules_to_role_id serial primary key, role_id int references Role(role_id) ON UPDATE CASCADE ON DELETE CASCADE, rules_id int references Rules(rules_id) ON UPDATE CASCADE ON DELETE CASCADE); 6 | CREATE TABLE Users (user_id serial primary key, firstName varchar(128), lastName varchar(128), city varchar(128), phone varchar(64), role_id int references Role(role_id) ON UPDATE CASCADE ON DELETE SET NULL); 7 | CREATE TABLE Item (item_id serial primary key, name varchar(128), description varchar(512), created timestamp, user_id int references Users(user_id) ON UPDATE CASCADE ON DELETE SET NULL, category_id int references Category(category_id) ON UPDATE CASCADE ON DELETE SET NULL, state_id int references State(state_id) ON UPDATE CASCADE ON DELETE SET NULL); 8 | CREATE TABLE Comments (comments_id serial primary key, comment text, item_id int references Item(item_id) ON UPDATE CASCADE ON DELETE CASCADE); 9 | CREATE TABLE Attached (attached_id serial primary key, link varchar(2048), item_id int references Item(item_id) ON UPDATE CASCADE ON DELETE CASCADE); -------------------------------------------------------------------------------- /chapter_008/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | junior 7 | ru.job4j 8 | 2.0 9 | 10 | 4.0.0 11 | 12 | chapter_008 13 | 14 | 15 | -------------------------------------------------------------------------------- /chapter_008/src/main/java/ru/job4j/generator/SimpleGeneratorException.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.generator; 2 | 3 | /** 4 | * @author John Ivanov (johnivo@mail.ru) 5 | * @since 13.08.2019 6 | */ 7 | public class SimpleGeneratorException extends RuntimeException { 8 | 9 | public SimpleGeneratorException(String msg) { 10 | super(msg); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /chapter_008/src/main/java/ru/job4j/generator/Template.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.generator; 2 | 3 | import java.util.Map; 4 | 5 | /** 6 | * @author John Ivanov (johnivo@mail.ru) 7 | * @since 12.08.2019 8 | */ 9 | public interface Template { 10 | 11 | String generate(String template, Map data); 12 | 13 | } 14 | -------------------------------------------------------------------------------- /chapter_008/src/main/java/ru/job4j/interactcalc/Action.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.interactcalc; 2 | 3 | /** 4 | * @author John Ivanov (johnivo@mail.ru) 5 | * @since 21.07.2019 6 | */ 7 | public interface Action { 8 | 9 | String operation(); 10 | 11 | Double arithmetical(Double first, Double second); 12 | 13 | Boolean getArgs(); 14 | 15 | } 16 | -------------------------------------------------------------------------------- /chapter_008/src/main/java/ru/job4j/interactcalc/ConsoleInput.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.interactcalc; 2 | 3 | import java.util.Scanner; 4 | 5 | /** 6 | * @author John Ivanov (johnivo@mail.ru) 7 | * @since 21.07.2019 8 | */ 9 | public class ConsoleInput implements Input { 10 | 11 | private final Scanner scanner = new Scanner(System.in); 12 | 13 | @Override 14 | public String next() { 15 | return scanner.next(); 16 | } 17 | 18 | @Override 19 | public String ask(String question) { 20 | System.out.print(question); 21 | return scanner.nextLine(); 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /chapter_008/src/main/java/ru/job4j/interactcalc/Input.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.interactcalc; 2 | 3 | /** 4 | * @author John Ivanov (johnivo@mail.ru) 5 | * @since 21.07.2019 6 | */ 7 | public interface Input { 8 | 9 | String next(); 10 | 11 | String ask(String question); 12 | 13 | } 14 | -------------------------------------------------------------------------------- /chapter_008/src/main/java/ru/job4j/interactcalc/Option.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.interactcalc; 2 | 3 | /** 4 | * @author John Ivanov (johnivo@mail.ru) 5 | * @since 22.07.2019 6 | */ 7 | public interface Option { 8 | 9 | String option(); 10 | 11 | } 12 | -------------------------------------------------------------------------------- /chapter_008/src/main/java/ru/job4j/interactcalc/StartCalc.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.interactcalc; 2 | 3 | /** 4 | * @author John Ivanov (johnivo@mail.ru) 5 | * @since 22.07.2019 6 | */ 7 | public class StartCalc { 8 | 9 | public static void main(String[] args) { 10 | 11 | Input input = new ConsoleInput(); 12 | Calculator calc = new EngineerCalculator(); 13 | InteractCalc interactCalc = new InteractCalc(input, calc, System.out::println); 14 | 15 | interactCalc.action(); 16 | 17 | } 18 | 19 | } 20 | -------------------------------------------------------------------------------- /chapter_008/src/main/java/ru/job4j/interactcalc/StubInput.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.interactcalc; 2 | 3 | /** 4 | * @author John Ivanov (johnivo@mail.ru) 5 | * @since 22.07.2019 6 | */ 7 | public class StubInput implements Input { 8 | 9 | /** 10 | * Поле содержит последовательность ответов пользователя. 11 | */ 12 | private final String[] value; 13 | 14 | /** 15 | * Поле считает количество вызовов метода ask. 16 | * При каждом вызове надо передвинуть указатель на новое число. 17 | */ 18 | private int position; 19 | 20 | /** 21 | * Конструктор. 22 | * @param value массив ответов. 23 | */ 24 | public StubInput(final String[] value) { 25 | this.value = value; 26 | } 27 | 28 | /** 29 | * Симулятор поведения пользователя. 30 | * При каждом вызове метода ask счетчик увеличивается и 31 | * при следующем вызове он вернет новое значение. 32 | * @param question вопрос. 33 | */ 34 | @Override 35 | public String ask(String question) { 36 | return this.value[this.position++]; 37 | } 38 | 39 | @Override 40 | public String next() { 41 | return null; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /chapter_008/src/main/java/ru/job4j/menu/CreateMenu.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.menu; 2 | 3 | import java.util.Map; 4 | import java.util.Set; 5 | 6 | /** 7 | * Описывает создание меню. 8 | * 9 | * @author John Ivanov (johnivo@mail.ru) 10 | * @since 06.08.2019 11 | */ 12 | public interface CreateMenu { 13 | 14 | Set create(Map menu); 15 | 16 | } 17 | -------------------------------------------------------------------------------- /chapter_008/src/main/java/ru/job4j/menu/ExecuteMenuItem.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.menu; 2 | 3 | /** 4 | * Описывает работу с пунктом меню - выбор и выполнение действия. 5 | * 6 | * @author John Ivanov (johnivo@mail.ru) 7 | * @since 06.08.2019 8 | */ 9 | public interface ExecuteMenuItem { 10 | 11 | void select(String name); 12 | 13 | void execute(MenuItem menuItem); 14 | 15 | } 16 | -------------------------------------------------------------------------------- /chapter_008/src/main/java/ru/job4j/menu/IMenu.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.menu; 2 | 3 | /** 4 | * Общий интерфейс для реализации меню. 5 | * 6 | * @author John Ivanov (johnivo@mail.ru) 7 | * @since 06.08.2019 8 | */ 9 | public interface IMenu extends CreateMenu, ShowMenu, ExecuteMenuItem { 10 | 11 | } 12 | -------------------------------------------------------------------------------- /chapter_008/src/main/java/ru/job4j/menu/MenuItem.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.menu; 2 | 3 | import java.util.*; 4 | 5 | /** 6 | * Описание пункта меню. 7 | * 8 | * @author John Ivanov (johnivo@mail.ru) 9 | * @since 05.08.2019 10 | */ 11 | public class MenuItem { 12 | 13 | /** 14 | * Имя пункта меню. 15 | */ 16 | private String name; 17 | 18 | /** 19 | * Список имен подпунктов - пп. 20 | */ 21 | private List items; 22 | 23 | /** 24 | * Конструктор, пункт меню не содержит пп. 25 | * @param name имя пункта. 26 | */ 27 | public MenuItem(String name) { 28 | this.name = name; 29 | } 30 | 31 | /** 32 | * Конструктор, пункт меню содержит пп. 33 | * @param name имя пункта. 34 | * @param items список пп. 35 | */ 36 | public MenuItem(String name, List items) { 37 | this.name = name; 38 | this.items = items; 39 | } 40 | 41 | @Override 42 | public String toString() { 43 | return "MenuItem{" + "items=" + items + '}'; 44 | } 45 | 46 | /** 47 | * Возвращает имя пункта. 48 | */ 49 | public String getName() { 50 | return this.name; 51 | } 52 | 53 | /** 54 | * Возвращает список пп. 55 | */ 56 | public List getItems() { 57 | return this.items; 58 | } 59 | 60 | } 61 | -------------------------------------------------------------------------------- /chapter_008/src/main/java/ru/job4j/menu/ShowMenu.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.menu; 2 | 3 | import java.io.ByteArrayOutputStream; 4 | import java.util.Set; 5 | 6 | /** 7 | * Описывает вывод меню. 8 | * 9 | * @author John Ivanov (johnivo@mail.ru) 10 | * @since 06.08.2019 11 | */ 12 | public interface ShowMenu { 13 | 14 | void showMenu(Set menu, ByteArrayOutputStream out); 15 | 16 | } 17 | -------------------------------------------------------------------------------- /chapter_008/src/main/java/ru/job4j/tictactoe/InvalidActionException.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.tictactoe; 2 | 3 | /** 4 | * @author John Ivanov (johnivo@mail.ru) 5 | * @since 09.09.2019 6 | */ 7 | public class InvalidActionException extends RuntimeException { 8 | 9 | public InvalidActionException(String message) { 10 | super(message); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /chapter_008/src/main/java/ru/job4j/tictactoe/TicTacToe.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.tictactoe; 2 | 3 | import ru.job4j.tictactoe.game.*; 4 | import ru.job4j.tictactoe.logic.*; 5 | import ru.job4j.tictactoe.player.*; 6 | 7 | /** 8 | * @author John Ivanov (johnivo@mail.ru) 9 | * @since 11.09.2019 10 | */ 11 | public class TicTacToe { 12 | 13 | public static void main(String[] args) { 14 | Logic logic = new Logic3T(3); 15 | 16 | Player first = new User(logic, "user", System.in, System.out::println); 17 | Player second = new BotSimple(logic, "bot"); 18 | 19 | Game cg = new ConsoleGame(logic, first, second, 5, System.out::println); 20 | 21 | cg.newGame(); 22 | while (!cg.exitGame()) { 23 | cg.nextMove(); 24 | } 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /chapter_008/src/main/java/ru/job4j/tictactoe/game/Game.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.tictactoe.game; 2 | 3 | /** 4 | * Описывает игру 5 | * 6 | * @author John Ivanov (johnivo@mail.ru) 7 | * @since 10.09.2019 8 | */ 9 | public interface Game { 10 | 11 | void newGame(); 12 | 13 | void showTable(); 14 | 15 | void nextMove(); 16 | 17 | boolean exitGame(); 18 | 19 | } 20 | -------------------------------------------------------------------------------- /chapter_008/src/main/java/ru/job4j/tictactoe/logic/Cell.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.tictactoe.logic; 2 | 3 | /** 4 | * Описывает клетку поля 5 | * 6 | * @author John Ivanov (johnivo@mail.ru) 7 | * @since 09.09.2019 8 | */ 9 | public class Cell { 10 | 11 | private final int x; 12 | private final int y; 13 | 14 | public Cell(int x, int y) { 15 | this.x = x; 16 | this.y = y; 17 | } 18 | 19 | public int getX() { 20 | return x; 21 | } 22 | 23 | public int getY() { 24 | return y; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /chapter_008/src/main/java/ru/job4j/tictactoe/logic/Logic.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.tictactoe.logic; 2 | 3 | /** 4 | * Описывает логику игры. 5 | * 6 | * @author John Ivanov (johnivo@mail.ru) 7 | * @since 09.09.2019 8 | */ 9 | public interface Logic { 10 | 11 | void newGame(); 12 | 13 | int getTableSize(); 14 | 15 | int getNumberOfMoves(); 16 | 17 | String getMark(Cell cell); 18 | 19 | void makeMove(Cell cell, String mark); 20 | 21 | boolean checkPossibleOfMove(); 22 | 23 | String checkWinner(); 24 | 25 | //void exitGame(); 26 | 27 | } 28 | -------------------------------------------------------------------------------- /chapter_008/src/main/java/ru/job4j/tictactoe/player/Player.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.tictactoe.player; 2 | 3 | import ru.job4j.tictactoe.logic.Cell; 4 | 5 | /** 6 | * Описывает поведение игрока. 7 | * 8 | * @author John Ivanov (johnivo@mail.ru) 9 | * @since 10.09.2019 10 | */ 11 | public interface Player { 12 | 13 | Cell move(); 14 | 15 | void setMark(String mark); 16 | 17 | String getMark(); 18 | 19 | String getName(); 20 | 21 | } 22 | -------------------------------------------------------------------------------- /chapter_008/src/main/java/ru/job4j/warehouse/Fruits.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.warehouse; 2 | 3 | import java.time.LocalDateTime; 4 | 5 | /** 6 | * @author John Ivanov (johnivo@mail.ru) 7 | * @since 29.07.2019 8 | */ 9 | public class Fruits extends Food { 10 | 11 | public Fruits(String name, LocalDateTime createDate, LocalDateTime expiryDate, Double price, Double discount) { 12 | super(name, createDate, expiryDate, price, discount); 13 | } 14 | 15 | @Override 16 | public boolean canReproduct() { 17 | return true; 18 | } 19 | 20 | @Override 21 | public boolean lowTemp() { 22 | return false; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /chapter_008/src/main/java/ru/job4j/warehouse/Meat.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.warehouse; 2 | 3 | import java.time.LocalDateTime; 4 | 5 | /** 6 | * @author John Ivanov (johnivo@mail.ru) 7 | * @since 29.07.2019 8 | */ 9 | public class Meat extends Food { 10 | 11 | public Meat(String name, LocalDateTime createDate, LocalDateTime expiryDate, Double price, Double discount) { 12 | super(name, createDate, expiryDate, price, discount); 13 | } 14 | 15 | @Override 16 | public boolean canReproduct() { 17 | return false; 18 | } 19 | 20 | @Override 21 | public boolean lowTemp() { 22 | return false; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /chapter_008/src/main/java/ru/job4j/warehouse/RecyclingFactory.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.warehouse; 2 | 3 | import java.time.LocalDateTime; 4 | 5 | /** 6 | * @author John Ivanov (johnivo@mail.ru) 7 | * @since 03.08.2019 8 | */ 9 | public class RecyclingFactory extends StorageDecorator { 10 | 11 | public RecyclingFactory(Storage decoratedStorage) { 12 | super(decoratedStorage); 13 | } 14 | 15 | @Override 16 | public boolean checkExpiration(Food food, LocalDateTime current) { 17 | boolean result = false; 18 | 19 | if (decoratedStorage.checkExpiration(food, current) && food.canReproduct()) { 20 | result = true; 21 | } 22 | 23 | return result; 24 | } 25 | 26 | @Override 27 | public String toString() { 28 | return "RecyclingFactory"; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /chapter_008/src/main/java/ru/job4j/warehouse/Refrigerator.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.warehouse; 2 | 3 | import java.time.LocalDateTime; 4 | 5 | /** 6 | * @author John Ivanov (johnivo@mail.ru) 7 | * @since 03.08.2019 8 | */ 9 | public class Refrigerator extends StorageDecorator { 10 | 11 | public Refrigerator(Storage decoratedStorage) { 12 | super(decoratedStorage); 13 | } 14 | 15 | @Override 16 | public boolean checkExpiration(Food food, LocalDateTime current) { 17 | boolean result = false; 18 | 19 | if (decoratedStorage.checkExpiration(food, current) && food.canReproduct() && food.lowTemp()) { 20 | result = true; 21 | } 22 | 23 | return result; 24 | } 25 | 26 | @Override 27 | public String toString() { 28 | return "Refrigerator"; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /chapter_008/src/main/java/ru/job4j/warehouse/Reproduct.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.warehouse; 2 | 3 | /** 4 | * @author John Ivanov (johnivo@mail.ru) 5 | * @since 02.08.2019 6 | */ 7 | public interface Reproduct { 8 | 9 | boolean canReproduct(); 10 | 11 | } 12 | -------------------------------------------------------------------------------- /chapter_008/src/main/java/ru/job4j/warehouse/SecondWarehause.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.warehouse; 2 | 3 | import java.time.LocalDateTime; 4 | 5 | /** 6 | * @author John Ivanov (johnivo@mail.ru) 7 | * @since 03.08.2019 8 | */ 9 | public class SecondWarehause extends StorageDecorator { 10 | 11 | public SecondWarehause(Storage decoratedStorage) { 12 | super(decoratedStorage); 13 | } 14 | 15 | @Override 16 | public boolean checkExpiration(Food food, LocalDateTime current) { 17 | return decoratedStorage.checkExpiration(food, current); 18 | } 19 | 20 | @Override 21 | public String toString() { 22 | return "SecondWarehause"; 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /chapter_008/src/main/java/ru/job4j/warehouse/StorageDecorator.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.warehouse; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | /** 7 | * @author John Ivanov (johnivo@mail.ru) 8 | * @since 02.08.2019 9 | */ 10 | public abstract class StorageDecorator implements Storage { 11 | 12 | protected Storage decoratedStorage; 13 | 14 | public StorageDecorator(Storage decoratedStorage) { 15 | this.decoratedStorage = decoratedStorage; 16 | } 17 | 18 | private List foods = new ArrayList(); 19 | 20 | @Override 21 | public void add(Food food) { 22 | this.foods.add(food); 23 | } 24 | 25 | @Override 26 | public void clear() { 27 | this.foods.clear(); 28 | } 29 | 30 | @Override 31 | public void setStorage(Storage decoratedStorage) { 32 | this.decoratedStorage = decoratedStorage; 33 | } 34 | 35 | @Override 36 | public List getList() { 37 | return foods; 38 | } 39 | 40 | } 41 | -------------------------------------------------------------------------------- /chapter_008/src/main/java/ru/job4j/warehouse/Trash.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.warehouse; 2 | 3 | import java.time.LocalDateTime; 4 | import java.util.ArrayList; 5 | import java.util.List; 6 | 7 | /** 8 | * @author John Ivanov (johnivo@mail.ru) 9 | * @since 29.07.2019 10 | */ 11 | public class Trash implements Storage { 12 | 13 | private List foods = new ArrayList(); 14 | 15 | @Override 16 | public void add(Food food) { 17 | this.foods.add(food); 18 | } 19 | 20 | @Override 21 | public void clear() { 22 | this.foods.clear(); 23 | } 24 | 25 | @Override 26 | public void setStorage(Storage storage) { 27 | } 28 | 29 | @Override 30 | public List getList() { 31 | return foods; 32 | } 33 | 34 | @Override 35 | public boolean checkExpiration(Food food, LocalDateTime current) { 36 | boolean result = false; 37 | 38 | double passed = Storage.duration(food.getCreateDate(), current); 39 | double leftover = Storage.duration(food.getCreateDate(), food.getExpiryDate()); 40 | double expire = passed / leftover; 41 | 42 | if (expire >= 1) { 43 | result = true; 44 | } 45 | return result; 46 | } 47 | 48 | @Override 49 | public String toString() { 50 | return "Trash"; 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /chapter_008/src/main/java/ru/job4j/warehouse/Vegetables.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.warehouse; 2 | 3 | import java.time.LocalDateTime; 4 | 5 | /** 6 | * @author John Ivanov (johnivo@mail.ru) 7 | * @since 29.07.2019 8 | */ 9 | public class Vegetables extends Food { 10 | 11 | public Vegetables(String name, LocalDateTime createDate, LocalDateTime expiryDate, Double price, Double discount) { 12 | super(name, createDate, expiryDate, price, discount); 13 | } 14 | 15 | @Override 16 | public boolean canReproduct() { 17 | return true; 18 | } 19 | 20 | @Override 21 | public boolean lowTemp() { 22 | return true; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /chapter_008/src/main/java/ru/job4j/warehouse/VegetablesReproduct.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.warehouse; 2 | 3 | /** 4 | * @author John Ivanov (johnivo@mail.ru) 5 | * @since 03.08.2019 6 | */ 7 | public interface VegetablesReproduct { 8 | 9 | boolean lowTemp(); 10 | 11 | } 12 | -------------------------------------------------------------------------------- /chapter_008/src/main/java/ru/job4j/warehouse/Warehouse.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.warehouse; 2 | 3 | import java.time.LocalDateTime; 4 | import java.util.ArrayList; 5 | import java.util.List; 6 | 7 | /** 8 | * @author John Ivanov (johnivo@mail.ru) 9 | * @since 29.07.2019 10 | */ 11 | public class Warehouse implements Storage { 12 | 13 | private List foods = new ArrayList(); 14 | 15 | @Override 16 | public void add(Food food) { 17 | this.foods.add(food); 18 | } 19 | 20 | @Override 21 | public void clear() { 22 | this.foods.clear(); 23 | } 24 | 25 | @Override 26 | public void setStorage(Storage storage) { 27 | } 28 | 29 | @Override 30 | public List getList() { 31 | return foods; 32 | } 33 | 34 | @Override 35 | public boolean checkExpiration(Food food, LocalDateTime current) { 36 | boolean result = false; 37 | 38 | double passed = Storage.duration(food.getCreateDate(), current); 39 | double leftover = Storage.duration(food.getCreateDate(), food.getExpiryDate()); 40 | 41 | double expire = passed / leftover; 42 | 43 | if (expire < Storage.LOWER && expire > 0) { 44 | result = true; 45 | } 46 | 47 | return result; 48 | } 49 | 50 | @Override 51 | public String toString() { 52 | return "Warehouse"; 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /chapter_008/src/test/java/ru/job4j/tictactoe/BotSimpleTest.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.tictactoe; 2 | 3 | import org.junit.Test; 4 | import ru.job4j.tictactoe.logic.*; 5 | import ru.job4j.tictactoe.player.*; 6 | 7 | import static org.junit.Assert.*; 8 | 9 | /** 10 | * @author John Ivanov (johnivo@mail.ru) 11 | * @since 10.09.2019 12 | */ 13 | public class BotSimpleTest { 14 | 15 | @Test 16 | public void whenBotMoveThenCellIsWithinField() { 17 | Logic logic3T = new Logic3T(3); 18 | Player bot = new BotSimple(logic3T, "Simple bot"); 19 | 20 | Cell cell = bot.move(); 21 | 22 | assertTrue(cell.getX() >= 0 && cell.getX() < 3); 23 | assertTrue(cell.getY() >= 0 && cell.getY() < 3); 24 | } 25 | 26 | } -------------------------------------------------------------------------------- /chapter_009/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | junior 7 | ru.job4j 8 | 2.0 9 | 10 | 4.0.0 11 | 12 | chapter_009 13 | 14 | 15 | 16 | 17 | 18 | com.carrotsearch 19 | java-sizeof 20 | 0.0.5 21 | 22 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /chapter_009/src/main/java/ru/job4j/gc/GCInfo.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.gc; 2 | 3 | import java.lang.management.GarbageCollectorMXBean; 4 | import java.lang.management.ManagementFactory; 5 | import java.util.List; 6 | 7 | /** 8 | * @author John Ivanov (johnivo@mail.ru) 9 | * @since 28.08.2019 10 | */ 11 | public class GCInfo { 12 | 13 | public static void main(String[] args) { 14 | try { 15 | List gcMxBeans = ManagementFactory.getGarbageCollectorMXBeans(); 16 | 17 | for (GarbageCollectorMXBean gcMxBean : gcMxBeans) { 18 | System.out.println(gcMxBean.getName()); 19 | System.out.println(gcMxBean.getObjectName()); 20 | System.out.println(); 21 | } 22 | 23 | } catch (RuntimeException re) { 24 | throw re; 25 | } catch (Exception exp) { 26 | throw new RuntimeException(exp); 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /chapter_009/src/main/java/ru/job4j/gc/ICache.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.gc; 2 | 3 | /** 4 | * Описывает получение данных из кеша. 5 | * 6 | * @author John Ivanov (johnivo@mail.ru) 7 | * @since 04.09.2019 8 | */ 9 | public interface ICache { 10 | 11 | String getData(String key); 12 | 13 | } 14 | -------------------------------------------------------------------------------- /chapter_009/src/main/java/ru/job4j/gc/Tracker Profiling.md: -------------------------------------------------------------------------------- 1 | 1. Используя различные утилиты для анализа памяти виртуальной машины провести анализ работы программы 2 | из второго модуля. Программа по обработке заявок Tracker. 3 | 4 | 2. Данные анализа описать в текстовом файле и добавить в репозиторий. В файле нужно указать, 5 | каким инструментом проведен анализ и что по нему видно. 6 | 7 | 3. Попробовать добиться состояния выхода за пределы памяти и посмотреть состояние виртуальной машины. 8 | 9 | Для анализа использовалась jconsole: 10 | 11 | ![img](https://github.com/johnivo/job4j/blob/master/chapter_009/src/main/resources/tracker1.jpg) 12 | 13 | Использовались настройки по умолчанию(G1GC), при заполнении соотвествующих областей в куче 14 | визаульно наблюдались малые сборки мусора в Eden Space 15 | 16 | ![img](https://github.com/johnivo/job4j/blob/master/chapter_009/src/main/resources/tracker2.jpg) 17 | 18 | и полные 19 | 20 | ![img](https://github.com/johnivo/job4j/blob/master/chapter_009/src/main/resources/Tracker3.jpg) 21 | 22 | При критическом росте количества заявок (около 10млн) произошло переполнение доступной памяти созданными объектами. 23 | Программа упала с java.lang.OutOfMemoryError: Java heap space. 24 | 25 | ![img](https://github.com/johnivo/job4j/blob/master/chapter_009/src/main/resources/Tracker4.jpg) 26 | 27 | Все потоки были остановлены, данные выгружены из памяти. -------------------------------------------------------------------------------- /chapter_009/src/main/resources/Address.txt: -------------------------------------------------------------------------------- 1 | Msk 2 | SPb 3 | Vol -------------------------------------------------------------------------------- /chapter_009/src/main/resources/Names.txt: -------------------------------------------------------------------------------- 1 | Nata 2 | Oleg 3 | Any 4 | Mike -------------------------------------------------------------------------------- /chapter_009/src/main/resources/Tracker3.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/johnivo/job4j/ca9c7eba9ee9a79d2c8b2deaaa5af06bff382dfe/chapter_009/src/main/resources/Tracker3.jpg -------------------------------------------------------------------------------- /chapter_009/src/main/resources/Tracker4.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/johnivo/job4j/ca9c7eba9ee9a79d2c8b2deaaa5af06bff382dfe/chapter_009/src/main/resources/Tracker4.jpg -------------------------------------------------------------------------------- /chapter_009/src/main/resources/log4j2.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /chapter_009/src/main/resources/tracker1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/johnivo/job4j/ca9c7eba9ee9a79d2c8b2deaaa5af06bff382dfe/chapter_009/src/main/resources/tracker1.jpg -------------------------------------------------------------------------------- /chapter_009/src/main/resources/tracker2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/johnivo/job4j/ca9c7eba9ee9a79d2c8b2deaaa5af06bff382dfe/chapter_009/src/main/resources/tracker2.jpg -------------------------------------------------------------------------------- /chapter_010/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | junior 7 | ru.job4j 8 | 2.0 9 | 10 | 4.0.0 11 | 12 | chapter_010 13 | 14 | 15 | 16 | 17 | 18 | net.jcip 19 | jcip-annotations 20 | 1.0 21 | 22 | 23 | 24 | ru.job4j 25 | chapter_005 26 | 2.0 27 | 28 | 29 | 30 | 31 | -------------------------------------------------------------------------------- /chapter_010/src/main/java/ru/job4j/count/Count.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.count; 2 | 3 | import net.jcip.annotations.GuardedBy; 4 | import net.jcip.annotations.ThreadSafe; 5 | 6 | /** 7 | * @author John Ivanov (johnivo@mail.ru) 8 | * @since 14.10.2019 9 | */ 10 | @ThreadSafe 11 | public class Count { 12 | @GuardedBy("this") 13 | private int value; 14 | 15 | public synchronized void increment() { 16 | this.value++; 17 | } 18 | 19 | public synchronized int get() { 20 | return this.value; 21 | } 22 | 23 | } 24 | -------------------------------------------------------------------------------- /chapter_010/src/main/java/ru/job4j/email/User.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.email; 2 | 3 | /** 4 | * @author John Ivanov (johnivo@mail.ru) 5 | * @since 24.10.2019 6 | */ 7 | public class User { 8 | 9 | private final String username; 10 | 11 | private final String email; 12 | 13 | public User(String username, String email) { 14 | this.username = username; 15 | this.email = email; 16 | } 17 | 18 | public String getUsername() { 19 | return username; 20 | } 21 | 22 | public String getEmail() { 23 | return email; 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /chapter_010/src/main/java/ru/job4j/jmm/race/ActionOne.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.jmm.race; 2 | 3 | /** 4 | * @author John Ivanov (johnivo@mail.ru) 5 | * @since 14.10.2019 6 | */ 7 | public class ActionOne implements Runnable { 8 | 9 | public Counter counter; 10 | 11 | public ActionOne(Counter counter) { 12 | this.counter = counter; 13 | } 14 | 15 | @Override 16 | public void run() { 17 | for (int i = 0; i < 10; i++) { 18 | counter.add(1); 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /chapter_010/src/main/java/ru/job4j/jmm/race/ActionTwo.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.jmm.race; 2 | 3 | /** 4 | * @author John Ivanov (johnivo@mail.ru) 5 | * @since 14.10.2019 6 | */ 7 | public class ActionTwo extends Thread { 8 | 9 | public Counter counter; 10 | 11 | public ActionTwo(Counter counter) { 12 | this.counter = counter; 13 | } 14 | 15 | @Override 16 | public void run() { 17 | for (int i = 0; i < 10; i++) { 18 | counter.add(100); 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /chapter_010/src/main/java/ru/job4j/jmm/race/Counter.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.jmm.race; 2 | 3 | /** 4 | * @author John Ivanov (johnivo@mail.ru) 5 | * @since 14.10.2019 6 | */ 7 | public class Counter { 8 | 9 | public int count; 10 | 11 | //Два потока используют общий ресурс - один объект типа счетчик и одновременно меняют его состояние 12 | //Чтобы уйти от состояния гонки, нужно синхронизировать код в критической секции 13 | //в нашем случае синхронизируем метод экземпляра 14 | //public synchronized void add(int value) { 15 | 16 | public void add(int value) { 17 | int temp = count; 18 | this.count = this.count + value; 19 | 20 | System.out.println(String.format("thread %s: %s + %s = %s", Thread.currentThread().getName(), temp, value, count)); 21 | 22 | } 23 | 24 | public static void main(String[] args) { 25 | 26 | Counter counter = new Counter(); 27 | 28 | ActionOne one = new ActionOne(counter); 29 | ActionTwo two = new ActionTwo(counter); 30 | 31 | Thread a = new Thread(new ActionOne(counter), "A"); 32 | Thread b = new Thread(new ActionTwo(counter), "B"); 33 | //new ActionTwo(counter).start(); 34 | 35 | a.start(); 36 | b.start(); 37 | } 38 | 39 | } 40 | -------------------------------------------------------------------------------- /chapter_010/src/main/java/ru/job4j/jmm/shared/VolatileDemo.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.jmm.shared; 2 | 3 | /** 4 | * @author John Ivanov (johnivo@mail.ru) 5 | * @since 14.10.2019 6 | */ 7 | public class VolatileDemo extends Thread { 8 | 9 | //использование volatile гарантирует видимость переменной для всех потоков 10 | //как только мы используем volatile вечный цикл завершится, будет использовано значение флага из основной памяти 11 | //volatile boolean keepRunning = true; 12 | boolean keepRunning = true; 13 | 14 | @Override 15 | public void run() { 16 | long count = 0; 17 | while (keepRunning) { 18 | count++; 19 | } 20 | System.out.println("Thread terminated. " + count); 21 | } 22 | 23 | public static void main(String[] args) throws InterruptedException { 24 | VolatileDemo demo = new VolatileDemo(); 25 | demo.start(); 26 | Thread.sleep(1000); 27 | System.out.println("after sleeping in main"); 28 | demo.keepRunning = false; 29 | demo.join(); 30 | System.out.println("keepRunning set to " + demo.keepRunning); 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /chapter_010/src/main/java/ru/job4j/nonblockingalgorithm/Base.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.nonblockingalgorithm; 2 | 3 | /** 4 | * @author John Ivanov (johnivo@mail.ru) 5 | * @since 20.10.2019 6 | */ 7 | public class Base { 8 | 9 | private int id; 10 | 11 | private volatile int version; 12 | 13 | public Base(int id, int version) { 14 | this.id = id; 15 | this.version = version; 16 | } 17 | 18 | public int getId() { 19 | return id; 20 | } 21 | 22 | public void setId(int id) { 23 | this.id = id; 24 | } 25 | 26 | public int getVersion() { 27 | return version; 28 | } 29 | 30 | public void setVersion(int version) { 31 | this.version = version; 32 | } 33 | 34 | @Override 35 | public String toString() { 36 | return "Base{" + "id=" + id + ", version=" + version + '}'; 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /chapter_010/src/main/java/ru/job4j/nonblockingalgorithm/NonBlockCache.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.nonblockingalgorithm; 2 | 3 | import java.util.concurrent.ConcurrentHashMap; 4 | 5 | /** 6 | * @author John Ivanov (johnivo@mail.ru) 7 | * @since 20.10.2019 8 | */ 9 | public class NonBlockCache { 10 | 11 | private final ConcurrentHashMap cache = new ConcurrentHashMap<>(); 12 | 13 | public void add(Base model) { 14 | cache.put(model.getId(), model); 15 | } 16 | 17 | public boolean update(Base model) { 18 | boolean rst = false; 19 | 20 | if (cache.computeIfPresent(model.getId(), (key, value) -> { 21 | if (model.getVersion() != value.getVersion()) { 22 | throw new OptimisticException("versions do not match"); 23 | } 24 | model.setVersion(model.getVersion() + 1); 25 | return model; 26 | } 27 | ) != null) { 28 | rst = true; 29 | } 30 | 31 | return rst; 32 | } 33 | 34 | public void delete(Base model) { 35 | cache.remove(model.getId()); 36 | } 37 | 38 | public Integer size() { 39 | return cache.size(); 40 | } 41 | 42 | public Base getBase(int key) { 43 | return cache.get(key); 44 | } 45 | 46 | } 47 | -------------------------------------------------------------------------------- /chapter_010/src/main/java/ru/job4j/nonblockingalgorithm/OptimisticException.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.nonblockingalgorithm; 2 | 3 | /** 4 | * @author John Ivanov (johnivo@mail.ru) 5 | * @since 20.10.2019 6 | */ 7 | public class OptimisticException extends RuntimeException { 8 | 9 | public OptimisticException(String message) { 10 | super(message); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /chapter_010/src/main/java/ru/job4j/pool/TaskExecutor.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.pool; 2 | 3 | import ru.job4j.blockingqueue.SimpleBlockingQueue; 4 | 5 | /** 6 | * @author John Ivanov (johnivo@mail.ru) 7 | * @since 22.10.2019 8 | */ 9 | public class TaskExecutor extends Thread { 10 | 11 | private SimpleBlockingQueue taskQueue; 12 | 13 | public TaskExecutor(SimpleBlockingQueue taskQueue) { 14 | this.taskQueue = taskQueue; 15 | } 16 | 17 | @Override 18 | public void run() { 19 | 20 | while (!Thread.currentThread().isInterrupted() || !taskQueue.isEmpty()) { 21 | try { 22 | Runnable task = taskQueue.poll(); 23 | task.run(); 24 | } catch (Exception e) { 25 | //e.printStackTrace(); 26 | Thread.currentThread().interrupt(); 27 | } 28 | } 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /chapter_010/src/test/java/ru/job4j/count/CountTest.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.count; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.hamcrest.Matchers.is; 6 | import static org.junit.Assert.*; 7 | 8 | /** 9 | * @author John Ivanov (johnivo@mail.ru) 10 | * @since 14.10.2019 11 | */ 12 | public class CountTest { 13 | 14 | /** 15 | * Класс описывает нить со счетчиком. 16 | */ 17 | private class ThreadCount extends Thread { 18 | private final Count count; 19 | 20 | private ThreadCount(final Count count) { 21 | this.count = count; 22 | } 23 | 24 | @Override 25 | public void run() { 26 | this.count.increment(); 27 | } 28 | } 29 | 30 | @Test 31 | public void whenExecute2ThreadThen2() throws InterruptedException { 32 | //Создаем счетчик. 33 | final Count count = new Count(); 34 | //Создаем нити. 35 | Thread first = new ThreadCount(count); 36 | Thread second = new ThreadCount(count); 37 | 38 | //Запускаем нити. 39 | first.start(); 40 | second.start(); 41 | //Заставляем главную нить дождаться выполнения наших нитей. 42 | first.join(); 43 | second.join(); 44 | 45 | //Проверяем результат. 46 | assertThat(count.get(), is(2)); 47 | } 48 | 49 | } -------------------------------------------------------------------------------- /chapter_011/README.md: -------------------------------------------------------------------------------- 1 | ## Веб-приложение для управления пользователями 2 | 3 | В приложении реализована возможность авторизации и аутентификации по ролям в системе. 4 | Админ может создавать и редактировать всех пользователей, пользователь - только себя. 5 | + интерфейс `html` и `css` (`bootstrap`); 6 | + валидация введенных на стороне клиента данных с помощью `js`; 7 | + в форме создания и редактирования список городов заполняется динамически через `ajax`; 8 | + хранение данных `psql`. 9 | 10 | Страница авторизации: 11 | 12 | ![img](https://github.com/johnivo/job4j/blob/master/chapter_011/src/main/resources/signin.JPG) 13 | 14 | Список пользователей: 15 | 16 | ![img](https://github.com/johnivo/job4j/blob/master/chapter_011/src/main/resources/usersview.JPG) 17 | 18 | Создание пользователя: 19 | 20 | ![img](https://github.com/johnivo/job4j/blob/master/chapter_011/src/main/resources/create.JPG) 21 | 22 | Редактирование пользователя: 23 | 24 | ![img](https://github.com/johnivo/job4j/blob/master/chapter_011/src/main/resources/update.JPG) -------------------------------------------------------------------------------- /chapter_011/db/master.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /chapter_011/db/scripts/update_001.sql: -------------------------------------------------------------------------------- 1 | CREATE TABLE IF NOT EXISTS country ( 2 | id SERIAL PRIMARY KEY, 3 | name VARCHAR(32) 4 | ); 5 | 6 | CREATE TABLE IF NOT EXISTS city ( 7 | id SERIAL PRIMARY KEY, 8 | name VARCHAR(32), 9 | country_id INT REFERENCES country(id) ON UPDATE CASCADE ON DELETE CASCADE 10 | ); 11 | 12 | INSERT INTO country (name) VALUES 13 | ('Russia'), 14 | ('Belarus'); 15 | 16 | INSERT INTO city (name, country_id) VALUES 17 | ('Moscow', '1'), 18 | ('Vologda', '1'), 19 | ('Minsk', '2'), 20 | ('Brest', '2'); 21 | -------------------------------------------------------------------------------- /chapter_011/db/scripts/update_002.sql: -------------------------------------------------------------------------------- 1 | CREATE TABLE IF NOT EXISTS users ( 2 | id SERIAL PRIMARY KEY, 3 | name VARCHAR(64), 4 | login VARCHAR(64), 5 | email VARCHAR(64), 6 | createDate TIMESTAMP, 7 | photoId VARCHAR(128), 8 | password VARCHAR(32), 9 | role VARCHAR(32), 10 | city_id INT REFERENCES city(id) ON UPDATE CASCADE ON DELETE SET NULL 11 | ); 12 | -- SERIAL - целое число с автоувеличением 13 | 14 | INSERT INTO users (name, login, email, createDate, password, role, city_id) 15 | VALUES ('admin', 'admin', 'admin', '2019-11-26 00:00:00', 'admin', 'admin', 1), 16 | ('user', 'user', 'user', '2019-11-27 00:00:00', 'user', 'user', 2); -------------------------------------------------------------------------------- /chapter_011/src/main/java/ru/job4j/crud/datamodel/Role.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.crud.datamodel; 2 | 3 | import java.util.Objects; 4 | 5 | /** 6 | * Описывает модель роли. 7 | * 8 | * @author John Ivanov (johnivo@mail.ru) 9 | * @since 06.12.2019 10 | */ 11 | public class Role { 12 | 13 | private String role; 14 | 15 | public Role(String role) { 16 | this.role = role; 17 | } 18 | 19 | public String getRole() { 20 | return role; 21 | } 22 | 23 | public void setRole(String role) { 24 | this.role = role; 25 | } 26 | 27 | @Override 28 | public String toString() { 29 | return role; 30 | } 31 | 32 | @Override 33 | public boolean equals(Object o) { 34 | if (this == o) { 35 | return true; 36 | } 37 | if (o == null || getClass() != o.getClass()) { 38 | return false; 39 | } 40 | Role role1 = (Role) o; 41 | return role.equals(role1.role); 42 | } 43 | 44 | @Override 45 | public int hashCode() { 46 | return Objects.hash(role); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /chapter_011/src/main/java/ru/job4j/crud/logic/Validate.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.crud.logic; 2 | 3 | import ru.job4j.crud.datamodel.User; 4 | 5 | import java.util.List; 6 | 7 | /** 8 | * @author John Ivanov (johnivo@mail.ru) 9 | * @since 10.12.2019 10 | */ 11 | public interface Validate { 12 | 13 | Boolean add(User user); 14 | 15 | Boolean update(User user, Integer id); 16 | 17 | Boolean uploadImage(User user); 18 | 19 | Boolean delete(Integer id); 20 | 21 | List findAll(); 22 | 23 | User findById(int id); 24 | 25 | User findByLogin(String login); 26 | 27 | User isCredential(String login, String password); 28 | 29 | List getCountries(); 30 | 31 | List getCities(String country); 32 | } 33 | -------------------------------------------------------------------------------- /chapter_011/src/main/java/ru/job4j/crud/servlet/SignOutController.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.crud.servlet; 2 | 3 | import javax.servlet.ServletException; 4 | import javax.servlet.http.HttpServlet; 5 | import javax.servlet.http.HttpServletRequest; 6 | import javax.servlet.http.HttpServletResponse; 7 | import javax.servlet.http.HttpSession; 8 | import java.io.IOException; 9 | 10 | /** 11 | * @author John Ivanov (johnivo@mail.ru) 12 | * @since 09.12.2019 13 | */ 14 | public class SignOutController extends HttpServlet { 15 | 16 | /** 17 | * Обеспечивает выход пользователя из системы. 18 | * 19 | * Удаляем атрибут сессии login и выполняем редирект на страницу аутентификации. 20 | */ 21 | @Override 22 | protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 23 | 24 | HttpSession session = req.getSession(); 25 | session.removeAttribute("login"); 26 | req.getRequestDispatcher("/WEB-INF/views/signin.jsp").forward(req, resp); 27 | } 28 | 29 | } 30 | -------------------------------------------------------------------------------- /chapter_011/src/main/java/ru/job4j/crud/store/Store.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.crud.store; 2 | 3 | import ru.job4j.crud.datamodel.User; 4 | 5 | import java.util.List; 6 | 7 | /** 8 | * 9 | * Описывает хранилище пользователей 10 | * 11 | * @author John Ivanov (johnivo@mail.ru) 12 | * @since 15.11.2019 13 | */ 14 | public interface Store { 15 | 16 | void add(User user); 17 | 18 | void update(User user, Integer id); 19 | 20 | void delete(Integer id); 21 | 22 | List findAll(); 23 | 24 | User findById(int id); 25 | 26 | void uploadImage(User user); 27 | 28 | User findByLogin(String login); 29 | 30 | User isCredential(String login, String password); 31 | 32 | List getCountries(); 33 | 34 | List getCities(String country); 35 | } 36 | -------------------------------------------------------------------------------- /chapter_011/src/main/java/ru/job4j/servlets/PersonStorage.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.servlets; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | import java.util.concurrent.ConcurrentHashMap; 6 | import java.util.concurrent.atomic.AtomicInteger; 7 | 8 | /** 9 | * @author John Ivanov (johnivo@mail.ru) 10 | * @since 30.12.2019 11 | */ 12 | public class PersonStorage { 13 | 14 | private static final PersonStorage INSTANCE = new PersonStorage(); 15 | private final ConcurrentHashMap storage = new ConcurrentHashMap<>(); 16 | private final AtomicInteger id = new AtomicInteger(0); 17 | 18 | private PersonStorage() { 19 | this.add(new Person("test", "test", "test", "test", "test")); 20 | } 21 | 22 | public static PersonStorage getInstance() { 23 | return INSTANCE; 24 | } 25 | 26 | public boolean add(Person person) { 27 | person.setId(id.getAndIncrement()); 28 | return this.storage.put(person.getId(), person) == null; 29 | } 30 | 31 | public List findAll() { 32 | List result = new ArrayList<>(); 33 | result.addAll(this.storage.values()); 34 | return result; 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /chapter_011/src/main/resources/app.properties: -------------------------------------------------------------------------------- 1 | url=jdbc:postgresql://127.0.0.1:5432/users1 2 | username=postgres 3 | password=password 4 | driver-class-name=org.postgresql.Driver 5 | minIdle=5 6 | maxIdle=10 7 | maxOpenPreparedStatements=100 8 | changeLogFile=/db/master.xml -------------------------------------------------------------------------------- /chapter_011/src/main/resources/create.JPG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/johnivo/job4j/ca9c7eba9ee9a79d2c8b2deaaa5af06bff382dfe/chapter_011/src/main/resources/create.JPG -------------------------------------------------------------------------------- /chapter_011/src/main/resources/icon.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/johnivo/job4j/ca9c7eba9ee9a79d2c8b2deaaa5af06bff382dfe/chapter_011/src/main/resources/icon.jpg -------------------------------------------------------------------------------- /chapter_011/src/main/resources/signin.JPG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/johnivo/job4j/ca9c7eba9ee9a79d2c8b2deaaa5af06bff382dfe/chapter_011/src/main/resources/signin.JPG -------------------------------------------------------------------------------- /chapter_011/src/main/resources/update.JPG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/johnivo/job4j/ca9c7eba9ee9a79d2c8b2deaaa5af06bff382dfe/chapter_011/src/main/resources/update.JPG -------------------------------------------------------------------------------- /chapter_011/src/main/resources/usersview.JPG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/johnivo/job4j/ca9c7eba9ee9a79d2c8b2deaaa5af06bff382dfe/chapter_011/src/main/resources/usersview.JPG -------------------------------------------------------------------------------- /chapter_011/src/test/java/ru/job4j/crud/store/ConnectionRollback.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.crud.store; 2 | 3 | import java.lang.reflect.Proxy; 4 | import java.sql.Connection; 5 | import java.sql.SQLException; 6 | 7 | /** 8 | * @author John Ivanov (johnivo@mail.ru) 9 | * @since 27.11.2019 10 | */ 11 | public class ConnectionRollback { 12 | 13 | /** 14 | * Create connection with autocommit=false mode and rollback call, when conneciton is closed. 15 | * @param connection connection. 16 | * @return Connection object. 17 | * @throws SQLException possible exception. 18 | */ 19 | public static Connection create(Connection connection) throws SQLException { 20 | connection.setAutoCommit(false); 21 | return (Connection) Proxy.newProxyInstance( 22 | ConnectionRollback.class.getClassLoader(), 23 | new Class[] {Connection.class}, 24 | (proxy, method, args) -> { 25 | Object rsl = null; 26 | if ("close".equals(method.getName())) { 27 | connection.rollback(); 28 | connection.close(); 29 | } else { 30 | rsl = method.invoke(connection, args); 31 | } 32 | return rsl; 33 | } 34 | ); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /chapter_011/src/test/java/ru/job4j/crud/store/LocationStoreTest.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.crud.store; 2 | 3 | import org.junit.Test; 4 | 5 | import java.util.List; 6 | 7 | import static org.hamcrest.Matchers.is; 8 | import static org.junit.Assert.*; 9 | 10 | /** 11 | * @author John Ivanov (johnivo@mail.ru) 12 | * @since 09.01.2020 13 | */ 14 | public class LocationStoreTest { 15 | 16 | LocationStore locations = LocationStore.getInstance(); 17 | 18 | @Test 19 | public void whenAddCountryThanTrue() { 20 | locations.addCountry("Norway"); 21 | List result = locations.getCountries(); 22 | assertThat(result.contains("Norway"), is(true)); 23 | } 24 | 25 | @Test 26 | public void whenAddOneCityThenTrue() { 27 | locations.addCity("Finland", "Helsinki"); 28 | List cities = locations.getCities("Finland"); 29 | assertThat(locations.getCountries().contains("Finland"), is(true)); 30 | assertThat(cities.get(0), is("Helsinki")); 31 | } 32 | 33 | @Test 34 | public void whenChecksSizeOfUKStorageThanTwo() { 35 | locations.addCity("UK", "London"); 36 | locations.addCity("UK", "Liverpool"); 37 | List cities = locations.getCities("UK"); 38 | assertThat(cities.size(), is(2)); 39 | } 40 | 41 | } -------------------------------------------------------------------------------- /chess/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | junior 7 | ru.job4j 8 | 2.0 9 | 10 | 4.0.0 11 | chess 12 | jar 13 | 14 | 15 | -------------------------------------------------------------------------------- /chess/src/main/java/ru/job4j/chess/firuges/Cell.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.chess.firuges; 2 | 3 | public enum Cell { 4 | A1(0, 0), A2(0, 1), A3(0, 2), A4(0, 3), A5(0, 4), A6(0, 5), A7(0, 6), A8(0, 7), 5 | B1(1, 0), B2(1, 1), B3(1, 2), B4(1, 3), B5(1, 4), B6(1, 5), B7(1, 6), B8(1, 7), 6 | C1(2, 0), C2(2, 1), C3(2, 2), C4(2, 3), C5(2, 4), C6(2, 5), C7(2, 6), C8(2, 7), 7 | D1(3, 0), D2(3, 1), D3(3, 2), D4(3, 3), D5(3, 4), D6(3, 5), D7(3, 6), D8(3, 7), 8 | E1(4, 0), E2(4, 1), E3(4, 2), E4(4, 3), E5(4, 4), E6(4, 5), E7(4, 6), E8(4, 7), 9 | F1(5, 0), F2(5, 1), F3(5, 2), F4(5, 3), F5(5, 4), F6(5, 5), F7(5, 6), F8(5, 7), 10 | G1(6, 0), G2(6, 1), G3(6, 2), G4(6, 3), G5(6, 4), G6(6, 5), G7(6, 6), G8(6, 7), 11 | H1(7, 0), H2(7, 1), H3(7, 2), H4(7, 3), H5(7, 4), H6(7, 5), H7(7, 6), H8(7, 7); 12 | 13 | public final int x; 14 | public final int y; 15 | 16 | Cell(int x, int y) { 17 | this.x = x; 18 | this.y = y; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /chess/src/main/java/ru/job4j/chess/firuges/Figure.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.chess.firuges; 2 | 3 | public interface Figure { 4 | Cell position(); 5 | 6 | Cell[] way(Cell source, Cell dest); 7 | 8 | default String icon() { 9 | return String.format( 10 | "%s.png", this.getClass().getSimpleName() 11 | ); 12 | 13 | } 14 | 15 | Figure copy(Cell dest); 16 | 17 | } 18 | -------------------------------------------------------------------------------- /chess/src/main/java/ru/job4j/chess/firuges/FigureNotFoundException.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.chess.firuges; 2 | 3 | public class FigureNotFoundException extends RuntimeException { 4 | 5 | public FigureNotFoundException(String msg) { 6 | super(msg); 7 | } 8 | 9 | } 10 | -------------------------------------------------------------------------------- /chess/src/main/java/ru/job4j/chess/firuges/ImpossibleMoveException.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.chess.firuges; 2 | 3 | public class ImpossibleMoveException extends RuntimeException { 4 | 5 | public ImpossibleMoveException(String msg) { 6 | super(msg); 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /chess/src/main/java/ru/job4j/chess/firuges/King.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.chess.firuges; 2 | 3 | /** 4 | * Abstract class for the King. 5 | * 6 | *@author John Ivanov (johnivo@mail.ru) 7 | *@version $Id$ 8 | *@since 23.01.2018 9 | */ 10 | public abstract class King implements Figure { 11 | 12 | public boolean isKing(Cell source, Cell dest) { 13 | return ((Math.abs(source.y - dest.y) == 1) && (Math.abs(source.x - dest.x) == 0) 14 | || (Math.abs(source.y - dest.y) == 1) && (Math.abs(source.x - dest.x) == 1) 15 | || (Math.abs(source.y - dest.y) == 0) && (Math.abs(source.x - dest.x) == 1)); 16 | } 17 | 18 | public Cell[] kingWay(Cell source, Cell dest) { 19 | if (!isKing(source, dest)) { 20 | throw new ImpossibleMoveException("You can't walk like that. "); 21 | } 22 | return new Cell[] {dest}; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /chess/src/main/java/ru/job4j/chess/firuges/Knight.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.chess.firuges; 2 | 3 | /** 4 | * Abstract class for a Knight. 5 | * 6 | *@author John Ivanov (johnivo@mail.ru) 7 | *@version $Id$ 8 | *@since 23.01.2018 9 | */ 10 | public abstract class Knight implements Figure { 11 | 12 | public boolean isKnight(Cell source, Cell dest) { 13 | return ((Math.abs(source.y - dest.y) == 1) && (Math.abs(source.x - dest.x) == 2) 14 | || (Math.abs(source.y - dest.y) == 2) && (Math.abs(source.x - dest.x) == 1)); 15 | } 16 | 17 | public Cell[] knightWay(Cell source, Cell dest) { 18 | if (!isKnight(source, dest)) { 19 | throw new ImpossibleMoveException("You can't walk like that. "); 20 | } 21 | return new Cell[] {dest}; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /chess/src/main/java/ru/job4j/chess/firuges/OccupiedWayException.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.chess.firuges; 2 | 3 | public class OccupiedWayException extends RuntimeException { 4 | 5 | public OccupiedWayException(String msg) { 6 | super(msg); 7 | } 8 | 9 | } 10 | -------------------------------------------------------------------------------- /chess/src/main/java/ru/job4j/chess/firuges/Pawn.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.chess.firuges; 2 | 3 | /** 4 | * Abstract class for a Pawn. 5 | * 6 | *@author John Ivanov (johnivo@mail.ru) 7 | *@version $Id$ 8 | *@since 23.01.2018 9 | */ 10 | public abstract class Pawn implements Figure { 11 | 12 | public Cell[] pawnWayBlack(Cell source, Cell dest) { 13 | Cell[] steps; 14 | if (source.y == dest.y + 1 && source.x == dest.x) { 15 | steps = new Cell[] {dest}; 16 | } else { 17 | throw new ImpossibleMoveException("You can't walk like that. "); 18 | } 19 | return steps; 20 | } 21 | 22 | public Cell[] pawnWayWhite(Cell source, Cell dest) { 23 | Cell[] steps; 24 | if (source.y == dest.y - 1 && source.x == dest.x) { 25 | steps = new Cell[] {dest}; 26 | } else { 27 | throw new ImpossibleMoveException("You can't walk like that. "); 28 | } 29 | return steps; 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /chess/src/main/java/ru/job4j/chess/firuges/black/BishopBlack.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.chess.firuges.black; 2 | 3 | import ru.job4j.chess.firuges.Bishop; 4 | import ru.job4j.chess.firuges.Cell; 5 | import ru.job4j.chess.firuges.Figure; 6 | 7 | /** 8 | * 9 | * @author Petr Arsentev (parsentev@yandex.ru) 10 | * @version $Id$ 11 | * @since 0.1 12 | */ 13 | public class BishopBlack extends Bishop { 14 | private final Cell position; 15 | 16 | public BishopBlack(final Cell position) { 17 | this.position = position; 18 | } 19 | 20 | @Override 21 | public Cell position() { 22 | return this.position; 23 | } 24 | 25 | @Override 26 | public Cell[] way(Cell source, Cell dest) { 27 | return bishopWay(source, dest); 28 | } 29 | 30 | @Override 31 | public Figure copy(Cell dest) { 32 | return new BishopBlack(dest); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /chess/src/main/java/ru/job4j/chess/firuges/black/KingBlack.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.chess.firuges.black; 2 | 3 | import ru.job4j.chess.firuges.Cell; 4 | import ru.job4j.chess.firuges.Figure; 5 | import ru.job4j.chess.firuges.King; 6 | 7 | /** 8 | * 9 | * @author Petr Arsentev (parsentev@yandex.ru) 10 | * @version $Id$ 11 | * @since 0.1 12 | */ 13 | public class KingBlack extends King { 14 | private final Cell position; 15 | 16 | public KingBlack(final Cell position) { 17 | this.position = position; 18 | } 19 | 20 | @Override 21 | public Cell position() { 22 | return this.position; 23 | } 24 | 25 | @Override 26 | public Cell[] way(Cell source, Cell dest) { 27 | return kingWay(source, dest); 28 | } 29 | 30 | @Override 31 | public Figure copy(Cell dest) { 32 | return new KingBlack(dest); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /chess/src/main/java/ru/job4j/chess/firuges/black/KnightBlack.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.chess.firuges.black; 2 | 3 | import ru.job4j.chess.firuges.Cell; 4 | import ru.job4j.chess.firuges.Figure; 5 | import ru.job4j.chess.firuges.Knight; 6 | 7 | /** 8 | * 9 | * @author Petr Arsentev (parsentev@yandex.ru) 10 | * @version $Id$ 11 | * @since 0.1 12 | */ 13 | public class KnightBlack extends Knight { 14 | private final Cell position; 15 | 16 | public KnightBlack(final Cell position) { 17 | this.position = position; 18 | } 19 | 20 | @Override 21 | public Cell position() { 22 | return this.position; 23 | } 24 | 25 | @Override 26 | public Cell[] way(Cell source, Cell dest) { 27 | return knightWay(source, dest); 28 | } 29 | 30 | @Override 31 | public Figure copy(Cell dest) { 32 | return new KnightBlack(dest); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /chess/src/main/java/ru/job4j/chess/firuges/black/PawnBlack.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.chess.firuges.black; 2 | 3 | import ru.job4j.chess.firuges.Cell; 4 | import ru.job4j.chess.firuges.Figure; 5 | import ru.job4j.chess.firuges.Pawn; 6 | 7 | /** 8 | * 9 | * @author Petr Arsentev (parsentev@yandex.ru) 10 | * @version $Id$ 11 | * @since 0.1 12 | */ 13 | public class PawnBlack extends Pawn { 14 | private final Cell position; 15 | 16 | public PawnBlack(final Cell position) { 17 | this.position = position; 18 | } 19 | 20 | @Override 21 | public Cell position() { 22 | return this.position; 23 | } 24 | 25 | @Override 26 | public Cell[] way(Cell source, Cell dest) { 27 | return pawnWayBlack(source, dest); 28 | } 29 | 30 | @Override 31 | public Figure copy(Cell dest) { 32 | return new PawnBlack(dest); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /chess/src/main/java/ru/job4j/chess/firuges/black/QeenBlack.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.chess.firuges.black; 2 | 3 | import ru.job4j.chess.firuges.Cell; 4 | import ru.job4j.chess.firuges.Figure; 5 | import ru.job4j.chess.firuges.Qeen; 6 | 7 | /** 8 | * 9 | * @author Petr Arsentev (parsentev@yandex.ru) 10 | * @version $Id$ 11 | * @since 0.1 12 | */ 13 | public class QeenBlack extends Qeen { 14 | private final Cell position; 15 | 16 | public QeenBlack(final Cell position) { 17 | this.position = position; 18 | } 19 | 20 | @Override 21 | public Cell position() { 22 | return this.position; 23 | } 24 | 25 | @Override 26 | public Cell[] way(Cell source, Cell dest) { 27 | return qeenWay(source, dest); 28 | } 29 | 30 | @Override 31 | public Figure copy(Cell dest) { 32 | return new QeenBlack(dest); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /chess/src/main/java/ru/job4j/chess/firuges/black/RookBlack.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.chess.firuges.black; 2 | 3 | import ru.job4j.chess.firuges.Cell; 4 | import ru.job4j.chess.firuges.Figure; 5 | import ru.job4j.chess.firuges.Rook; 6 | 7 | /** 8 | * 9 | * @author Petr Arsentev (parsentev@yandex.ru) 10 | * @version $Id$ 11 | * @since 0.1 12 | */ 13 | public class RookBlack extends Rook { 14 | private final Cell position; 15 | 16 | public RookBlack(final Cell position) { 17 | this.position = position; 18 | } 19 | 20 | @Override 21 | public Cell position() { 22 | return this.position; 23 | } 24 | 25 | @Override 26 | public Cell[] way(Cell source, Cell dest) { 27 | return rookWay(source, dest); 28 | } 29 | 30 | @Override 31 | public Figure copy(Cell dest) { 32 | return new RookBlack(dest); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /chess/src/main/java/ru/job4j/chess/firuges/white/BishopWhite.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.chess.firuges.white; 2 | 3 | import ru.job4j.chess.firuges.Bishop; 4 | import ru.job4j.chess.firuges.Cell; 5 | import ru.job4j.chess.firuges.Figure; 6 | 7 | /** 8 | * 9 | * @author Petr Arsentev (parsentev@yandex.ru) 10 | * @version $Id$ 11 | * @since 0.1 12 | */ 13 | public class BishopWhite extends Bishop { 14 | private final Cell position; 15 | 16 | public BishopWhite(final Cell position) { 17 | this.position = position; 18 | } 19 | 20 | @Override 21 | public Cell position() { 22 | return this.position; 23 | } 24 | 25 | @Override 26 | public Cell[] way(Cell source, Cell dest) { 27 | return bishopWay(source, dest); 28 | } 29 | 30 | @Override 31 | public Figure copy(Cell dest) { 32 | return new BishopWhite(dest); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /chess/src/main/java/ru/job4j/chess/firuges/white/KingWhite.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.chess.firuges.white; 2 | 3 | import ru.job4j.chess.firuges.Cell; 4 | import ru.job4j.chess.firuges.Figure; 5 | import ru.job4j.chess.firuges.King; 6 | 7 | /** 8 | * 9 | * @author Petr Arsentev (parsentev@yandex.ru) 10 | * @version $Id$ 11 | * @since 0.1 12 | */ 13 | public class KingWhite extends King { 14 | private final Cell position; 15 | 16 | public KingWhite(final Cell position) { 17 | this.position = position; 18 | } 19 | 20 | @Override 21 | public Cell position() { 22 | return this.position; 23 | } 24 | 25 | @Override 26 | public Cell[] way(Cell source, Cell dest) { 27 | return kingWay(source, dest); 28 | } 29 | 30 | @Override 31 | public Figure copy(Cell dest) { 32 | return new KingWhite(dest); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /chess/src/main/java/ru/job4j/chess/firuges/white/KnightWhite.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.chess.firuges.white; 2 | 3 | import ru.job4j.chess.firuges.Cell; 4 | import ru.job4j.chess.firuges.Figure; 5 | import ru.job4j.chess.firuges.Knight; 6 | 7 | /** 8 | * 9 | * @author Petr Arsentev (parsentev@yandex.ru) 10 | * @version $Id$ 11 | * @since 0.1 12 | */ 13 | public class KnightWhite extends Knight { 14 | private final Cell position; 15 | 16 | public KnightWhite(final Cell position) { 17 | this.position = position; 18 | } 19 | 20 | @Override 21 | public Cell position() { 22 | return this.position; 23 | } 24 | 25 | @Override 26 | public Cell[] way(Cell source, Cell dest) { 27 | return knightWay(source, dest); 28 | } 29 | 30 | @Override 31 | public Figure copy(Cell dest) { 32 | return new KnightWhite(dest); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /chess/src/main/java/ru/job4j/chess/firuges/white/PawnWhite.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.chess.firuges.white; 2 | 3 | import ru.job4j.chess.firuges.Cell; 4 | import ru.job4j.chess.firuges.Figure; 5 | import ru.job4j.chess.firuges.Pawn; 6 | 7 | /** 8 | * 9 | * @author Petr Arsentev (parsentev@yandex.ru) 10 | * @version $Id$ 11 | * @since 0.1 12 | */ 13 | public class PawnWhite extends Pawn { 14 | private final Cell position; 15 | 16 | public PawnWhite(final Cell position) { 17 | this.position = position; 18 | } 19 | 20 | @Override 21 | public Cell position() { 22 | return this.position; 23 | } 24 | 25 | @Override 26 | public Cell[] way(Cell source, Cell dest) { 27 | return pawnWayWhite(source, dest); 28 | } 29 | 30 | @Override 31 | public Figure copy(Cell dest) { 32 | return new PawnWhite(dest); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /chess/src/main/java/ru/job4j/chess/firuges/white/QeenWhite.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.chess.firuges.white; 2 | 3 | import ru.job4j.chess.firuges.Cell; 4 | import ru.job4j.chess.firuges.Figure; 5 | import ru.job4j.chess.firuges.Qeen; 6 | 7 | /** 8 | * 9 | * @author Petr Arsentev (parsentev@yandex.ru) 10 | * @version $Id$ 11 | * @since 0.1 12 | */ 13 | public class QeenWhite extends Qeen { 14 | private final Cell position; 15 | 16 | public QeenWhite(final Cell position) { 17 | this.position = position; 18 | } 19 | 20 | @Override 21 | public Cell position() { 22 | return this.position; 23 | } 24 | 25 | @Override 26 | public Cell[] way(Cell source, Cell dest) { 27 | return qeenWay(source, dest); 28 | } 29 | 30 | @Override 31 | public Figure copy(Cell dest) { 32 | return new QeenWhite(dest); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /chess/src/main/java/ru/job4j/chess/firuges/white/RookWhite.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.chess.firuges.white; 2 | 3 | import ru.job4j.chess.firuges.Cell; 4 | import ru.job4j.chess.firuges.Figure; 5 | import ru.job4j.chess.firuges.Rook; 6 | 7 | /** 8 | * 9 | * @author Petr Arsentev (parsentev@yandex.ru) 10 | * @version $Id$ 11 | * @since 0.1 12 | */ 13 | public class RookWhite extends Rook { 14 | private final Cell position; 15 | 16 | public RookWhite(final Cell position) { 17 | this.position = position; 18 | } 19 | 20 | @Override 21 | public Cell position() { 22 | return this.position; 23 | } 24 | 25 | @Override 26 | public Cell[] way(Cell source, Cell dest) { 27 | return rookWay(source, dest); 28 | } 29 | 30 | @Override 31 | public Figure copy(Cell dest) { 32 | return new RookWhite(dest); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /chess/src/main/resources/BishopBlack.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/johnivo/job4j/ca9c7eba9ee9a79d2c8b2deaaa5af06bff382dfe/chess/src/main/resources/BishopBlack.png -------------------------------------------------------------------------------- /chess/src/main/resources/BishopWhite.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/johnivo/job4j/ca9c7eba9ee9a79d2c8b2deaaa5af06bff382dfe/chess/src/main/resources/BishopWhite.png -------------------------------------------------------------------------------- /chess/src/main/resources/KingBlack.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/johnivo/job4j/ca9c7eba9ee9a79d2c8b2deaaa5af06bff382dfe/chess/src/main/resources/KingBlack.png -------------------------------------------------------------------------------- /chess/src/main/resources/KingWhite.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/johnivo/job4j/ca9c7eba9ee9a79d2c8b2deaaa5af06bff382dfe/chess/src/main/resources/KingWhite.png -------------------------------------------------------------------------------- /chess/src/main/resources/KnightBlack.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/johnivo/job4j/ca9c7eba9ee9a79d2c8b2deaaa5af06bff382dfe/chess/src/main/resources/KnightBlack.png -------------------------------------------------------------------------------- /chess/src/main/resources/KnightWhite.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/johnivo/job4j/ca9c7eba9ee9a79d2c8b2deaaa5af06bff382dfe/chess/src/main/resources/KnightWhite.png -------------------------------------------------------------------------------- /chess/src/main/resources/PawnBlack.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/johnivo/job4j/ca9c7eba9ee9a79d2c8b2deaaa5af06bff382dfe/chess/src/main/resources/PawnBlack.png -------------------------------------------------------------------------------- /chess/src/main/resources/PawnWhite.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/johnivo/job4j/ca9c7eba9ee9a79d2c8b2deaaa5af06bff382dfe/chess/src/main/resources/PawnWhite.png -------------------------------------------------------------------------------- /chess/src/main/resources/QeenBlack.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/johnivo/job4j/ca9c7eba9ee9a79d2c8b2deaaa5af06bff382dfe/chess/src/main/resources/QeenBlack.png -------------------------------------------------------------------------------- /chess/src/main/resources/QeenWhite.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/johnivo/job4j/ca9c7eba9ee9a79d2c8b2deaaa5af06bff382dfe/chess/src/main/resources/QeenWhite.png -------------------------------------------------------------------------------- /chess/src/main/resources/RookBlack.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/johnivo/job4j/ca9c7eba9ee9a79d2c8b2deaaa5af06bff382dfe/chess/src/main/resources/RookBlack.png -------------------------------------------------------------------------------- /chess/src/main/resources/RookWhite.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/johnivo/job4j/ca9c7eba9ee9a79d2c8b2deaaa5af06bff382dfe/chess/src/main/resources/RookWhite.png -------------------------------------------------------------------------------- /cinema/README.md: -------------------------------------------------------------------------------- 1 | ## Сервис - кинотеатр 2 | 3 | Простое веб-приложение для онлайн-бронирования билетов в кино. 4 | 5 | Начальная страница: 6 | 7 | ![img](https://github.com/johnivo/job4j/blob/master/cinema/src/main/resources/booked.JPG) 8 | 9 | Страница оплаты: 10 | 11 | ![img](https://github.com/johnivo/job4j/blob/master/cinema/src/main/resources/payment.JPG) 12 | 13 | #### Использованные технологии: 14 | + Java 8 15 | + Apache Maven 16 | + Apache Tomcat 17 | + Servlet 3 18 | + Ajax JSON 19 | + JDBC 20 | + Liquibase 21 | + PostgreSQL 22 | + JUnit -------------------------------------------------------------------------------- /cinema/db/master.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /cinema/db/scripts/update_001.sql: -------------------------------------------------------------------------------- 1 | CREATE TABLE IF NOT EXISTS halls ( 2 | id SERIAL PRIMARY KEY, 3 | row INTEGER NOT NULL, 4 | place INTEGER NOT NULL, 5 | price INTEGER NOT NULL, 6 | booked BOOLEAN DEFAULT FALSE 7 | ); 8 | 9 | CREATE TABLE IF NOT EXISTS accounts ( 10 | id SERIAL PRIMARY KEY, 11 | username VARCHAR(128) NOT NULL, 12 | phone VARCHAR(32) NOT NULL, 13 | halls_id INTEGER REFERENCES halls(id) 14 | ); 15 | -------------------------------------------------------------------------------- /cinema/db/scripts/update_002.sql: -------------------------------------------------------------------------------- 1 | INSERT INTO halls (row, place, price) VALUES 2 | (1, 1, 500), (1, 2, 500), (1, 3, 500), (1, 4, 500), (1, 5, 500), 3 | (2, 1, 500), (2, 2, 500), (2, 3, 500), (2, 4, 500), (2, 5, 500), 4 | (3, 1, 400), (3, 2, 400), (3, 3, 400), (3, 4, 400), (3, 5, 400); -------------------------------------------------------------------------------- /cinema/src/main/java/ru/job4j/cinema/persistence/Store.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.cinema.persistence; 2 | 3 | import ru.job4j.cinema.model.Seat; 4 | import ru.job4j.cinema.model.User; 5 | 6 | import java.util.List; 7 | 8 | /** 9 | * @author John Ivanov (johnivo@mail.ru) 10 | * @since 03.02.2020 11 | */ 12 | public interface Store { 13 | 14 | List getSeats(); 15 | 16 | Seat getSeat(Seat seat); 17 | 18 | boolean makePayment(Seat seat, User user); 19 | 20 | } 21 | -------------------------------------------------------------------------------- /cinema/src/main/java/ru/job4j/cinema/service/Validate.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.cinema.service; 2 | 3 | import ru.job4j.cinema.model.Seat; 4 | import ru.job4j.cinema.model.User; 5 | 6 | import java.util.List; 7 | 8 | /** 9 | * @author John Ivanov (johnivo@mail.ru) 10 | * @since 03.02.2020 11 | */ 12 | public interface Validate { 13 | 14 | List getSeats(); 15 | 16 | void makePayment(Seat seat, User user); 17 | 18 | } 19 | -------------------------------------------------------------------------------- /cinema/src/main/resources/app.properties: -------------------------------------------------------------------------------- 1 | url=jdbc:postgresql://127.0.0.1:5432/cinema 2 | username=postgres 3 | password=password 4 | driver-class-name=org.postgresql.Driver 5 | minIdle=5 6 | maxIdle=10 7 | maxOpenPreparedStatements=100 8 | changeLogFile=/db/master.xml -------------------------------------------------------------------------------- /cinema/src/main/resources/booked.JPG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/johnivo/job4j/ca9c7eba9ee9a79d2c8b2deaaa5af06bff382dfe/cinema/src/main/resources/booked.JPG -------------------------------------------------------------------------------- /cinema/src/main/resources/payment.JPG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/johnivo/job4j/ca9c7eba9ee9a79d2c8b2deaaa5af06bff382dfe/cinema/src/main/resources/payment.JPG -------------------------------------------------------------------------------- /cinema/src/main/webapp/WEB-INF/web.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | HallController 14 | ru.job4j.cinema.controller.HallController 15 | 16 | 17 | HallController 18 | /hall 19 | 20 | 21 | -------------------------------------------------------------------------------- /deploy.sh: -------------------------------------------------------------------------------- 1 | #deploy script -------------------------------------------------------------------------------- /interview_questions/README.md: -------------------------------------------------------------------------------- 1 | ## Вопросы для интервью по темам [Job4j](https://job4j.ru/ "https://job4j.ru") 2 | 3 | + [Java Core](Core.md#core) 4 | + [OOP](OOP.md#oop) 5 | + [Collections. Lite](CollectionsLite.md#collections-lite) 6 | + [FP, Lambda, Stream API](FPLambdaStreamAPI.md#fp-lambda-stream-api) 7 | + [Collections. Pro](CollectionsPro.md#collections-pro) 8 | + [IO](IO.md#io) 9 | + [SQL, JDBC](SQL.md#sql) 10 | + [OOD](OOD.md#ood) 11 | + [Garbage Collection](GC.md#garbage-collection) 12 | + [Multithreading](Multithreading.md#multithreading) 13 | + [XML](XML.md#xml) 14 | + [Servlet](Servlet.md#servlet) 15 | + [JSP, JSTL](JSPJSTL.md#jspjstl) -------------------------------------------------------------------------------- /interview_questions/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | junior 7 | ru.job4j 8 | 2.0 9 | 10 | 4.0.0 11 | 12 | interview_questions 13 | 14 | 15 | -------------------------------------------------------------------------------- /interview_questions/src/main/resources/core_1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/johnivo/job4j/ca9c7eba9ee9a79d2c8b2deaaa5af06bff382dfe/interview_questions/src/main/resources/core_1.png -------------------------------------------------------------------------------- /interview_questions/src/main/resources/core_2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/johnivo/job4j/ca9c7eba9ee9a79d2c8b2deaaa5af06bff382dfe/interview_questions/src/main/resources/core_2.png -------------------------------------------------------------------------------- /interview_questions/src/main/resources/gc_4.1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/johnivo/job4j/ca9c7eba9ee9a79d2c8b2deaaa5af06bff382dfe/interview_questions/src/main/resources/gc_4.1.png -------------------------------------------------------------------------------- /interview_questions/src/main/resources/gc_4.2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/johnivo/job4j/ca9c7eba9ee9a79d2c8b2deaaa5af06bff382dfe/interview_questions/src/main/resources/gc_4.2.png -------------------------------------------------------------------------------- /interview_questions/src/main/resources/gc_4.3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/johnivo/job4j/ca9c7eba9ee9a79d2c8b2deaaa5af06bff382dfe/interview_questions/src/main/resources/gc_4.3.png -------------------------------------------------------------------------------- /interview_questions/src/main/resources/gc_6.1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/johnivo/job4j/ca9c7eba9ee9a79d2c8b2deaaa5af06bff382dfe/interview_questions/src/main/resources/gc_6.1.png -------------------------------------------------------------------------------- /interview_questions/src/main/resources/gc_7.1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/johnivo/job4j/ca9c7eba9ee9a79d2c8b2deaaa5af06bff382dfe/interview_questions/src/main/resources/gc_7.1.png -------------------------------------------------------------------------------- /interview_questions/src/main/resources/gc_7.2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/johnivo/job4j/ca9c7eba9ee9a79d2c8b2deaaa5af06bff382dfe/interview_questions/src/main/resources/gc_7.2.png -------------------------------------------------------------------------------- /interview_questions/src/main/resources/gc_7.3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/johnivo/job4j/ca9c7eba9ee9a79d2c8b2deaaa5af06bff382dfe/interview_questions/src/main/resources/gc_7.3.png -------------------------------------------------------------------------------- /interview_questions/src/main/resources/gc_7.4.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/johnivo/job4j/ca9c7eba9ee9a79d2c8b2deaaa5af06bff382dfe/interview_questions/src/main/resources/gc_7.4.png -------------------------------------------------------------------------------- /interview_questions/src/main/resources/gc_7.5.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/johnivo/job4j/ca9c7eba9ee9a79d2c8b2deaaa5af06bff382dfe/interview_questions/src/main/resources/gc_7.5.png -------------------------------------------------------------------------------- /interview_questions/src/main/resources/gc_7.6.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/johnivo/job4j/ca9c7eba9ee9a79d2c8b2deaaa5af06bff382dfe/interview_questions/src/main/resources/gc_7.6.png -------------------------------------------------------------------------------- /interview_questions/src/main/resources/gc_7.7.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/johnivo/job4j/ca9c7eba9ee9a79d2c8b2deaaa5af06bff382dfe/interview_questions/src/main/resources/gc_7.7.png -------------------------------------------------------------------------------- /interview_questions/src/main/resources/io_diagram.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/johnivo/job4j/ca9c7eba9ee9a79d2c8b2deaaa5af06bff382dfe/interview_questions/src/main/resources/io_diagram.gif -------------------------------------------------------------------------------- /interview_questions/src/main/resources/isp1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/johnivo/job4j/ca9c7eba9ee9a79d2c8b2deaaa5af06bff382dfe/interview_questions/src/main/resources/isp1.png -------------------------------------------------------------------------------- /interview_questions/src/main/resources/isp2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/johnivo/job4j/ca9c7eba9ee9a79d2c8b2deaaa5af06bff382dfe/interview_questions/src/main/resources/isp2.png -------------------------------------------------------------------------------- /interview_questions/src/main/resources/isp3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/johnivo/job4j/ca9c7eba9ee9a79d2c8b2deaaa5af06bff382dfe/interview_questions/src/main/resources/isp3.png -------------------------------------------------------------------------------- /interview_questions/src/main/resources/lsp1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/johnivo/job4j/ca9c7eba9ee9a79d2c8b2deaaa5af06bff382dfe/interview_questions/src/main/resources/lsp1.png -------------------------------------------------------------------------------- /interview_questions/src/main/resources/lsp2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/johnivo/job4j/ca9c7eba9ee9a79d2c8b2deaaa5af06bff382dfe/interview_questions/src/main/resources/lsp2.png -------------------------------------------------------------------------------- /interview_questions/src/main/resources/oop_1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/johnivo/job4j/ca9c7eba9ee9a79d2c8b2deaaa5af06bff382dfe/interview_questions/src/main/resources/oop_1.png -------------------------------------------------------------------------------- /interview_questions/src/main/resources/oop_2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/johnivo/job4j/ca9c7eba9ee9a79d2c8b2deaaa5af06bff382dfe/interview_questions/src/main/resources/oop_2.png -------------------------------------------------------------------------------- /interview_questions/src/main/resources/oop_3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/johnivo/job4j/ca9c7eba9ee9a79d2c8b2deaaa5af06bff382dfe/interview_questions/src/main/resources/oop_3.png -------------------------------------------------------------------------------- /interview_questions/src/main/resources/oop_4.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/johnivo/job4j/ca9c7eba9ee9a79d2c8b2deaaa5af06bff382dfe/interview_questions/src/main/resources/oop_4.png -------------------------------------------------------------------------------- /interview_questions/src/main/resources/pro_1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/johnivo/job4j/ca9c7eba9ee9a79d2c8b2deaaa5af06bff382dfe/interview_questions/src/main/resources/pro_1.png -------------------------------------------------------------------------------- /interview_questions/src/main/resources/pro_2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/johnivo/job4j/ca9c7eba9ee9a79d2c8b2deaaa5af06bff382dfe/interview_questions/src/main/resources/pro_2.png -------------------------------------------------------------------------------- /interview_questions/src/main/resources/solid.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/johnivo/job4j/ca9c7eba9ee9a79d2c8b2deaaa5af06bff382dfe/interview_questions/src/main/resources/solid.png -------------------------------------------------------------------------------- /interview_questions/src/main/resources/sql1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/johnivo/job4j/ca9c7eba9ee9a79d2c8b2deaaa5af06bff382dfe/interview_questions/src/main/resources/sql1.png -------------------------------------------------------------------------------- /interview_questions/src/main/resources/sql2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/johnivo/job4j/ca9c7eba9ee9a79d2c8b2deaaa5af06bff382dfe/interview_questions/src/main/resources/sql2.png -------------------------------------------------------------------------------- /interview_questions/src/main/resources/sql_joins.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/johnivo/job4j/ca9c7eba9ee9a79d2c8b2deaaa5af06bff382dfe/interview_questions/src/main/resources/sql_joins.png -------------------------------------------------------------------------------- /interview_questions/src/main/resources/srp1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/johnivo/job4j/ca9c7eba9ee9a79d2c8b2deaaa5af06bff382dfe/interview_questions/src/main/resources/srp1.png -------------------------------------------------------------------------------- /interview_questions/src/main/resources/srp2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/johnivo/job4j/ca9c7eba9ee9a79d2c8b2deaaa5af06bff382dfe/interview_questions/src/main/resources/srp2.png -------------------------------------------------------------------------------- /interview_questions/src/main/resources/srp3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/johnivo/job4j/ca9c7eba9ee9a79d2c8b2deaaa5af06bff382dfe/interview_questions/src/main/resources/srp3.png -------------------------------------------------------------------------------- /interview_questions/src/main/resources/srp4.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/johnivo/job4j/ca9c7eba9ee9a79d2c8b2deaaa5af06bff382dfe/interview_questions/src/main/resources/srp4.png -------------------------------------------------------------------------------- /puzzle/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | junior 7 | ru.job4j 8 | 2.0 9 | 10 | 4.0.0 11 | puzzle 12 | jar 13 | 14 | 15 | -------------------------------------------------------------------------------- /puzzle/src/main/java/ru/job4j/puzzle/firuges/Block.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.puzzle.firuges; 2 | 3 | public class Block implements Figure { 4 | private final Cell position; 5 | 6 | public Block(final Cell position) { 7 | this.position = position; 8 | } 9 | 10 | @Override 11 | public Cell position() { 12 | return this.position; 13 | } 14 | 15 | @Override 16 | public Cell[] way(Cell source, Cell dest) { 17 | return new Cell[0]; 18 | } 19 | 20 | @Override 21 | public Figure copy(Cell dest) { 22 | throw new IllegalStateException("Block could not move."); 23 | } 24 | 25 | @Override 26 | public boolean movable() { 27 | return false; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /puzzle/src/main/java/ru/job4j/puzzle/firuges/Cell.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.puzzle.firuges; 2 | 3 | import java.util.Objects; 4 | 5 | public class Cell { 6 | public final int x; 7 | public final int y; 8 | 9 | public Cell(int x, int y) { 10 | this.x = x; 11 | this.y = y; 12 | } 13 | 14 | @Override 15 | public boolean equals(Object o) { 16 | if (this == o) { 17 | return true; 18 | } 19 | if (o == null || getClass() != o.getClass()) { 20 | return false; 21 | } 22 | Cell cell = (Cell) o; 23 | return x == cell.x && y == cell.y; 24 | } 25 | 26 | @Override 27 | public int hashCode() { 28 | return Objects.hash(x, y); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /puzzle/src/main/java/ru/job4j/puzzle/firuges/Checker.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.puzzle.firuges; 2 | 3 | public class Checker implements Figure { 4 | private final Cell position; 5 | 6 | public Checker(final Cell position) { 7 | this.position = position; 8 | } 9 | 10 | @Override 11 | public Cell position() { 12 | return this.position; 13 | } 14 | 15 | @Override 16 | public Cell[] way(Cell source, Cell dest) { 17 | Cell[] steps = new Cell[0]; 18 | if ((Math.abs(source.x - dest.x) + Math.abs(source.y - dest.y)) == 1) { 19 | steps = new Cell[]{dest}; 20 | } 21 | return steps; 22 | } 23 | 24 | @Override 25 | public Figure copy(Cell dest) { 26 | return new Checker(dest); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /puzzle/src/main/java/ru/job4j/puzzle/firuges/Figure.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.puzzle.firuges; 2 | 3 | public interface Figure { 4 | default boolean movable() { 5 | return true; 6 | } 7 | 8 | Cell position(); 9 | 10 | Cell[] way(Cell source, Cell dest); 11 | 12 | default String icon() { 13 | return String.format( 14 | "%s.png", this.getClass().getSimpleName() 15 | ); 16 | 17 | } 18 | 19 | Figure copy(Cell dest); 20 | 21 | } 22 | -------------------------------------------------------------------------------- /puzzle/src/main/resources/Block.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/johnivo/job4j/ca9c7eba9ee9a79d2c8b2deaaa5af06bff382dfe/puzzle/src/main/resources/Block.png -------------------------------------------------------------------------------- /puzzle/src/main/resources/Checker.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/johnivo/job4j/ca9c7eba9ee9a79d2c8b2deaaa5af06bff382dfe/puzzle/src/main/resources/Checker.png -------------------------------------------------------------------------------- /tictactoe/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | junior 7 | ru.job4j 8 | 2.0 9 | 10 | 4.0.0 11 | tictactoe 12 | jar 13 | 14 | 15 | -------------------------------------------------------------------------------- /tictactoe/src/main/java/ru/job4j/tictactoe/Figure3T.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.tictactoe; 2 | 3 | import javafx.scene.shape.Rectangle; 4 | 5 | public class Figure3T extends Rectangle { 6 | private boolean markX = false; 7 | private boolean markO = false; 8 | 9 | public Figure3T() { 10 | } 11 | 12 | public Figure3T(boolean markX, boolean markO) { 13 | this.markX = markX; 14 | this.markO = markO; 15 | } 16 | 17 | public void take(boolean markX) { 18 | this.markX = markX; 19 | this.markO = !markX; 20 | } 21 | 22 | public boolean hasMarkX() { 23 | return this.markX; 24 | } 25 | 26 | public boolean hasMarkO() { 27 | return this.markO; 28 | } 29 | } -------------------------------------------------------------------------------- /vacancy_parser/db/master.xml: -------------------------------------------------------------------------------- 1 | 2 | 8 | 9 | -------------------------------------------------------------------------------- /vacancy_parser/db/scripts/update_001.sql: -------------------------------------------------------------------------------- 1 | CREATE TABLE IF NOT EXISTS Vacancy (id serial primary key, name varchar(512), description text, link varchar(2048), created timestamp); -------------------------------------------------------------------------------- /vacancy_parser/src/main/java/ru/job4j/parser/MainParser.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.parser; 2 | 3 | import org.jsoup.helper.Validate; 4 | 5 | /** 6 | * Запуск приложения. 7 | * 8 | * @author John Ivanov (johnivo@mail.ru) 9 | * @since 03.07.2019 10 | */ 11 | public class MainParser { 12 | 13 | public static void main(String[] args) { 14 | Validate.isTrue(args.length < 1, "fill properties"); 15 | ParserJob pj = new ParserJob(); 16 | pj.run(); 17 | } 18 | 19 | } 20 | -------------------------------------------------------------------------------- /vacancy_parser/src/main/resources/app.properties: -------------------------------------------------------------------------------- 1 | url=jdbc:postgresql://127.0.0.1:5432/vacancy_parser1 2 | username=postgres 3 | password=password 4 | driver-class-name=org.postgresql.Driver 5 | cron.time=0 0/2 * 1/1 * ? * 6 | json.url=https://www.sql.ru/forum/job-offers/ -------------------------------------------------------------------------------- /vacancy_parser/src/main/resources/log4j2.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /vacancy_parser/src/test/java/ru/job4j/parser/ConnectionRollback.java: -------------------------------------------------------------------------------- 1 | package ru.job4j.parser; 2 | 3 | import java.lang.reflect.Proxy; 4 | import java.sql.Connection; 5 | import java.sql.SQLException; 6 | 7 | /** 8 | * @author John Ivanov (johnivo@mail.ru) 9 | * @since 23.09.2019 10 | */ 11 | public class ConnectionRollback { 12 | 13 | /** 14 | * Create connection with autocommit=false mode and rollback call, when conneciton is closed. 15 | * @param connection connection. 16 | * @return Connection object. 17 | * @throws SQLException possible exception. 18 | */ 19 | public static Connection create(Connection connection) throws SQLException { 20 | connection.setAutoCommit(false); 21 | return (Connection) Proxy.newProxyInstance( 22 | ConnectionRollback.class.getClassLoader(), 23 | new Class[] {Connection.class}, 24 | (proxy, method, args) -> { 25 | Object rsl = null; 26 | if ("close".equals(method.getName())) { 27 | connection.rollback(); 28 | connection.close(); 29 | } else { 30 | rsl = method.invoke(connection, args); 31 | } 32 | return rsl; 33 | } 34 | ); 35 | } 36 | 37 | } 38 | --------------------------------------------------------------------------------