├── CapitalizeWords.java ├── HorizontalChart.java ├── JSoupValidateAndSum.java ├── NinetyNineBottles.java ├── PropsEnv.java ├── README.md ├── ReadTodosEx.java ├── RemoveStringSpaces.java ├── ResourceBundleEx.java ├── RomanNumeralsEx.java ├── UniqueNames.java ├── algorithms ├── FactorialEx.java ├── FibonacciLoopEx.java ├── FibonacciRecursiveEx.java ├── FibonacciRecursiveEx2.java ├── FibonacciStreamEx.java ├── FindMax.java ├── Palindrome.java ├── Palindrome2.java ├── Palindrome3.java ├── Palindrome4.java ├── RecursionEx.java ├── ReverseInteger.java ├── ReverseInteger2.java ├── ReverseInteger3.java ├── ReverseInteger4.java ├── ReverseInteger5.java └── sorting │ ├── BubbleSortEx.java │ ├── BucketSortEx.java │ ├── InsertionSortEx.java │ └── SelectionSortEx.java ├── apps ├── commandline │ ├── JavaStatsEx.java │ ├── MyStatsApp.java │ ├── README.md │ ├── data.txt │ └── pom.xml ├── gui │ └── QuitButtonEx.java ├── test │ └── classic.md └── web │ ├── ReadWebpage.java │ ├── WebPageReader.java │ ├── context.xml │ ├── index.html │ └── pom.xml ├── arrays ├── AccessElements.java ├── AccessElements2.java ├── ArrayCopy.java ├── ArrayMethods.java ├── ArraySearch.java ├── ArraySetAll.java ├── ArraySortPrimitive.java ├── ArraySortWrapper.java ├── ArraySplitIterator.java ├── ArrayToList.java ├── ArrayToString.java ├── ComparingArrays.java ├── CopyImage.java ├── DownloadImage.java ├── HexadecimalOutput.java ├── InitArray.java ├── InitArray2.java ├── InitArray3.java ├── InitArray4.java ├── IrregularArrays.java ├── ListToArray.java ├── PassingArray.java ├── ReadAllBytesEx.java ├── ThreeDimensions.java ├── TraversingArrays.java ├── TwoDimensions.java ├── VowelsConsonantsEx.java ├── ball.png ├── sid.jpg └── thermopylae.txt ├── async ├── README.md ├── RunTasksCompletableFuture.java ├── RunTasksParrallel.java ├── RunTasksSequentially.java ├── asyncdb │ ├── AsyncDatabase.java │ └── pom.xml ├── completablefuture │ ├── CombineCompletedWithAsyncFuture.java │ ├── GetBlocking.java │ ├── RunAfterEitherAsync.java │ ├── RunBlocking.java │ ├── TheyApply.java │ └── WebsiteStatus.java └── future-vs-completablefuture │ ├── CompletableFutureEx.java │ └── FutureEx.java ├── cdi ├── README.md ├── autodiscovery │ ├── Autodiscovery.java │ ├── TextService.java │ ├── TimeService.java │ └── pom.xml ├── event │ ├── CdiEventEx.java │ ├── NotifyBoard.java │ ├── TextModify.java │ ├── TextService.java │ └── pom.xml ├── named │ ├── ConsoleMessageRenderer.java │ ├── FileMessageRenderer.java │ ├── HelloMessageProvider.java │ ├── MessageProvider.java │ ├── MessageRenderer.java │ ├── NamedEx.java │ ├── TimeMessageProvider.java │ └── pom.xml ├── producer │ ├── ConsoleMessageRenderer.java │ ├── HelloMessageProvider.java │ ├── Message.java │ ├── MessageFactory.java │ ├── MessageProvider.java │ ├── MessageRenderer.java │ ├── MessageType.java │ ├── ProducerEx.java │ ├── TimeMessageProvider.java │ ├── application.properties │ └── pom.xml ├── simple │ ├── CdiSimple.java │ ├── ConsoleMessageRenderer.java │ ├── HelloMessageProvider.java │ ├── MessageProvider.java │ ├── pom.xml │ └── simplelogger.properties └── undertowweld │ ├── AppConfig.java │ ├── HelloMessage.java │ ├── MessageResource.java │ ├── UndertowWeldEx.java │ ├── beans.xml │ └── pom.xml ├── collections ├── arraylist │ ├── AddAll.java │ ├── ContainsElement.java │ ├── FilterList.java │ ├── GetAndSize.java │ ├── GetIndex.java │ ├── ListCopy.java │ ├── ListInit.java │ ├── ListOfLists.java │ ├── ListSort.java │ ├── ListSort2.java │ ├── ListToArray.java │ ├── ModifyList.java │ ├── Person.java │ ├── RemoveAll.java │ ├── RemoveIf.java │ ├── ReplaceAll.java │ ├── ReplaceAll2.java │ ├── RetainAll.java │ ├── SubList.java │ ├── ToList.java │ └── TraverseList.java ├── eclipse-collections.md ├── hashmap │ ├── CountingWordsEx.java │ ├── HashMapClear.java │ ├── HashMapContainsKey.java │ ├── HashMapConvertToList.java │ ├── HashMapEnhancedFor.java │ ├── HashMapFilter.java │ ├── HashMapForEach.java │ ├── HashMapInit.java │ ├── HashMapInit2.java │ ├── HashMapKeys.java │ ├── HashMapReplace.java │ ├── HashMapRetrieve.java │ ├── HashMapSize.java │ ├── HashMapValues.java │ └── thermopylae.txt └── stack │ └── Palindrome.java ├── comparesort ├── ArrayBubbleSortEx.java ├── ArrayBucketSortEx.java ├── ArraysSortEx.java ├── ArraysSortEx2.java ├── ArraysSortObjectsEx.java ├── ArraysSortObjectsEx2.java ├── ArraysSortStringsEx.java ├── CompareListsApacheCollsEx.java ├── CompareListsEx.java ├── CompareListsEx2.java ├── CompareListsEx3.java ├── CompareListsEx4.java ├── CompareListsWithHashSetEx.java ├── ListSortByFields.java ├── ListSortCards.java ├── ListSortCards2.java ├── ListSortCustomComparatorEx.java ├── ListSortDouble.java ├── ListSortEx.java ├── ListSortIntegers.java ├── ListSortIntegers2.java ├── ListSortMultiple.java ├── ListSortSurname.java └── comparable_comparator.txt ├── concurrency ├── AtomicBooleanEx.java ├── AtomicLongEx.java ├── AtomicLongEx2.java ├── CallableEx.java ├── DirectoryWatcherEx.java ├── FutureCancelEx.java ├── FutureIsDoneEx.java ├── InvokeAllEx.java ├── IvokeAnyEx.java ├── JoinEx.java ├── MessageSender.java ├── MultipleThreadsEx.java ├── README.md ├── ReadWebPageEx.java ├── ScheduledExecutorServiceEx.java ├── SearchingImagesEx.java ├── SimpleThreadEx.java ├── SimpleThreadEx2.java ├── SleepEx.java ├── SplashScreenEx.java ├── SupervisorWorkerEx.java ├── SynchronizedCounter.java └── factorial │ ├── FactorialCalculator.java │ └── FactorialCalculatorEx.java ├── conversions ├── AutoboxingEx.java ├── AutoboxingEx2.java ├── AutoboxingEx3.java ├── BoxingUnboxingEx.java ├── ConversionsEx.java ├── IntegerWrapperEx.java ├── NullTypeEx.java └── NumbersEx.java ├── csv ├── OpenCSVReadEx.java ├── OpenCSVReadEx2.java ├── OpenCSVWriteEx.java ├── OpenCSVWriteEx2.java ├── Readme.md ├── mysql │ ├── OpenCSVDatabaseEx.java │ └── cars_mysql.sql ├── numbers.csv ├── readbeans │ ├── Car.java │ ├── OpenCSVReadBeansEx.java │ └── cars.csv ├── readbeans2 │ ├── Car.java │ ├── OpenCSVReadBeansEx2.java │ └── cars.csv └── writebeans │ ├── Car.java │ └── OpenCSVWriteBeansEx.java ├── datetime ├── IslamicDateEx.java ├── JavaBratislavaMoscowTime.java ├── JavaCurrentDateTime.java ├── JavaCustomTemporalAdjusterEx.java ├── JavaCustomTemporalAdjusterEx2.java ├── JavaDateCurrentEx.java ├── JavaDateTimeArithmeticEx.java ├── JavaDateTimeFormat.java ├── JavaGregorianCalendarEx.java ├── JavaInstantEx.java ├── JavaJulianDayEx.java ├── JavaParseDateTime.java ├── JavaTemporalAdjustersEx.java └── JavaUnixTimeEx.java ├── fun-streams ├── DirectoryStreamFilterEx.java ├── FibonacciStreamEx.java ├── FilesListCount.java ├── HashMap2Objects.java ├── JavaStreamRandomIntegers.java ├── PatternCompileEx.java ├── WordFreqEx.java ├── collect │ ├── CustomCollector.java │ ├── JavaCollectAndThenEx.java │ ├── JavaCollectCountEx.java │ ├── JavaCollectJoinEx.java │ ├── JavaCollectMinMaxEx.java │ ├── JavaCollectToListEx.java │ ├── JavaCollectToMapEx.java │ ├── JavaCollectToMapEx2.java │ ├── JavaCollectToSetEx.java │ ├── README.md │ ├── ReverseInteger.java │ ├── groupby │ │ ├── JavaCollectGroupByCategory.java │ │ ├── JavaCollectGroupByEx.java │ │ └── Product.java │ ├── groupby2 │ │ ├── JavaCollectGroupByCategoryPrice.java │ │ └── Product.java │ ├── partition │ │ ├── JavaCollectPartitionByEx.java │ │ └── User.java │ └── sum │ │ ├── Cat.java │ │ ├── JavaCollectSumAgeEx.java │ │ ├── JavaCollectSumEvenValsEx.java │ │ ├── JavaCollectSumEx.java │ │ └── JavaCollectSumStringValsEx.java ├── filter │ ├── JavaStreamFilterMapByKeys.java │ ├── JavaStreamFilterMapByValues.java │ ├── JavaStreamFilterObjects.java │ ├── JavaStreamFilterRemoveNulls.java │ ├── JavaStreamFilterStringLength.java │ ├── JavaStreamMultipleFilters.java │ └── User.java ├── gatherers.md ├── map.md ├── reduce.md └── the-king-james-bible.txt ├── functional ├── BiConsumerAndThen.java ├── BiConsumerEx.java ├── BiFunctionAndThen.java ├── BiFunctionEx.java ├── BiPredicateEx.java ├── BinaryOperatorEx.java ├── BinaryOperatorEx2.java ├── CollectorEx.java ├── ComparatorEx.java ├── ConsumerEx.java ├── ConsumerEx2.java ├── ConsumerEx3.java ├── ConsumerEx4.java ├── ConsumerEx5.java ├── ConsumerEx6.java ├── Country.java ├── CustomFunctionalInterface.java ├── FunctionEx3.java ├── IntPredicateEx.java ├── IntPredicateEx2.java ├── PredicateCompose.java ├── PredicateEx.java ├── PredicateEx2.java ├── PredicateEx3.java ├── PredicateNegate.java ├── SupplierEx.java ├── SupplierEx2.java ├── SupplierEx3.java ├── SupplierEx4.java ├── UnaryOperatorEx.java ├── function.md └── functional_iterface.md ├── generics ├── ConsumerForEachEx.java ├── GenericArray2ListEx.java ├── GenericBoundedEx.java ├── GenericConcatListEx.java ├── GenericMethodEx.java ├── GenericRandomValEx.java └── GenericWildcardEx.java ├── gradle.md ├── hash_code.md ├── intellij.md ├── io ├── ByteArrayInputStreamEx.java ├── DiskInfoEx.java ├── JavaPropertiesEx.java ├── JavaReadResourceEx.java ├── JavaReadResourceEx2.java ├── README.md ├── RandomAccessFileEx.java ├── ReadWrite.java ├── channel │ ├── ChannelCopy.java │ ├── DownloadFileEx.java │ ├── FileChannelWrite.java │ ├── SevenByteBufferChannel.java │ ├── TransferBytes.java │ ├── beginning.txt │ └── data1.txt ├── copyfile │ ├── CopyFileChannel.java │ ├── CopyFileJava7.java │ ├── CopyFileStream.java │ ├── CopyFileStream2.java │ └── bugs.txt ├── db.properties ├── directorystream │ ├── DirectoryStreamFilterEx.java │ ├── DirectoryStreamGlobEx.java │ └── DirectoryStreamRecursiveEx.java ├── file │ ├── JavaCopyFile.java │ ├── JavaCreateFile.java │ ├── JavaDeleteFile.java │ ├── JavaFileSize.java │ ├── JavaGetFileOwner.java │ ├── JavaMoveFile.java │ ├── JavaReadFile.java │ ├── JavaWriteFile.java │ └── bugs.txt ├── fileslist │ ├── FilesListCount.java │ ├── FilesListDirectories.java │ ├── FilesListEx.java │ └── FilesListExtension.java ├── fileswalk │ ├── FilesWalkDirectoriesEx.java │ ├── FilesWalkFileExtensionEx.java │ └── FilesWalkRegularFilesEx.java ├── filewatcher │ ├── DirWatcherEx.java │ └── DirWatcherThread.java ├── input.md ├── readtext.md ├── readtext │ ├── FileChannelEx.java │ ├── InputStreamReaderEx.java │ ├── InputStreamReaderEx2.java │ ├── README.md │ ├── ReadAllBytesEx.java │ └── thermopylae.txt ├── simplefilevisitor │ ├── FileVisitorFindDirsEx.java │ ├── datemodified │ │ ├── FileVisitorDateModifiedEx.java │ │ └── MyDateModifiedVisitor.java │ ├── deletesubtree │ │ ├── FileVisitorDeleteSubTree.java │ │ └── MyFileVisitor.java │ ├── filesize │ │ ├── FileVisitorSizeEx.java │ │ └── MyFileSizeVisitor.java │ └── skipdirectory │ │ ├── FileVisitorSkipEx.java │ │ └── MyTextFileVisitor.java ├── streams │ ├── filestream │ │ ├── FileInputStreamEx.java │ │ ├── FileInputStreamEx2.java │ │ ├── FileInputStreamEx3.java │ │ ├── FileInputStreamEx4.java │ │ ├── FileOutputStreamAppend.java │ │ ├── FileOutputStreamEnconding.java │ │ ├── FileOutputStreamEx.java │ │ └── JavaFileWriterEx.java │ ├── inputstream │ │ ├── Country.java │ │ ├── JavaInputStreamBytes.java │ │ ├── JavaInputStreamObjects.java │ │ ├── JavaInputStreamText.java │ │ ├── JavaInputStreamURL.java │ │ ├── JavaObjectOutputStreamEx.java │ │ ├── ball.png │ │ └── thermopylae.txt │ └── inputstreamreader │ │ ├── JavaInputStreamReaderEx.java │ │ ├── JavaInputStreamReaderEx2.java │ │ ├── JavaInputStreamReaderEx3.java │ │ ├── ProcessBuilderEnvEx2.java │ │ ├── ProcessBuilderEx.java │ │ ├── ProcessBuilderRedirectEx.java │ │ └── russiantext.txt └── words.txt ├── iteration ├── ClassicForEx.java ├── EnhancedForLoopEx.java ├── HashMapEnhancedForEx.java ├── HashMapForEachEx.java ├── HashMapIteratorEx.java ├── ListForEachEx.java ├── ListIteratorEx.java └── foreach │ ├── ForEachArray.java │ ├── ForEachConsSpec.java │ ├── ForEachConsumer.java │ ├── ForEachFilterList.java │ ├── ForEachListLambda.java │ ├── ForEachMap.java │ ├── ForEachMap2.java │ └── ForEachSet.java ├── jdbc ├── DBUtils.java ├── DerbyBatchUpdates.java ├── DerbyColumnHeaders.java ├── DerbyDataSourceEx.java ├── DerbyDataSourceEx2.java ├── DerbyNoTransaction.java ├── DerbyReadImage.java ├── DerbySelectAllCarsEx.java ├── DerbySelectAllCarsPropertiesEx.java ├── DerbySqlExportCsvEx.java ├── DerbySqlInsertEx.java ├── DerbySqlSelectCarEx.java ├── DerbyTransaction.java ├── DerbyWriteImage.java ├── authors_books.sql ├── cars_derby.sql ├── db.properties └── images_derby.sql ├── json ├── gson │ ├── GsonBuilderEx.java │ ├── GsonDataBindApiRead.java │ ├── GsonDataBindApiWrite.java │ ├── GsonExcludeFileds.java │ ├── GsonFromJson.java │ ├── GsonPrettyPrinting.java │ ├── GsonReadArray.java │ ├── GsonReadList.java │ ├── GsonReadWebPage.java │ ├── GsonSerializeNulls.java │ ├── GsonStreamApiRead.java │ ├── GsonStreamApiWrite.java │ ├── GsonToJson.java │ ├── GsonTreeModelRead.java │ ├── GsonTreeModelWrite.java │ ├── GsonWriteList.java │ ├── README.md │ ├── cars.json │ ├── items.json │ └── users.json └── jsonp │ ├── JsonArrayBuilderEx.java │ ├── JsonGeneratorEx.java │ ├── JsonObjectBuilderEx.java │ ├── JsonObjectBuilderEx2.java │ ├── JsonParserEx.java │ ├── JsonParserSimpleEx.java │ ├── JsonPrettyPrintEx.java │ ├── README.md │ ├── User.java │ └── users.json ├── junit5 ├── README.md ├── beforeall │ ├── Application.java │ ├── MathUtils.java │ └── MathUtilsTest.java ├── beforeeach │ ├── Application.java │ ├── ColorBag.java │ └── ColorBagTest.java ├── csvfilesource │ ├── Application.java │ ├── MathUtils.java │ ├── MathUtilsTest.java │ └── test-data.csv ├── parameterized │ ├── Application.java │ ├── StringUtils.java │ └── StringUtilsTest.java ├── repeatedtest │ ├── Application.java │ ├── MySelectionSort.java │ └── MySelectionSortTest.java └── selenium │ ├── README.md │ ├── TestPageSource.java │ └── TestTitle.java ├── lambda ├── JavaLambdaEx.java ├── JavaLambdaEx2.java ├── JavaLambdaEx3.java ├── JavaLambdaEx4.java ├── JavaLambdaEx5.java ├── JavaLambdaEx6.java ├── MethodReferenceEx.java ├── MethodReferenceEx2.java ├── QuitButtonEx.java ├── User.java ├── constructorreference │ ├── Cat.java │ ├── CatFactory.java │ └── ConstructorReferenceEx.java └── lambda.md ├── maven.md ├── mockito ├── README.md ├── argumentcaptor │ ├── ArgumentCaptorEx.java │ ├── MessageService.java │ └── MessageServiceTest.java ├── callorder │ ├── CallOrder.java │ ├── TimeService.java │ └── TimeServiceTest.java ├── helloservice │ ├── HelloService.java │ ├── HelloServiceTest.java │ └── SimpleEx.java ├── nofcalls │ ├── MessageService.java │ ├── MessageServiceTest.java │ └── VerifyNumberOfCalls.java ├── pom.xml └── throwexception │ ├── StringUtils.java │ ├── StringUtilsTest.java │ └── ThrowException.java ├── modern-java ├── README.md └── deprecated.md ├── mongodb ├── MongoCollectionFromJSON.java ├── MongoCommand.java ├── MongoCreateCollection.java ├── MongoFilter.java ├── MongoListCollections.java ├── MongoModify.java ├── MongoProjection.java ├── MongoReadAll.java ├── MongoReadGreaterThan.java ├── MongoSkipLimit.java └── README.md ├── net ├── README.md ├── channel │ └── DownloadFileEx.java ├── downloadimage │ ├── DownloadImageChannel.java │ └── DownloadImageImageIO.java ├── socket │ ├── DatagramSocketEx.java │ ├── DateServer.java │ ├── README.md │ ├── SocketGetRequest.java │ ├── SocketHeadRequest.java │ ├── SocketTimeClient.java │ ├── WhoisClientEx.java │ └── clientserver │ │ ├── ReverseClient.java │ │ └── ReverseServer.java └── uri.md ├── optional.md ├── patterns ├── builder │ ├── BuilderPatternEx.java │ ├── Task.java │ └── TaskBuilder.java └── factory │ ├── Cat.java │ ├── Dog.java │ ├── FactoryMethodPatternEx.java │ ├── Parrot.java │ ├── Pet.java │ └── PetFactory.java ├── pitfalls ├── Associativity.java ├── IncrementOperator.java ├── IntegerEqual.java ├── ListRemoveElement.java ├── ListRemoveNullVals.java ├── StringEqual.java └── StringIntern.java ├── regex ├── JavaRegexAlternation.java ├── JavaRegexAnchor.java ├── JavaRegexCaseInsensitive.java ├── JavaRegexCurrency.java ├── JavaRegexEmail.java ├── JavaRegexEx.java ├── JavaRegexExpressions.java ├── JavaRegexGroups.java ├── JavaRegexImplicitWordBoundaries.java ├── JavaRegexReplacingStrings.java ├── JavaRegexSplitText.java ├── JavaRegexSubpatterns.java ├── JavaRegexWordBoundaries.java ├── WordFreqEx.java ├── data.csv └── the-king-james-bible.txt ├── resteasy ├── README.md ├── context │ ├── AppConfig.java │ ├── ContextEx.java │ ├── InfoResource.java │ ├── beans.xml │ └── pom.xml ├── hello │ ├── AppConfig.java │ ├── HelloEx.java │ ├── HelloResource.java │ ├── beans.xml │ └── pom.xml ├── jsonres │ ├── AppConfig.java │ ├── City.java │ ├── CityResource.java │ ├── CityService.java │ ├── ICityService.java │ ├── JSonEx.java │ ├── beans.xml │ └── pom.xml ├── pathparam │ ├── AppConfig.java │ ├── PathParamEx.java │ ├── ReverseResource.java │ ├── beans.xml │ └── pom.xml ├── queryparam │ ├── AppConfig.java │ ├── MessageResource.java │ ├── QueryParamEx.java │ ├── beans.xml │ └── pom.xml ├── uploadfile │ ├── AppConfig.java │ ├── FileUploadForm.java │ ├── FileUploadService.java │ ├── README.md │ ├── UploadFileEx.java │ ├── index.html │ └── pom.xml └── weburl │ ├── AppConfig.java │ ├── README.md │ ├── UrlInfoRes.java │ ├── WebUrlEx.java │ ├── beans.xml │ └── pom.xml ├── springboot └── jpa │ └── onetomany │ ├── Application.java │ ├── Employee.java │ ├── EmployeeRepository.java │ ├── MyRunner.java │ ├── Task.java │ ├── TaskRepository.java │ ├── application.properties │ └── pom.xml ├── strings ├── Base64MimeEncoder.java ├── Base64Wrap.java ├── ConcatStrings.java ├── ConcatenateStrings.java ├── Conversions.java ├── CountingWords.java ├── GetBytes.java ├── MutableImmutableEx.java ├── PrecisionSpecifier.java ├── README.md ├── SplitStringGuavaEx.java ├── SplitStringLimitEx.java ├── StringBuilderAppendEx.java ├── StringBuilderElements.java ├── StringElements.java ├── StringEnds.java ├── StringLength.java ├── StringLines.java ├── StringMatch.java ├── StringStarts.java ├── WidthSpecifier.java ├── favicon.ico └── thermopylae.txt ├── tasks └── fizz_buzz.md ├── templates ├── README.md └── emailsfreemarker │ ├── Application.java │ ├── Customer.java │ ├── customers.csv │ └── emails.ftl ├── types ├── enum.md └── record.md ├── validation ├── EmailEx.java ├── NotNullEx.java ├── PastDate.java ├── PositiveValues.java ├── README.md ├── ValidateValue.java ├── customconstraint │ ├── checkcase │ │ ├── CaseMode.java │ │ ├── CheckCase.java │ │ ├── CheckCaseConstraint.java │ │ ├── CheckCaseValidator.java │ │ └── ValidationMessages.properties │ └── localelang │ │ ├── CustomConstraint.java │ │ ├── LocaleLang.java │ │ └── LocaleLangValidator.java ├── customvalidationmessage │ ├── CustomValidationMessages.java │ └── ValidationMessages.properties ├── localizedvalidationmessages │ ├── LocalizedValidationMessages.java │ ├── README.md │ └── ValidationMessages_sk.properties ├── pom.xml └── simple │ ├── Car.java │ └── SimpleValidation.java ├── web ├── ApacheHttpClientGet.java ├── ApacheHttpClientPost.java ├── JavaGetImage.java ├── JavaGetRequest.java ├── JavaPostRequest.java ├── embeddedjetty │ ├── plaintext │ │ ├── JettyServer.java │ │ ├── MyHandler.java │ │ └── pom.xml │ └── secureres │ │ ├── HelloHandler.java │ │ ├── HomeHandler.java │ │ ├── JettyServer.java │ │ ├── StatHandler.java │ │ ├── myrealm.properties │ │ └── pom.xml ├── httpclient │ ├── FileBodyHandler.java │ ├── GetRequestAsync.java │ ├── GetRequestSync.java │ ├── HeadRequest.java │ ├── HttpClientStatus.java │ ├── README.md │ ├── RedirectEx.java │ ├── post-json │ │ ├── JsonBodyHandler.java │ │ ├── Task.java │ │ ├── UndertowJsonEx.java │ │ ├── UndertowJsonExTest.java │ │ └── pom.xml │ ├── post-undertow │ │ ├── README.md │ │ ├── UndertowPostEx.java │ │ └── UndertowPostExTest.java │ └── postreq │ │ ├── HttpClientPost.java │ │ └── README.md ├── security │ └── tomcat │ │ └── containerloginform │ │ ├── AdminServlet.java │ │ ├── LogoutServlet.java │ │ ├── README.md │ │ ├── error.jsp │ │ ├── index.jsp │ │ ├── login.jsp │ │ ├── pom.xml │ │ └── web.xml ├── servlet │ ├── README.md │ ├── chart │ │ ├── DoChart.java │ │ ├── index.html │ │ └── pom.xml │ ├── deploywebxml │ │ ├── FirstServlet.java │ │ ├── README.md │ │ ├── index.html │ │ ├── pom.xml │ │ └── web.xml │ ├── directorylistings │ │ ├── README.md │ │ ├── data.txt │ │ ├── index.html │ │ ├── pom.xml │ │ └── web.xml │ ├── dispatcher │ │ ├── MyServlet.java │ │ ├── pom.xml │ │ ├── show.html │ │ └── show.jsp │ ├── errorpage │ │ ├── 404.html │ │ ├── README.md │ │ ├── error.html │ │ ├── index.html │ │ ├── pom.xml │ │ └── web.xml │ ├── forwardservlet │ │ ├── AnotherServlet.java │ │ ├── MyServlet.java │ │ ├── index.html │ │ └── pom.xml │ ├── freemarkersimple │ │ ├── Car.java │ │ ├── MyServlet.java │ │ ├── index.ftl │ │ ├── index.html │ │ ├── pom.xml │ │ └── web.xml │ ├── headers │ │ ├── ShowHeaders.java │ │ ├── index.html │ │ └── pom.xml │ ├── plaintext │ │ ├── MyServlet.java │ │ ├── index.html │ │ └── pom.xml │ ├── postreq │ │ ├── MyServlet.java │ │ ├── index.jsp │ │ └── pom.xml │ ├── readcsvwar │ │ ├── Country.java │ │ ├── CountryService.java │ │ ├── README.md │ │ ├── ReadCountries.java │ │ ├── countries.csv │ │ ├── index.jsp │ │ ├── listCountries.jsp │ │ ├── pom.xml │ │ └── showError.jsp │ ├── scss │ │ ├── CityService.java │ │ ├── GetCities.java │ │ ├── ICityService.java │ │ ├── README.md │ │ ├── index.jsp │ │ ├── pom.xml │ │ ├── showCities.jsp │ │ └── style.scss │ ├── sendimage │ │ ├── SendImageServlet.java │ │ ├── index.html │ │ ├── pom.xml │ │ └── sid.jpg │ ├── sendjson │ │ ├── City.java │ │ ├── CityService.java │ │ ├── GetCities.java │ │ ├── JsonConverter.java │ │ ├── index.html │ │ └── pom.xml │ └── welcomefilelist │ │ ├── default.html │ │ ├── index.html │ │ ├── index.jsp │ │ ├── pom.xml │ │ └── web.xml └── undertow │ ├── accesslog │ └── UndertowAccessLog.java │ ├── fileserver │ ├── UndertowFileServer.java │ └── pom.xml │ ├── pathparam │ ├── UndertowPathParam.java │ └── pom.xml │ ├── queryparam │ ├── UndertowQueryParam.java │ └── pom.xml │ ├── requestinfo │ └── UndertowRequestInfo.java │ ├── routing │ ├── PlainTextHandler.java │ ├── RoutingHandlers.java │ ├── UndertowRouting.java │ └── pom.xml │ ├── sendimage │ ├── UndertowSendImage.java │ ├── pom.xml │ └── sid.jpg │ ├── servlet │ ├── HelloServlet.java │ ├── UndertowServletEx.java │ └── pom.xml │ ├── simple │ ├── UndertowSimple.java │ └── pom.xml │ └── welcomepage │ ├── WelcomePage.java │ ├── index.html │ └── pom.xml ├── words.properties ├── words_de.properties ├── words_sk.properties └── xml ├── JavaAlexaRankingEx.java ├── XMLHttpRequest ├── README.md ├── fetchdata1.js ├── fetchdata2.js └── index.html ├── doc.txt ├── dom ├── JavaXmlDomCustomFilter.java ├── JavaXmlDomReadElements.java ├── JavaXmlDomReadEx.java ├── JavaXmlDomReadText.java ├── JavaXmlDomTreeWalkerEx.java ├── JavaXmlDomWrite.java ├── continents.xml └── users.xml ├── jackson ├── binding │ ├── readjson │ │ ├── JacksonReadJsonEx.java │ │ ├── README.md │ │ ├── User.java │ │ ├── Users.java │ │ └── users.json │ └── writejson │ │ ├── JacksonJsonWriteEx.java │ │ ├── README.md │ │ └── User.java ├── object2json │ └── JacksonObject2JsonEx.java ├── object2xml │ ├── JacksonObject2XmlEx.java │ ├── README.md │ └── User.java ├── stream │ ├── JacksonJsonStreamReadEx.java │ ├── JacksonJsonStreamWriteEx.java │ └── users.json └── treemodel │ ├── README.md │ ├── readjson │ ├── JacksonJsonTreeReadEx.java │ └── users.json │ └── writejson │ ├── JacksonJsonTreeWriteEx.java │ └── User.java ├── jaxb ├── Book.java ├── BookStore.java ├── JavaReadXmlJaxbEx.java ├── JavaWriteXmlJaxbEx.java └── pom.xml ├── sax ├── JavaReadXmlSaxEx.java ├── MyHandler.java ├── User.java └── users.xml ├── schema.txt ├── stax ├── JavaStaxReadEx.java ├── JavaStaxWriteEx.java └── users.xml ├── xlsfo ├── JavaXLsfoEx.java ├── README.md ├── contacts.xml ├── pom.xml └── stylesheet.xsl ├── xlst ├── xml2csv │ ├── JavaXmlTransformCsv.java │ ├── stylesheet.xls │ └── users.xml └── xml2html │ ├── JavaXmlTransformHtmlEx.java │ ├── input.xml │ └── stylesheet.xls ├── xpath ├── JavaXPathEx.java ├── JavaXPathSimpleEx.java ├── inventory.xml └── users.xml └── xsd ├── JavaXmlXsdValidationEx.java ├── books.xml ├── enumaration ├── JavaXsdEnumEx.java ├── myschema.xsd └── students.xml ├── external ├── JavaXmlExternalXsdValidationEx.java └── books2.xml ├── myschema.xsd ├── pom.xml └── restriction ├── JavaXsdRestrictionEx.java ├── books.xml └── myschema.xsd /HorizontalChart.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | public class HorizontalChart { 4 | 5 | public static void main(String[] args) { 6 | 7 | int[] nums = {7, 9, 2, 6, 12, 10}; 8 | 9 | String unit = "*"; 10 | 11 | for (var num: nums) { 12 | 13 | for (int i = 0; i < num; i++) { 14 | 15 | System.out.print("*"); 16 | } 17 | System.out.println(); 18 | } 19 | 20 | for (var num: nums) { 21 | 22 | System.out.println(unit.repeat(num)); 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /algorithms/FibonacciRecursiveEx.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.math.BigInteger; 4 | 5 | public class FibonacciRecursiveEx { 6 | 7 | private static final BigInteger[] fibCache = new BigInteger[100000]; 8 | 9 | static { 10 | fibCache[0] = BigInteger.ONE; 11 | fibCache[1] = BigInteger.ONE; 12 | } 13 | 14 | public static BigInteger fibonacci(int b) { 15 | 16 | if (fibCache[b] == null) { 17 | fibCache[b] = fibonacci(b - 1).add(fibonacci(b - 2)); 18 | } 19 | 20 | return fibCache[b]; 21 | } 22 | 23 | public static void main(String[] args) { 24 | 25 | System.out.println(fibonacci(99)); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /algorithms/FibonacciRecursiveEx2.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.math.BigInteger; 4 | 5 | public class FibonacciRecursiveEx2 { 6 | 7 | public static BigInteger fibonacci2(int n) { 8 | 9 | if (n == 0 || n == 1) { 10 | return BigInteger.ONE; 11 | } 12 | 13 | return fibonacci2(n - 2).add(fibonacci2(n - 1)); 14 | } 15 | 16 | public static void main(String[] args) { 17 | 18 | for (int i = 0; i < 10; i++) { 19 | 20 | System.out.println(fibonacci2(i)); 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /algorithms/FibonacciStreamEx.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.math.BigInteger; 4 | import java.util.List; 5 | import java.util.stream.Collectors; 6 | import java.util.stream.Stream; 7 | 8 | public class FibonacciStreamEx { 9 | 10 | public static List fibonacci(int limit) { 11 | 12 | var vals = Stream.iterate(new BigInteger[] { BigInteger.ZERO, BigInteger.ONE }, 13 | t -> new BigInteger[]{t[1], t[0].add(t[1])}) 14 | .limit(limit) 15 | .map(n -> n[1]) 16 | .collect(Collectors.toList()); 17 | 18 | return vals; 19 | } 20 | 21 | public static void main(String[] args) { 22 | 23 | System.out.println(fibonacci(99)); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /algorithms/FindMax.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | // brute force algorithm to find maximum value 4 | // in array 5 | 6 | public class FindMax { 7 | 8 | public static void main(String[] args) { 9 | 10 | int[] values = {3, 7, 1, 15, 12, 6, 11, 9}; 11 | 12 | int max = values[0]; 13 | 14 | for (int i = 1; i < values.length; i++) { 15 | 16 | if (values[i] > max) { 17 | max = values[i]; 18 | } 19 | } 20 | 21 | System.out.printf("The maximum is %d%n", max); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /algorithms/Palindrome.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | // A palindrome is a word, number, phrase, or other sequence of characters 4 | // which reads the same backward as forward, such as madam or racecar 5 | 6 | public class Palindrome { 7 | 8 | public static void main(String[] args) { 9 | 10 | System.out.println(isPalindrome("radar")); 11 | System.out.println(isPalindrome("kayak")); 12 | System.out.println(isPalindrome("forest")); 13 | } 14 | 15 | private static boolean isPalindrome(String original) { 16 | 17 | String reversed = new StringBuilder(original).reverse().toString(); 18 | return original.equals(reversed); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /algorithms/RecursionEx.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | public class RecursionEx { 4 | 5 | public static void main(String[] args) { 6 | 7 | printWord("rock", 10); 8 | } 9 | 10 | public static void printWord(String word, int count) { 11 | 12 | System.out.printf("%d %s%n", count, word); 13 | 14 | if (count > 1) { 15 | 16 | printWord(word, count - 1); 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /algorithms/ReverseInteger.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | public class ReverseInteger { 4 | 5 | public static void main(String[] args) { 6 | 7 | int val = 73230; 8 | 9 | var str = String.valueOf(val); 10 | byte[] data = str.getBytes(); 11 | 12 | byte[] data2 = new byte[data.length]; 13 | 14 | for (int i = 0; i < data.length; i++) { 15 | 16 | data2[i] = data[data.length - i - 1]; 17 | } 18 | 19 | var str2 = new String(data2); 20 | int val2 = Integer.parseInt(str2); 21 | 22 | System.out.println(val2); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /algorithms/ReverseInteger2.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | public class ReverseInteger2 { 4 | 5 | public static void main(String[] args) { 6 | 7 | int val = 7320300; 8 | 9 | var str = String.valueOf(val); 10 | 11 | char[] data = str.toCharArray(); 12 | char[] data2 = new char[data.length]; 13 | 14 | for (int i = 0; i < data.length; i++) { 15 | 16 | data2[i] = data[data.length - i - 1]; 17 | } 18 | 19 | // remove possible leading zeros 20 | int j = 0; 21 | while (data2[j] == '0') { 22 | 23 | data2[j] = ' '; 24 | j++; 25 | } 26 | 27 | var str2 = new String(data2); 28 | System.out.println(str2.stripLeading()); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /algorithms/ReverseInteger4.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | public class ReverseInteger4 { 4 | 5 | public static void main(String[] args) { 6 | 7 | int value = 73203000; 8 | 9 | var str = String.valueOf(value); 10 | var sb = new StringBuilder(str).reverse(); 11 | 12 | // removing possible leading zeros 13 | int i = 0; 14 | 15 | while (sb.charAt(i) == '0') { 16 | // does not work with deleteCharAt 17 | // val2.deleteCharAt(0); 18 | i++; 19 | } 20 | 21 | if (i > 0) { 22 | 23 | sb.delete(0, i); 24 | } 25 | 26 | System.out.println(sb.toString()); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /algorithms/ReverseInteger5.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | public class ReverseInteger5 { 4 | 5 | public static void main(String[] args) { 6 | 7 | int value = 73203000; 8 | 9 | int value2 = reverse(value); 10 | 11 | System.out.println(value2); 12 | } 13 | 14 | private static int reverse(int number) { 15 | 16 | int reverse = 0; 17 | int remainder; 18 | 19 | do { 20 | remainder = number % 10; 21 | reverse = reverse * 10 + remainder; 22 | number = number / 10; 23 | 24 | } while (number > 0); 25 | 26 | return reverse; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /apps/commandline/JavaStatsEx.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | /** 4 | * Starter class for MyStats application. 5 | * 6 | * @author janbodnar 7 | */ 8 | 9 | public class JavaStatsEx { 10 | 11 | /** 12 | * Application entry point. 13 | * 14 | * @param args application command line arguments 15 | */ 16 | public static void main(String[] args) { 17 | 18 | var app = new MyStatsApp(); 19 | app.run(args); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /apps/commandline/README.md: -------------------------------------------------------------------------------- 1 | An example of a more complex command line application in Java. The application calculates the statistics from 2 | data read from a specified file. 3 | 4 | To run the application, we need to specify the file name in the program arguments. For instance: `-f src/main/resources/data.txt`. 5 | -------------------------------------------------------------------------------- /apps/commandline/data.txt: -------------------------------------------------------------------------------- 1 | 2.3, 3.5, 5, 6.7, 3.2, 1.2, 6.7, 7.8 2 | 4.5, 2.1, 6.6, 8.7, 3.2, 1.0, 1.2, 3 3 | -------------------------------------------------------------------------------- /apps/web/context.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | -------------------------------------------------------------------------------- /apps/web/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Home page 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | -------------------------------------------------------------------------------- /arrays/AccessElements.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | public class AccessElements { 4 | 5 | public static void main(String[] args) { 6 | 7 | String[] names = {"Jane", "Thomas", "Lucy", "David"}; 8 | 9 | System.out.println(names[0]); 10 | System.out.println(names[1]); 11 | System.out.println(names[2]); 12 | System.out.println(names[3]); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /arrays/AccessElements2.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.util.Arrays; 4 | 5 | public class AccessElements2 { 6 | 7 | public static void main(String[] args) { 8 | 9 | int[] vals = { 1, 2, 3 }; 10 | 11 | vals[0] *= 2; 12 | vals[1] *= 2; 13 | vals[2] *= 2; 14 | 15 | System.out.println(Arrays.toString(vals)); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /arrays/ArrayCopy.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.util.Arrays; 4 | 5 | public class ArrayCopy { 6 | 7 | public static void main(String[] args) { 8 | 9 | int[] vals = {1, 2, 3, 4, 5, 6, 7, 8}; 10 | 11 | int[] vals2 = Arrays.copyOf(vals, 8); 12 | int[] vals3 = Arrays.copyOfRange(vals, 2, 7); 13 | 14 | // we need to create an empty array 15 | int[] vals4 = new int[8]; 16 | System.arraycopy(vals, 0, vals4, 0, vals.length); 17 | 18 | System.out.println(Arrays.toString(vals)); 19 | System.out.println(Arrays.toString(vals2)); 20 | System.out.println(Arrays.toString(vals3)); 21 | System.out.println(Arrays.toString(vals4)); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /arrays/ArrayMethods.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.util.Arrays; 4 | 5 | public class ArrayMethods { 6 | 7 | public static void main(String[] args) { 8 | 9 | int[] a = {5, 2, 4, 3, 1}; 10 | 11 | Arrays.sort(a); 12 | 13 | System.out.println(Arrays.toString(a)); 14 | 15 | Arrays.fill(a, 8); 16 | System.out.println(Arrays.toString(a)); 17 | 18 | int[] b = Arrays.copyOf(a, 5); 19 | 20 | if (Arrays.equals(a, b)) { 21 | 22 | System.out.println("Arrays a, b are equal"); 23 | } else { 24 | 25 | System.out.println("Arrays a, b are not equal"); 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /arrays/ArraySetAll.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.util.Arrays; 4 | 5 | public class ArraySetAll { 6 | 7 | public static void main(String[] args) { 8 | 9 | int[] a = new int[10]; 10 | 11 | Arrays.setAll(a, idx -> idx); 12 | 13 | System.out.println(Arrays.toString(a)); 14 | 15 | String[] vals = {"1", "2", "3", "4", "5"}; 16 | 17 | int[] b = new int[vals.length]; 18 | 19 | Arrays.setAll(b, idx -> Integer.parseInt(vals[idx])); 20 | 21 | System.out.println(Arrays.toString(b)); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /arrays/ArraySortPrimitive.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.util.Arrays; 4 | 5 | // Sorting an array of primitive integer values 6 | 7 | public class ArraySortPrimitive { 8 | 9 | public static void main(String[] args) { 10 | 11 | var nums = new int[]{3, 2, 8, 1, 7, 0, 5, 4, 6}; 12 | 13 | Arrays.sort(nums); 14 | 15 | System.out.println(Arrays.toString(nums)); 16 | 17 | for (int start = 0, end = nums.length - 1; start <= end; start++, end--) { 18 | 19 | int temp = nums[start]; 20 | nums[start] = nums[end]; 21 | nums[end] = temp; 22 | } 23 | 24 | System.out.println(Arrays.toString(nums)); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /arrays/ArraySortWrapper.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.util.Arrays; 4 | import java.util.Comparator; 5 | 6 | // Sorting an array of wrapper integer values 7 | 8 | public class ArraySortWrapper { 9 | 10 | public static void main(String[] args) { 11 | 12 | Integer[] vals = { 3, 2, 12, 5, 7, 12, 87, 43, 21, 12, 4 }; 13 | 14 | Arrays.sort(vals, Comparator.naturalOrder()); 15 | System.out.println(Arrays.toString(vals)); 16 | 17 | Arrays.sort(vals, Comparator.reverseOrder()); 18 | System.out.println(Arrays.toString(vals)); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /arrays/ArraySplitIterator.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.util.Arrays; 4 | import java.util.Spliterator; 5 | import java.util.function.IntConsumer; 6 | 7 | public class ArraySplitIterator { 8 | 9 | // split iterator gives read-only access to a range 10 | // of elements 11 | public static void main(String[] args) { 12 | 13 | int[] vals = {1, 2, 3, 4, 5, 6, 7, 8}; 14 | 15 | Spliterator.OfInt sit = Arrays.spliterator(vals, 2, 6); 16 | 17 | sit.forEachRemaining((IntConsumer) System.out::println); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /arrays/ArrayToList.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.util.Arrays; 4 | import java.util.List; 5 | import java.util.stream.Collectors; 6 | 7 | public class ArrayToList { 8 | 9 | public static void main(String[] args) { 10 | 11 | int[] ints = {1, 2, 3, 4, 5, 6, 7}; 12 | 13 | List vals = Arrays.stream(ints).boxed().collect(Collectors.toList()); 14 | 15 | System.out.println(vals); 16 | 17 | Integer[] nums = {2, 4, 6, 8, 10}; 18 | List vals2 = Arrays.asList(nums); 19 | List vals3 = Arrays.stream(nums).collect(Collectors.toList()); 20 | 21 | System.out.println(vals2); 22 | System.out.println(vals3); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /arrays/ArrayToString.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.util.Arrays; 4 | 5 | public class ArrayToString { 6 | 7 | public static void main(String[] args) { 8 | 9 | int[][] a = { 10 | {1, 1, 2, 1, 1}, 11 | {0, 0, 3, 0, 0} 12 | }; 13 | 14 | System.out.println(Arrays.toString(a)); 15 | System.out.println(Arrays.deepToString(a)); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /arrays/InitArray.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.util.Arrays; 4 | 5 | public class InitArray { 6 | 7 | public static void main(String[] args) { 8 | 9 | int[] a = new int[5]; 10 | 11 | a[0] = 1; 12 | a[1] = 2; 13 | a[2] = 3; 14 | a[3] = 4; 15 | a[4] = 5; 16 | 17 | System.out.println(Arrays.toString(a)); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /arrays/InitArray2.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.util.Arrays; 4 | 5 | public class InitArray2 { 6 | 7 | public static void main(String[] args) { 8 | 9 | // we can use var keyword 10 | var a = new int[] { 2, 4, 5, 6, 7, 3, 2 }; 11 | 12 | System.out.println(Arrays.toString(a)); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /arrays/InitArray3.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.util.Arrays; 4 | 5 | public class InitArray3 { 6 | 7 | public static void main(String[] args) { 8 | 9 | // we cannot use var keyword 10 | int[] a = { 2, 4, 5, 6, 7, 3, 2 }; 11 | 12 | System.out.println(Arrays.toString(a)); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /arrays/InitArray4.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.util.Arrays; 4 | 5 | public class InitArray4 { 6 | 7 | public static void main(String[] args) { 8 | 9 | int[] a = new int[10]; 10 | 11 | Arrays.fill(a, 1); 12 | 13 | System.out.println(Arrays.toString(a)); 14 | 15 | int[] b = new int[10]; 16 | 17 | Arrays.setAll(b, idx -> idx); 18 | 19 | System.out.println(Arrays.toString(b)); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /arrays/IrregularArrays.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | public class IrregularArrays { 4 | 5 | public static void main(String[] args) { 6 | 7 | int[][] ir = new int[][] { 8 | {1, 2}, 9 | {1, 2, 3}, 10 | {1, 2, 3, 4} 11 | }; 12 | 13 | for (int[] a : ir) { 14 | for (int e : a) { 15 | System.out.print(e + " "); 16 | } 17 | } 18 | 19 | System.out.print('\n'); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /arrays/ListToArray.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.util.Arrays; 4 | import java.util.List; 5 | 6 | public class ListToArray { 7 | 8 | public static void main(String[] args) { 9 | 10 | List vals = List.of(2.3, 2.5, 3.1, 6.7); 11 | 12 | Double[] vals2 = vals.toArray(new Double[0]); 13 | System.out.println(Arrays.toString(vals2)); 14 | 15 | double[] vals3 = vals.stream().mapToDouble(Double::doubleValue).toArray(); 16 | System.out.println(Arrays.toString(vals3)); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /arrays/PassingArray.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.util.Arrays; 4 | 5 | public class PassingArray { 6 | 7 | public static void main(String[] args) { 8 | 9 | int[] a = { 3, 4, 5, 6, 7 }; 10 | int[] r = reverseArray(a); 11 | 12 | System.out.println(Arrays.toString(a)); 13 | System.out.println(Arrays.toString(r)); 14 | } 15 | 16 | private static int[] reverseArray(int[] b) { 17 | 18 | int[] c = new int[b.length]; 19 | 20 | for (int i=b.length-1, j=0; i>=0; i--, j++) { 21 | 22 | c[j] = b[i]; 23 | } 24 | 25 | return c; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /arrays/ReadAllBytesEx.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.io.IOException; 4 | import java.nio.file.Files; 5 | import java.nio.file.Paths; 6 | 7 | // An array of bytes is used to store data 8 | // read from a file 9 | public class ReadAllBytesEx { 10 | 11 | public static void main(String[] args) throws IOException { 12 | 13 | var fileName = "src/resources/thermopylae.txt"; 14 | var filePath = Paths.get(fileName); 15 | 16 | byte[] data = Files.readAllBytes(filePath); 17 | var content = new String(data); 18 | 19 | System.out.println(content); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /arrays/TwoDimensions.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | public class TwoDimensions { 4 | 5 | public static void main(String[] args) { 6 | 7 | int[][] twodim = new int[][]{{1, 2, 3}, {1, 2, 3}}; 8 | 9 | int d1 = twodim.length; 10 | int d2 = twodim[1].length; 11 | 12 | for (int i = 0; i < d1; i++) { 13 | 14 | for (int j = 0; j < d2; j++) { 15 | 16 | System.out.println(twodim[i][j]); 17 | } 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /arrays/ball.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/janbodnar/Java-Advanced/9c90c857505ec7d1fff6979ac8e5fa8ea527c57f/arrays/ball.png -------------------------------------------------------------------------------- /arrays/sid.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/janbodnar/Java-Advanced/9c90c857505ec7d1fff6979ac8e5fa8ea527c57f/arrays/sid.jpg -------------------------------------------------------------------------------- /arrays/thermopylae.txt: -------------------------------------------------------------------------------- 1 | The Battle of Thermopylae was fought between an alliance of Greek city-states, 2 | led by King Leonidas of Sparta, and the Persian Empire of Xerxes I over the 3 | course of three days, during the second Persian invasion of Greece. 4 | -------------------------------------------------------------------------------- /cdi/autodiscovery/TextService.java: -------------------------------------------------------------------------------- 1 | package com.zetcode.service; 2 | 3 | public class TextService { 4 | 5 | public String upper(String value) { 6 | 7 | return value.toUpperCase(); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /cdi/autodiscovery/TimeService.java: -------------------------------------------------------------------------------- 1 | package com.zetcode.service; 2 | 3 | import java.time.LocalTime; 4 | 5 | public class TimeService { 6 | 7 | public String getTime() { 8 | 9 | return LocalTime.now().toString(); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /cdi/event/NotifyBoard.java: -------------------------------------------------------------------------------- 1 | package com.zetcode.board; 2 | 3 | import com.zetcode.TextModify; 4 | 5 | import javax.enterprise.event.Observes; 6 | 7 | public class NotifyBoard { 8 | 9 | public void textNotify(@Observes @TextModify String value) { 10 | 11 | System.out.printf("Notification: %s%n", value); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /cdi/event/TextModify.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import javax.inject.Qualifier; 4 | import java.lang.annotation.Retention; 5 | import java.lang.annotation.Target; 6 | 7 | import static java.lang.annotation.ElementType.FIELD; 8 | import static java.lang.annotation.ElementType.METHOD; 9 | import static java.lang.annotation.ElementType.PARAMETER; 10 | import static java.lang.annotation.ElementType.TYPE; 11 | import static java.lang.annotation.RetentionPolicy.RUNTIME; 12 | 13 | @Qualifier 14 | @Retention(RUNTIME) 15 | @Target({FIELD, TYPE, PARAMETER, METHOD}) 16 | public @interface TextModify { 17 | 18 | } 19 | -------------------------------------------------------------------------------- /cdi/event/TextService.java: -------------------------------------------------------------------------------- 1 | package com.zetcode.service; 2 | 3 | import com.zetcode.TextModify; 4 | 5 | import javax.enterprise.event.Event; 6 | import javax.inject.Inject; 7 | 8 | public class TextService { 9 | 10 | @Inject @TextModify 11 | private Event textEvent; 12 | 13 | public String upper(String val) { 14 | 15 | var msg = String.format("%s modified to uppercase", val); 16 | 17 | textEvent.fire(msg); 18 | 19 | return val.toUpperCase(); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /cdi/named/ConsoleMessageRenderer.java: -------------------------------------------------------------------------------- 1 | package com.zetcode.renderer; 2 | 3 | import com.zetcode.provider.MessageProvider; 4 | 5 | import javax.inject.Inject; 6 | import javax.inject.Named; 7 | 8 | public class ConsoleMessageRenderer implements MessageRenderer { 9 | 10 | @Inject 11 | @Named("TimeMessageProvider") 12 | private MessageProvider messageProvider; 13 | 14 | public void render() { 15 | 16 | var msg = messageProvider.getMessage(); 17 | 18 | System.out.println(msg); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /cdi/named/HelloMessageProvider.java: -------------------------------------------------------------------------------- 1 | package com.zetcode.provider; 2 | 3 | import javax.enterprise.inject.Alternative; 4 | import javax.inject.Named; 5 | 6 | //@Alternative 7 | @Named("HelloMessageProvider") 8 | public class HelloMessageProvider implements MessageProvider { 9 | 10 | public String getMessage() { 11 | 12 | return "Hello there"; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /cdi/named/MessageProvider.java: -------------------------------------------------------------------------------- 1 | package com.zetcode.provider; 2 | 3 | public interface MessageProvider { 4 | 5 | String getMessage(); 6 | } 7 | -------------------------------------------------------------------------------- /cdi/named/MessageRenderer.java: -------------------------------------------------------------------------------- 1 | package com.zetcode.renderer; 2 | 3 | public interface MessageRenderer { 4 | 5 | void render(); 6 | } 7 | -------------------------------------------------------------------------------- /cdi/named/TimeMessageProvider.java: -------------------------------------------------------------------------------- 1 | package com.zetcode.provider; 2 | 3 | import javax.inject.Named; 4 | import java.time.LocalTime; 5 | 6 | @Named("TimeMessageProvider") 7 | public class TimeMessageProvider implements MessageProvider { 8 | 9 | @Override 10 | public String getMessage() { 11 | 12 | return LocalTime.now().toString(); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /cdi/producer/ConsoleMessageRenderer.java: -------------------------------------------------------------------------------- 1 | package com.zetcode.renderer; 2 | 3 | import com.zetcode.producer.Message; 4 | import com.zetcode.producer.MessageType; 5 | import com.zetcode.provider.MessageProvider; 6 | 7 | import javax.inject.Inject; 8 | 9 | public class ConsoleMessageRenderer implements MessageRenderer { 10 | 11 | @Inject 12 | @Message(MessageType.TIME_MESSAGE) 13 | private MessageProvider messageProvider; 14 | 15 | public void render() { 16 | 17 | var msg = messageProvider.getMessage(); 18 | 19 | System.out.println(msg); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /cdi/producer/HelloMessageProvider.java: -------------------------------------------------------------------------------- 1 | package com.zetcode.provider; 2 | 3 | public class HelloMessageProvider implements MessageProvider { 4 | 5 | public String getMessage() { 6 | 7 | return "Hello there"; 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /cdi/producer/Message.java: -------------------------------------------------------------------------------- 1 | package com.zetcode.producer; 2 | 3 | import static java.lang.annotation.ElementType.FIELD; 4 | import static java.lang.annotation.ElementType.TYPE; 5 | import static java.lang.annotation.ElementType.METHOD; 6 | import static java.lang.annotation.RetentionPolicy.RUNTIME; 7 | 8 | import java.lang.annotation.Retention; 9 | import java.lang.annotation.Target; 10 | 11 | import javax.inject.Qualifier; 12 | 13 | @Qualifier 14 | @Retention(RUNTIME) 15 | @Target({FIELD, TYPE, METHOD}) 16 | public @interface Message { 17 | 18 | MessageType value(); 19 | } 20 | -------------------------------------------------------------------------------- /cdi/producer/MessageProvider.java: -------------------------------------------------------------------------------- 1 | package com.zetcode.provider; 2 | 3 | public interface MessageProvider { 4 | 5 | String getMessage(); 6 | } 7 | -------------------------------------------------------------------------------- /cdi/producer/MessageRenderer.java: -------------------------------------------------------------------------------- 1 | package com.zetcode.renderer; 2 | 3 | public interface MessageRenderer { 4 | 5 | void render(); 6 | } 7 | -------------------------------------------------------------------------------- /cdi/producer/MessageType.java: -------------------------------------------------------------------------------- 1 | package com.zetcode.producer; 2 | 3 | public enum MessageType { 4 | 5 | HELLO_MESSAGE, TIME_MESSAGE 6 | } 7 | -------------------------------------------------------------------------------- /cdi/producer/TimeMessageProvider.java: -------------------------------------------------------------------------------- 1 | package com.zetcode.provider; 2 | 3 | import java.time.LocalTime; 4 | import java.time.format.DateTimeFormatter; 5 | 6 | public class TimeMessageProvider implements MessageProvider { 7 | 8 | private String format; 9 | 10 | @Override 11 | public String getMessage() { 12 | 13 | var dtf = DateTimeFormatter.ofPattern(format); 14 | return LocalTime.now().format(dtf); 15 | } 16 | 17 | public void setFormat(String format) { 18 | 19 | this.format = format; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /cdi/producer/application.properties: -------------------------------------------------------------------------------- 1 | timeFormat=HH:mm:ss.n 2 | -------------------------------------------------------------------------------- /cdi/producer/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /cdi/simple/ConsoleMessageRenderer.java: -------------------------------------------------------------------------------- 1 | package com.zetcode.renderer; 2 | 3 | import com.zetcode.provider.MessageProvider; 4 | 5 | import javax.inject.Inject; 6 | 7 | public class ConsoleMessageRenderer implements MessageRenderer { 8 | 9 | @Inject 10 | private MessageProvider messageProvider; 11 | 12 | public void render() { 13 | 14 | var message = messageProvider.getMessage(); 15 | 16 | System.out.println(message); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /cdi/simple/HelloMessageProvider.java: -------------------------------------------------------------------------------- 1 | package com.zetcode.provider; 2 | 3 | public class HelloMessageProvider implements MessageProvider { 4 | 5 | public String getMessage() { 6 | 7 | return "Hello there"; 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /cdi/simple/MessageProvider.java: -------------------------------------------------------------------------------- 1 | package com.zetcode.provider; 2 | 3 | public interface MessageProvider { 4 | 5 | String getMessage(); 6 | } 7 | -------------------------------------------------------------------------------- /cdi/simple/simplelogger.properties: -------------------------------------------------------------------------------- 1 | org.slf4j.simpleLogger.log.org.jboss.weld=error 2 | #org.slf4j.simpleLogger.defaultLogLevel=off 3 | -------------------------------------------------------------------------------- /cdi/undertowweld/AppConfig.java: -------------------------------------------------------------------------------- 1 | package com.zetcode.conf; 2 | 3 | import com.zetcode.ws.MessageResource; 4 | 5 | import javax.ws.rs.ApplicationPath; 6 | import javax.ws.rs.core.Application; 7 | import java.util.HashSet; 8 | import java.util.Set; 9 | 10 | @ApplicationPath("/") 11 | public class AppConfig extends Application { 12 | 13 | @Override 14 | public Set> getClasses() { 15 | Set> set = new HashSet<>(); 16 | set.add(MessageResource.class); 17 | return set; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /cdi/undertowweld/HelloMessage.java: -------------------------------------------------------------------------------- 1 | package com.zetcode.bean; 2 | 3 | import javax.enterprise.inject.Produces; 4 | import javax.inject.Named; 5 | 6 | public class HelloMessage { 7 | 8 | @Named("hello") 9 | @Produces 10 | public String message() { 11 | return "Hello there"; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /cdi/undertowweld/MessageResource.java: -------------------------------------------------------------------------------- 1 | package com.zetcode.ws; 2 | 3 | import javax.inject.Inject; 4 | import javax.inject.Named; 5 | import javax.ws.rs.GET; 6 | import javax.ws.rs.Path; 7 | import javax.ws.rs.Produces; 8 | import javax.ws.rs.core.MediaType; 9 | 10 | @Path("/sayhello") 11 | public class MessageResource { 12 | 13 | @Named("hello") 14 | @Inject 15 | private String message; 16 | 17 | @GET 18 | @Produces(MediaType.TEXT_PLAIN) 19 | public String getMessage(){ 20 | return message; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /cdi/undertowweld/beans.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | -------------------------------------------------------------------------------- /collections/arraylist/ContainsElement.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | public class ContainsElement { 7 | 8 | public static void main(String[] args) { 9 | 10 | List items = new ArrayList<>(); 11 | 12 | items.add("coin"); 13 | items.add("pen"); 14 | items.add("cup"); 15 | items.add("notebook"); 16 | items.add("class"); 17 | 18 | var item = "pen"; 19 | 20 | if (items.contains(item)) { 21 | 22 | System.out.printf("There is a %s in the list%n", item); 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /collections/arraylist/GetAndSize.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | public class GetAndSize { 7 | 8 | public static void main(String[] args) { 9 | 10 | List colours = new ArrayList<>(); 11 | 12 | colours.add("blue"); 13 | colours.add("orange"); 14 | colours.add("red"); 15 | colours.add("green"); 16 | 17 | String col = colours.get(1); 18 | System.out.println(col); 19 | 20 | int size = colours.size(); 21 | 22 | System.out.printf("The size of the ArrayList is: %d%n", size); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /collections/arraylist/GetIndex.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | public class GetIndex { 7 | 8 | public static void main(String[] args) { 9 | 10 | List colours = new ArrayList<>(); 11 | 12 | colours.add(0, "blue"); 13 | colours.add(1, "orange"); 14 | colours.add(2, "red"); 15 | colours.add(3, "green"); 16 | colours.add(4, "orange"); 17 | 18 | int idx1 = colours.indexOf("orange"); 19 | System.out.println(idx1); 20 | 21 | int idx2 = colours.lastIndexOf("orange"); 22 | System.out.println(idx2); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /collections/arraylist/ListCopy.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.util.List; 4 | 5 | public class ListCopy { 6 | 7 | public static void main(String[] args) { 8 | 9 | var words = List.of("forest", "wood", "eagle", "sky", "cloud"); 10 | System.out.println(words); 11 | 12 | var words2 = List.copyOf(words); 13 | System.out.println(words2); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /collections/arraylist/ListToArray.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.util.Arrays; 4 | import java.util.List; 5 | 6 | public class ListToArray { 7 | 8 | public static void main(String[] args) { 9 | 10 | List planets = Arrays.asList("Mercury", "Venus", "Earth", 11 | "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"); 12 | 13 | System.out.println(planets); 14 | 15 | String[] planets2 = planets.toArray(new String[0]); 16 | 17 | System.out.println(Arrays.toString(planets2)); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /collections/arraylist/RemoveAll.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Collections; 5 | import java.util.List; 6 | 7 | public class RemoveAll { 8 | 9 | public static void main(String[] args) { 10 | 11 | List letters = new ArrayList<>(); 12 | letters.add("a"); 13 | letters.add("b"); 14 | letters.add("c"); 15 | letters.add("a"); 16 | letters.add("d"); 17 | 18 | System.out.println(letters); 19 | 20 | letters.removeAll(Collections.singleton("a")); 21 | System.out.println(letters); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /collections/arraylist/RemoveIf.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | public class RemoveIf { 7 | 8 | public static void main(String[] args) { 9 | 10 | List words = new ArrayList<>(); 11 | words.add("forest"); 12 | words.add("flower"); 13 | words.add("grass"); 14 | words.add("wood"); 15 | words.add("sky"); 16 | words.add("rock"); 17 | words.add("river"); 18 | 19 | words.removeIf(e -> e.length() == 5); 20 | 21 | System.out.println(words); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /collections/arraylist/ReplaceAll.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | import java.util.function.UnaryOperator; 6 | 7 | public class ReplaceAll { 8 | 9 | public static void main(String[] args) { 10 | 11 | List items = new ArrayList<>(); 12 | items.add("coin"); 13 | items.add("pen"); 14 | items.add("cup"); 15 | items.add("notebook"); 16 | items.add("class"); 17 | 18 | UnaryOperator uo = (x) -> x.toUpperCase(); 19 | 20 | items.replaceAll(uo); 21 | 22 | System.out.println(items); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /collections/arraylist/RetainAll.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | public class RetainAll { 7 | 8 | public static void main(String[] args) { 9 | 10 | List letters = new ArrayList<>(); 11 | letters.add("a"); 12 | letters.add("b"); 13 | letters.add("c"); 14 | letters.add("a"); 15 | letters.add("d"); 16 | 17 | System.out.println(letters); 18 | 19 | letters.retainAll(List.of("a", "b")); 20 | System.out.println(letters); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /collections/arraylist/ToList.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.util.List; 4 | import java.util.stream.Collectors; 5 | import java.util.stream.Stream; 6 | 7 | public class ToList { 8 | 9 | public static void main(String[] args) { 10 | 11 | var words = Stream.of("forest", "eagle", "river", "cloud", "sky"); 12 | 13 | List words2 = words.collect(Collectors.toList()); 14 | System.out.println(words2.getClass()); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /collections/hashmap/HashMapForEach.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | 6 | public class HashMapForEach { 7 | 8 | public static void main(String[] args) { 9 | 10 | Map capitals = new HashMap<>(); 11 | 12 | capitals.put("svk", "Bratislava"); 13 | capitals.put("ger", "Berlin"); 14 | capitals.put("hun", "Budapest"); 15 | capitals.put("czk", "Prague"); 16 | capitals.put("pol", "Warsaw"); 17 | capitals.put("ita", "Rome"); 18 | 19 | capitals.forEach((k, v) -> System.out.format("%s: %s%n", k, v)); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /collections/hashmap/HashMapInit2.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | 6 | // up to Java 8 7 | public class HashMapInit2 { 8 | 9 | public static void main(String[] args) { 10 | 11 | Map countries = new HashMap<>() {{ 12 | put("de", "Germany"); 13 | put("sk", "Slovakia"); 14 | put("ru", "Russia"); 15 | }}; 16 | 17 | System.out.println(countries); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /collections/hashmap/HashMapKeys.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | import java.util.Set; 6 | 7 | public class HashMapKeys { 8 | 9 | public static void main(String[] args) { 10 | 11 | Map capitals = new HashMap<>(); 12 | 13 | capitals.put("svk", "Bratislava"); 14 | capitals.put("ger", "Berlin"); 15 | capitals.put("hun", "Budapest"); 16 | capitals.put("czk", "Prague"); 17 | capitals.put("pol", "Warsaw"); 18 | capitals.put("ita", "Rome"); 19 | 20 | Set keys = capitals.keySet(); 21 | 22 | keys.forEach(System.out::println); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /collections/hashmap/HashMapReplace.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | 6 | public class HashMapReplace { 7 | 8 | public static void main(String[] args) { 9 | 10 | Map capitals = new HashMap<>(); 11 | 12 | capitals.put("day", "Monday"); 13 | capitals.put("country", "Poland"); 14 | capitals.put("colour", "blue"); 15 | 16 | capitals.replace("day", "Sunday"); 17 | capitals.replace("country", "Russia", "Great Britain"); 18 | capitals.replace("colour", "blue", "green"); 19 | 20 | capitals.entrySet().forEach(System.out::println); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /collections/hashmap/HashMapRetrieve.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | 6 | public class HashMapRetrieve { 7 | 8 | public static void main(String[] args) { 9 | 10 | Map capitals = new HashMap<>(); 11 | 12 | capitals.put("svk", "Bratislava"); 13 | capitals.put("ger", "Berlin"); 14 | capitals.put("hun", "Budapest"); 15 | capitals.put("czk", "Prague"); 16 | capitals.put("pol", "Warsaw"); 17 | capitals.put("ita", "Rome"); 18 | 19 | String cap1 = capitals.get("ita"); 20 | String cap2 = capitals.get("svk"); 21 | 22 | System.out.println(cap1); 23 | System.out.println(cap2); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /collections/hashmap/HashMapValues.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.util.Collection; 4 | import java.util.HashMap; 5 | import java.util.Map; 6 | 7 | public class HashMapValues { 8 | 9 | public static void main(String[] args) { 10 | 11 | Map capitals = new HashMap<>(); 12 | 13 | capitals.put("svk", "Bratislava"); 14 | capitals.put("ger", "Berlin"); 15 | capitals.put("hun", "Budapest"); 16 | capitals.put("czk", "Prague"); 17 | capitals.put("pol", "Warsaw"); 18 | capitals.put("ita", "Rome"); 19 | 20 | Collection vals = capitals.values(); 21 | 22 | vals.forEach(System.out::println); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /collections/hashmap/thermopylae.txt: -------------------------------------------------------------------------------- 1 | The Battle of Thermopylae was fought between an alliance of Greek city-states, 2 | led by King Leonidas of Sparta, and the Persian Empire of Xerxes I over the 3 | course of three days, during the second Persian invasion of Greece. 4 | It took place simultaneously with the naval battle at Artemisium, in August 5 | or September 480 BC, at the narrow coastal pass of Thermopylae. 6 | The Persian invasion was a delayed response to the defeat of the first Persian 7 | invasion of Greece, which had been ended by the Athenian victory at the Battle 8 | of Marathon in 490 BC. Xerxes had amassed a huge army and navy, and set out to 9 | conquer all of Greece. 10 | -------------------------------------------------------------------------------- /comparesort/ArraysSortEx2.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.util.Arrays; 4 | import java.util.Comparator; 5 | 6 | // Sorting an array of wrapper integer values 7 | 8 | public class ArraysSortEx2 { 9 | 10 | public static void main(String[] args) { 11 | 12 | Integer[] vals = { 3, 2, 12, 5, 7, 12, 87, 43, 21, 12, 4 }; 13 | 14 | Arrays.sort(vals, Comparator.naturalOrder()); 15 | System.out.println(Arrays.toString(vals)); 16 | 17 | Arrays.sort(vals, Comparator.reverseOrder()); 18 | System.out.println(Arrays.toString(vals)); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /comparesort/ArraysSortStringsEx.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.util.Arrays; 4 | import java.util.Collections; 5 | 6 | // Sorting arrays of Strings; a String is an Object 7 | 8 | public class ArraysSortStringsEx { 9 | 10 | public static void main(String[] args) { 11 | 12 | String[] words = {"pen", "blue", "atom", "abbey", "car", 13 | "ten", "desk", "slim"}; 14 | 15 | Arrays.sort(words); 16 | 17 | System.out.println(Arrays.toString(words)); 18 | 19 | Arrays.sort(words, Collections.reverseOrder()); 20 | 21 | System.out.println(Arrays.toString(words)); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /comparesort/CompareListsEx3.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Comparator; 5 | import java.util.List; 6 | 7 | public class CompareListsEx3 { 8 | 9 | public static void main(String[] args) { 10 | 11 | 12 | } 13 | } 14 | 15 | -------------------------------------------------------------------------------- /comparesort/ListSortByFields.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.util.Arrays; 4 | import java.util.Comparator; 5 | 6 | // Sorting objects by their fields 7 | 8 | record Car(String name, int price) {} 9 | 10 | public class ListSortByFields { 11 | 12 | public static void main(String[] args) { 13 | 14 | var cars = Arrays.asList(new Car("Volvo", 23400), 15 | new Car("Mazda", 13700), new Car("Porsche", 353800), 16 | new Car("Skoda", 8900), new Car("Volkswagen", 19900)); 17 | 18 | cars.sort(Comparator.comparing(Car::price)); 19 | System.out.println(cars); 20 | 21 | cars.sort(Comparator.comparing(Car::name)); 22 | System.out.println(cars); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /comparesort/ListSortEx.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.util.Arrays; 4 | import java.util.Comparator; 5 | 6 | // Sorting a list of strings 7 | 8 | public class ListSortEx { 9 | 10 | public static void main(String[] args) { 11 | 12 | var words = Arrays.asList("dog", "Sun", "Earth", "pen", "plum", "forest", 13 | "atom", "water", "sky", "meadow", "lowland", "swim", "eat", "drum"); 14 | 15 | words.sort(String.CASE_INSENSITIVE_ORDER); 16 | System.out.println(words); 17 | 18 | words.sort(Comparator.naturalOrder()); 19 | System.out.println(words); 20 | 21 | words.sort(Comparator.reverseOrder()); 22 | System.out.println(words); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /comparesort/ListSortIntegers.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.util.Arrays; 4 | import java.util.Comparator; 5 | import java.util.List; 6 | 7 | // sorting integers in-place 8 | 9 | public class ListSortIntegers { 10 | 11 | public static void main(String[] args) { 12 | 13 | List vals = Arrays.asList(5, -4, 0, 2, -1, 4, 7, 6, 1, -1, 3, 8, -2); 14 | vals.sort(Comparator.naturalOrder()); 15 | System.out.println(vals); 16 | 17 | vals.sort(Comparator.reverseOrder()); 18 | System.out.println(vals); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /concurrency/MultipleThreadsEx.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.util.stream.IntStream; 4 | 5 | public class MultipleThreadsEx { 6 | 7 | public static void main(String[] args) { 8 | 9 | var t1 = new Thread(MultipleThreadsEx::printValues); 10 | var t2 = new Thread(MultipleThreadsEx::printValues); 11 | var t3 = new Thread(MultipleThreadsEx::printValues); 12 | 13 | t1.start(); 14 | t2.start(); 15 | t3.start(); 16 | } 17 | 18 | private static void printValues() { 19 | 20 | IntStream.range(1, 9).forEach(e -> System.out.print(" " + e)); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /concurrency/SimpleThreadEx.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | public class SimpleThreadEx extends Thread { 4 | 5 | // run() method contains the code that is executed by the thread 6 | @Override 7 | public void run() { 8 | 9 | System.out.printf("inside %s%n", Thread.currentThread().getName()); 10 | } 11 | 12 | public static void main(String[] args) { 13 | 14 | System.out.printf("inside %s%n", Thread.currentThread().getName()); 15 | 16 | var thread = new SimpleThreadEx(); 17 | 18 | System.out.println("starting thread"); 19 | thread.start(); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /concurrency/SimpleThreadEx2.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | public class SimpleThreadEx2 implements Runnable { 4 | 5 | public static void main(String[] args) { 6 | 7 | System.out.printf("inside %s%n", Thread.currentThread().getName()); 8 | 9 | var runnable = new SimpleThreadEx2(); 10 | var thread = new Thread(runnable); 11 | 12 | System.out.println("starting thread"); 13 | thread.start(); 14 | } 15 | 16 | @Override 17 | public void run() { 18 | 19 | System.out.printf("inside %s%n", Thread.currentThread().getName()); 20 | } 21 | } 22 | 23 | -------------------------------------------------------------------------------- /conversions/AutoboxingEx.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | public class AutoboxingEx { 4 | 5 | private static int cube(int x) { 6 | 7 | return x * x * x; 8 | } 9 | 10 | public static void main(String[] args) { 11 | 12 | Integer i = 10; 13 | int j = i; 14 | 15 | System.out.println(i); 16 | System.out.println(j); 17 | 18 | Integer a = cube(i); 19 | System.out.println(a); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /conversions/AutoboxingEx2.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | public class AutoboxingEx2 { 4 | 5 | public static void main(String[] args) { 6 | 7 | Integer a = new Integer(5); 8 | Integer b = new Integer(7); 9 | 10 | Integer add = a + b; 11 | Integer mul = a * b; 12 | 13 | System.out.println(add); 14 | System.out.println(mul); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /conversions/AutoboxingEx3.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | // This example demonstrates autoboxing and object interning 4 | 5 | public class AutoboxingEx3 { 6 | 7 | public static void main(String[] args) { 8 | 9 | Integer a = 5; // new Integer(5); 10 | Integer b = 5; // new Integer(5); 11 | 12 | System.out.println(a == b); 13 | System.out.println(a.equals(b)); 14 | System.out.println(a.compareTo(b)); 15 | 16 | Integer c = 155; 17 | Integer d = 155; 18 | 19 | System.out.println(c == d); 20 | System.out.println(c.equals(d)); 21 | System.out.println(c.compareTo(d)); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /conversions/BoxingUnboxingEx.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | public class BoxingUnboxingEx { 4 | 5 | public static void main(String[] args) { 6 | 7 | long a = 124235L; 8 | 9 | Long b = new Long(a); 10 | long c = b.longValue(); 11 | 12 | System.out.println(c); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /conversions/NumbersEx.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | public class NumbersEx { 7 | 8 | public static void main(String[] args) { 9 | 10 | List ls = new ArrayList<>(); 11 | 12 | ls.add(1342341); 13 | ls.add(new Float(34.56)); 14 | ls.add(235.242); 15 | ls.add(new Byte("102")); 16 | ls.add(new Short("1245")); 17 | 18 | for (Number n : ls) { 19 | 20 | System.out.println(n.getClass()); 21 | System.out.println(n); 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /csv/OpenCSVWriteEx.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import com.opencsv.CSVWriter; 4 | import java.io.FileOutputStream; 5 | import java.io.IOException; 6 | import java.io.OutputStreamWriter; 7 | import java.nio.charset.StandardCharsets; 8 | 9 | public class OpenCSVWriteEx { 10 | 11 | public static void main(String[] args) throws IOException { 12 | 13 | String[] entries = { "book", "coin", "pencil", "cup" }; 14 | String fileName = "src/main/resources/items.csv"; 15 | 16 | try (var fos = new FileOutputStream(fileName); 17 | var osw = new OutputStreamWriter(fos, StandardCharsets.UTF_8); 18 | var writer = new CSVWriter(osw)) { 19 | 20 | writer.writeNext(entries); 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /csv/Readme.md: -------------------------------------------------------------------------------- 1 | Sources from the ZetCode's OpenCSV tutorial 2 | http://zetcode.com/java/opencsv/ 3 | -------------------------------------------------------------------------------- /csv/mysql/cars_mysql.sql: -------------------------------------------------------------------------------- 1 | -- SQL for the cars table 2 | 3 | CREATE TABLE cars(id BIGINT PRIMARY KEY AUTO_INCREMENT, name VARCHAR(255), 4 | price INTEGER); 5 | 6 | INSERT INTO cars(name, price) VALUES('Audi', 52642); 7 | INSERT INTO cars(name, price) VALUES('Mercedes', 57127); 8 | INSERT INTO cars(name, price) VALUES('Skoda', 9000); 9 | INSERT INTO cars(name, price) VALUES('Volvo', 29000); 10 | INSERT INTO cars(name, price) VALUES('Bentley', 350000); 11 | INSERT INTO cars(name, price) VALUES('Citroen', 21000); 12 | INSERT INTO cars(name, price) VALUES('Hummer', 41400); 13 | INSERT INTO cars(name, price) VALUES('Volkswagen', 21600); 14 | -------------------------------------------------------------------------------- /csv/numbers.csv: -------------------------------------------------------------------------------- 1 | 3,5,6,2,1,7,8 2 | 4,5,7,3,2,8,9 3 | -------------------------------------------------------------------------------- /csv/readbeans/cars.csv: -------------------------------------------------------------------------------- 1 | id,name,price 2 | 1,Audi,52642 3 | 2,Mercedes,57127 4 | 3,Skoda,9000 5 | 4,Volvo,29000 6 | 5,Bentley,350000 7 | 6,Citroen,21000 8 | 7,Hummer,41400 9 | 8,Volkswagen,21600 10 | 9,Toyota,26700 11 | -------------------------------------------------------------------------------- /csv/readbeans2/cars.csv: -------------------------------------------------------------------------------- 1 | 1,Audi,52642 2 | 2,Mercedes,57127 3 | 3,Skoda,9000 4 | 4,Volvo,29000 5 | 5,Bentley,350000 6 | 6,Citroen,21000 7 | 7,Hummer,41400 8 | 8,Volkswagen,21600 9 | 9,Toyota,26700 10 | -------------------------------------------------------------------------------- /datetime/IslamicDateEx.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.time.LocalDate; 4 | import java.time.chrono.HijrahDate; 5 | 6 | public class IslamicDateEx { 7 | 8 | public static void main(String[] args) { 9 | 10 | var nowIslamic = HijrahDate.now(); 11 | System.out.println("Islamic date: " + nowIslamic); 12 | 13 | var nowGregorian = LocalDate.now(); 14 | System.out.println("Gregorian date: " + nowGregorian); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /datetime/JavaBratislavaMoscowTime.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.time.ZoneId; 4 | import java.time.ZoneOffset; 5 | import java.time.ZonedDateTime; 6 | 7 | public class JavaBratislavaMoscowTimeEx { 8 | 9 | public static void main(String[] args) { 10 | 11 | var zbrat = ZonedDateTime.now(ZoneId.of("Europe/Bratislava")); 12 | var zmosc = ZonedDateTime.now(ZoneId.of("Europe/Moscow")); 13 | 14 | System.out.println(zbrat); 15 | System.out.println(zmosc); 16 | 17 | var utc = ZonedDateTime.now(ZoneOffset.UTC); 18 | System.out.println(utc); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /datetime/JavaCurrentDateTime.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.time.LocalDateTime; 4 | import java.time.ZoneId; 5 | import java.time.ZonedDateTime; 6 | import java.util.Date; 7 | 8 | public class JavaCurrentDateTime { 9 | 10 | public static void main(String[] args) { 11 | 12 | Date dt = new Date(); 13 | System.out.println(dt); 14 | 15 | // Java 8 16 | LocalDateTime ldt = LocalDateTime.now(); 17 | System.out.println(ldt); 18 | 19 | ZonedDateTime zdt = ZonedDateTime.now(ZoneId.of("Europe/Bratislava")); 20 | System.out.println(zdt); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /datetime/JavaCustomTemporalAdjusterEx.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.time.LocalDate; 4 | import java.time.Period; 5 | import java.time.temporal.TemporalAdjuster; 6 | 7 | public class JavaCustomTemporalAdjusterEx { 8 | 9 | public static void main(String[] args) { 10 | 11 | var localDate = LocalDate.of(2018, 12, 1); 12 | 13 | TemporalAdjuster taj = t -> t.plus(Period.ofDays(14)); 14 | var result = localDate.with(taj); 15 | 16 | System.out.printf("Adding 14 days to %s gives %s", localDate, result); 17 | 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /datetime/JavaDateTimeArithmeticEx.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.time.LocalDate; 4 | import static java.time.temporal.ChronoUnit.DAYS; 5 | 6 | public class JavaDateTimeArithmeticEx { 7 | 8 | public static void main(String[] args) { 9 | 10 | var now = LocalDate.now(); 11 | var date1 = now.plusDays(30); 12 | System.out.println(date1); 13 | 14 | var date2 = now.minusWeeks(15); 15 | System.out.println(date2); 16 | 17 | var date3 = now.plusYears(6); 18 | System.out.println(date3); 19 | 20 | var newYear = LocalDate.of(2018, 1, 1); 21 | long dif = DAYS.between(newYear, now); 22 | 23 | System.out.printf("Days passed since beginning of 2018: %d%n", dif); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /datetime/JavaUnixTimeEx.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.time.Instant; 4 | 5 | // Unix time (also known as POSIX time or epoch time) 6 | // is a system for describing a point in time, defined as the number 7 | // of seconds that have elapsed since 00:00:00 Coordinated Universal Time (UTC), 8 | // Thursday, 1 January 1970, minus the number of leap seconds 9 | // that have taken place since then 10 | 11 | public class JavaUnixTimeEx { 12 | 13 | public static void main(String[] args) { 14 | 15 | long unixTime = System.currentTimeMillis() / 1000L; 16 | System.out.println(unixTime); 17 | 18 | // Java 8 19 | 20 | long unixTime2 = Instant.now().getEpochSecond(); 21 | System.out.println(unixTime2); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /fun-streams/FibonacciStreamEx.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.math.BigInteger; 4 | import java.util.List; 5 | import java.util.stream.Collectors; 6 | import java.util.stream.Stream; 7 | 8 | public class FibonacciStreamEx { 9 | 10 | public static List fibonacci(int limit) { 11 | 12 | var vals = Stream.iterate(new BigInteger[] { BigInteger.ZERO, BigInteger.ONE }, 13 | t -> new BigInteger[]{t[1], t[0].add(t[1])}) 14 | .limit(limit) 15 | .map(n -> n[1]) 16 | .collect(Collectors.toList()); 17 | 18 | return vals; 19 | } 20 | 21 | public static void main(String[] args) { 22 | 23 | System.out.println(fibonacci(99)); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /fun-streams/FilesListCount.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.io.IOException; 4 | import java.nio.file.Files; 5 | import java.nio.file.Paths; 6 | 7 | // count # of PDF files in the Dowloads directory 8 | public class FilesListCount { 9 | 10 | public static void main(String[] args) throws IOException { 11 | 12 | var homeDir = System.getProperty("user.home") 13 | + System.getProperty("file.separator") + "Downloads"; 14 | 15 | var nOfPdfFiles = Files.list(Paths.get(homeDir)).filter(path -> path.toString() 16 | .endsWith(".pdf")).count(); 17 | 18 | System.out.printf("There are %d PDF files", nOfPdfFiles); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /fun-streams/JavaStreamRandomIntegers.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.util.Arrays; 4 | import java.util.Random; 5 | 6 | public class JavaStreamRandomIntegers { 7 | 8 | public static void main(String[] args) { 9 | 10 | int[] randInts = new Random().ints(-4, 5).limit(10).toArray(); 11 | 12 | System.out.println(Arrays.toString(randInts)); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /fun-streams/PatternCompileEx.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.util.regex.Pattern; 4 | import java.util.stream.Collectors; 5 | 6 | public class PatternCompileEx { 7 | 8 | public static void main(String[] args) { 9 | 10 | var phoneNumber = "202-555-0154"; 11 | 12 | var output = Pattern.compile("-") 13 | .splitAsStream(phoneNumber) 14 | .collect(Collectors.toList()); 15 | 16 | output.forEach(System.out::println); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /fun-streams/collect/JavaCollectCountEx.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.util.List; 4 | import java.util.stream.Collectors; 5 | 6 | public class JavaCollectCountEx { 7 | 8 | public static void main(String[] args) { 9 | 10 | var vals = List.of(1, 2, 3, 4, 5); 11 | 12 | // can be replaced with count 13 | var n = vals.stream().collect(Collectors.counting()); 14 | 15 | System.out.println(n); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /fun-streams/collect/JavaCollectJoinEx.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.util.List; 4 | import java.util.stream.Collectors; 5 | 6 | public class JavaCollectJoinEx { 7 | 8 | public static void main(String[] args) { 9 | 10 | var words = List.of("marble", "coin", "forest", "falcon", 11 | "sky", "cloud", "eagle", "lion"); 12 | 13 | var joined = words.stream().collect(Collectors.joining(",")); 14 | 15 | System.out.printf("Joined string: %s", joined); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /fun-streams/collect/JavaCollectToListEx.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.util.List; 4 | import java.util.stream.Collectors; 5 | 6 | public class JavaCollectToListEx { 7 | 8 | public static void main(String[] args) { 9 | 10 | var words = List.of("marble", "coin", "forest", "falcon", 11 | "sky", "cloud", "eagle", "lion"); 12 | 13 | // filter all four character words into a list 14 | var words4 = words.stream().filter(word -> word.length() == 4) 15 | .collect(Collectors.toList()); 16 | 17 | System.out.println(words4); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /fun-streams/collect/JavaCollectToMapEx2.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.nio.CharBuffer; 4 | import java.util.Map; 5 | import java.util.function.Function; 6 | import java.util.stream.Collectors; 7 | 8 | // creating an ASCII table from a sequence of characters 9 | public class JavaCollectToMapEx2 { 10 | 11 | public static void main(String[] args) { 12 | 13 | char[] letters = "abcdefghijklmnopqrstuvwxyz".toCharArray(); 14 | 15 | Map asciiMap = CharBuffer.wrap(letters) 16 | .chars() 17 | .mapToObj(e -> (char) e) 18 | .collect(Collectors.toMap(Object::hashCode, Function.identity())); 19 | 20 | System.out.println(asciiMap); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /fun-streams/collect/JavaCollectToSetEx.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.util.Set; 4 | import java.util.stream.Collectors; 5 | import java.util.stream.Stream; 6 | 7 | public class JavaCollectToSetEx { 8 | 9 | public static void main(String[] args) { 10 | 11 | var vals = Stream.of("a", "b", "c", "a", 12 | "b", "c", "a", "a"); 13 | 14 | Set uniqueVals = vals 15 | .collect(Collectors.toSet()); 16 | 17 | System.out.println(uniqueVals); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /fun-streams/collect/partition/User.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | public class User { 4 | 5 | private String name; 6 | private boolean single; 7 | 8 | public User(String name, boolean single) { 9 | 10 | this.name = name; 11 | this.single = single; 12 | } 13 | 14 | public boolean isSingle() { 15 | 16 | return single; 17 | } 18 | 19 | @Override 20 | public String toString() { 21 | final StringBuilder sb = new StringBuilder("User{"); 22 | sb.append("name='").append(name).append('\''); 23 | sb.append(", single=").append(single); 24 | sb.append('}'); 25 | return sb.toString(); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /fun-streams/collect/sum/JavaCollectSumAgeEx.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.util.List; 4 | import java.util.stream.Collectors; 5 | 6 | public class JavaCollectSumAgeEx { 7 | 8 | public static void main(String[] args) { 9 | 10 | var cats = List.of( 11 | new Cat("Bella", 4), 12 | new Cat("Othello", 2), 13 | new Cat("Coco", 6) 14 | ); 15 | 16 | // can be replaced with mapToInt().sum() 17 | var ageSum = cats.stream().collect(Collectors.summingInt(cat -> cat.getAge())); 18 | 19 | System.out.printf("Sum of cat ages: %d%n", ageSum); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /fun-streams/collect/sum/JavaCollectSumEvenValsEx.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.util.stream.Collectors; 4 | import java.util.stream.IntStream; 5 | 6 | public class JavaCollectSumEvenValsEx { 7 | 8 | public static void main(String[] args) { 9 | 10 | var vals = IntStream.of(1, 2, 3, 4, 5, 6, 7, 8); 11 | 12 | // can be replaced with mapToInt().sum() 13 | var sumEven = vals.boxed().collect(Collectors.summingInt((e -> e % 2 == 0 ? e : 0))); 14 | System.out.printf("The sum of even values is: %d%n", sumEven); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /fun-streams/collect/sum/JavaCollectSumEx.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.util.List; 4 | import java.util.stream.Collectors; 5 | 6 | public class JavaCollectSumEx { 7 | 8 | public static void main(String[] args) { 9 | 10 | var vals = List.of(2, 4, 6, 8, 10, 12); 11 | 12 | // can be replaced with mapToInt().sum() 13 | var sum = vals.stream().collect(Collectors.summingInt(Integer::intValue)); 14 | 15 | System.out.printf("The sum of values is %d%n", sum); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /fun-streams/collect/sum/JavaCollectSumStringValsEx.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.util.stream.Collectors; 4 | import java.util.stream.Stream; 5 | 6 | public class JavaCollectSumStringValsEx { 7 | 8 | public static void main(String[] args) { 9 | 10 | Stream vals = Stream.of("1", "2", "3", "5", "6"); 11 | 12 | // can be replaced with mapToInt().sum() 13 | var sum = vals.collect(Collectors.summingInt(n -> Integer.parseInt(n))); 14 | 15 | System.out.println(sum); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /fun-streams/filter/JavaStreamFilterMapByKeys.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | 6 | public class JavaStreamFilterMapByKeys { 7 | 8 | public static void main(String[] args) { 9 | 10 | Map hmap = new HashMap<>(); 11 | 12 | hmap.put("de", "Germany"); 13 | hmap.put("hu", "Hungary"); 14 | hmap.put("sk", "Slovakia"); 15 | hmap.put("si", "Slovenia"); 16 | hmap.put("so", "Somalia"); 17 | hmap.put("us", "United States"); 18 | hmap.put("ru", "Russia"); 19 | 20 | hmap.entrySet().stream().filter(map -> map.getKey().startsWith("s")) 21 | .forEach(m -> System.out.println(m)); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /fun-streams/filter/JavaStreamFilterRemoveNulls.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.util.Arrays; 4 | import java.util.List; 5 | import java.util.stream.Collectors; 6 | 7 | public class JavaStreamFilterRemoveNulls { 8 | 9 | public static void main(String[] args) { 10 | 11 | List words = Arrays.asList("cup", null, "forest", 12 | "sky", "book", null, "theatre"); 13 | 14 | List result = words.stream().filter(w -> w != null) 15 | .collect(Collectors.toList()); 16 | 17 | System.out.println(result); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /fun-streams/filter/JavaStreamFilterStringLength.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.util.Arrays; 4 | import java.util.List; 5 | import java.util.stream.Collectors; 6 | 7 | public class JavaStreamFilterStringLength { 8 | 9 | public static void main(String[] args) { 10 | 11 | List words = Arrays.asList("pen", "custom", "orphanage", 12 | "forest", "bubble", "butterfly"); 13 | 14 | List result = words.stream().filter(word -> word.length() > 5) 15 | .collect(Collectors.toList()); 16 | 17 | result.forEach(word -> System.out.println(word)); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /fun-streams/filter/JavaStreamMultipleFilters.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.util.Arrays; 4 | import java.util.function.IntConsumer; 5 | 6 | public class JavaStreamMultipleFilters { 7 | 8 | public static void main(String[] args) { 9 | 10 | int[] inums = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 }; 11 | 12 | IntConsumer icons = i -> System.out.print(i + " "); 13 | 14 | Arrays.stream(inums).filter(e -> e < 6 || e > 10) 15 | .filter(e -> e % 2 == 0).forEach(icons); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /fun-streams/filter/User.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | public class User { 4 | 5 | private String name; 6 | private String email; 7 | 8 | public User(String name, String email) { 9 | this.name = name; 10 | this.email = email; 11 | } 12 | 13 | public String getName() { 14 | return name; 15 | } 16 | 17 | public void setName(String name) { 18 | this.name = name; 19 | } 20 | 21 | public String getEmail() { 22 | return email; 23 | } 24 | 25 | public void setEmail(String email) { 26 | this.email = email; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /functional/BiConsumerAndThen.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.util.function.BiConsumer; 4 | 5 | public class BiConsumerAndThen { 6 | 7 | public static void main(String[] args) { 8 | 9 | BiConsumer add = (a, b) -> System.out.println(a + b); 10 | BiConsumer sub = (a, b) -> System.out.println(a - b); 11 | 12 | add.andThen(sub).accept(10, 6); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /functional/BiFunctionAndThen.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.util.function.BiFunction; 4 | import java.util.function.Function; 5 | 6 | public class BiFunctionAndThen { 7 | 8 | public static void main(String[] args) { 9 | 10 | BiFunction sum = Integer::sum; 11 | Function square = (n) -> n * n; 12 | 13 | System.out.println(sum.andThen(square).apply(5, 3)); 14 | System.out.println(sum.andThen(square).apply(12, 2)); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /functional/BiFunctionEx.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.util.function.BiFunction; 4 | 5 | public class BiFunctionEx { 6 | 7 | public static void main(String[] args) { 8 | 9 | // Integer::sum 10 | BiFunction addFun = (x, y) -> x + y; 11 | var ret = addFun.apply(10, 20); 12 | System.out.println(ret); 13 | 14 | BiFunction subFun = (x, y) -> x - y; 15 | var ret2 = subFun.apply(10, 20); 16 | System.out.println(ret2); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /functional/BiPredicateEx.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.util.function.BiPredicate; 4 | 5 | public class BiPredicateEx { 6 | 7 | public static void main(String[] args) { 8 | 9 | BiPredicate pred1 = (x, y) -> x > y; 10 | BiPredicate pred2 = Long::equals; 11 | 12 | // using and() 13 | System.out.println(pred1.and(pred2).test(7L, 7L)); 14 | 15 | // using or() 16 | System.out.println(pred1.or(pred2).test(3L, 2L)); 17 | 18 | // using negate() 19 | System.out.println(pred1.negate().test(4L, 1L)); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /functional/ConsumerEx.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.util.function.Consumer; 4 | 5 | // Consumer represents an operation that accepts a single input argument and 6 | // returns no result. Unlike most other functional interfaces, Consumer is expected 7 | // to operate via side-effects. 8 | 9 | public class ConsumerEx { 10 | 11 | public static void main(String[] args) { 12 | 13 | Consumer showThreeTimes = value -> { 14 | 15 | System.out.println(value); 16 | System.out.println(value); 17 | System.out.println(value); 18 | }; 19 | 20 | showThreeTimes.accept("Blue sky"); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /functional/ConsumerEx2.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.util.function.Consumer; 4 | import java.util.function.IntConsumer; 5 | 6 | public class ConsumerEx2 { 7 | 8 | public static void main(String[] args) { 9 | 10 | Consumer printMultiplyBy100 = (val) -> System.out.println(val * 100); 11 | 12 | printMultiplyBy100.accept(3); 13 | printMultiplyBy100.accept(4); 14 | printMultiplyBy100.accept(5); 15 | 16 | IntConsumer printMultiplyBy500 = a -> System.out.println(a * 50); 17 | printMultiplyBy500.accept(1); 18 | printMultiplyBy500.accept(2); 19 | printMultiplyBy500.accept(3); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /functional/ConsumerEx3.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.util.List; 4 | import java.util.function.Consumer; 5 | 6 | public class ConsumerEx3 { 7 | 8 | public static void main(String[] args) { 9 | 10 | var words = List.of("falcon", "wood", "rock", "forest", 11 | "river", "water"); 12 | 13 | words.forEach(new Consumer() { 14 | @Override 15 | public void accept(String s) { 16 | 17 | System.out.println(s); 18 | } 19 | }); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /functional/ConsumerEx6.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.util.List; 4 | import java.util.function.Consumer; 5 | 6 | public class ConsumerEx6 { 7 | 8 | public static void main(String[] args) { 9 | 10 | var data = List.of(1, 2, 3, 4, 5, 6, 7); 11 | 12 | // Consumer consumer = (Integer x) -> System.out.println(x); 13 | Consumer consumer = System.out::println; 14 | forEach(data, consumer); 15 | 16 | System.out.println("--------------------------"); 17 | 18 | forEach(data, System.out::println); 19 | } 20 | 21 | static void forEach(List data, Consumer consumer) { 22 | 23 | for (T t : data) { 24 | consumer.accept(t); 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /functional/CustomFunctionalInterface.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | @FunctionalInterface 4 | interface Concat 5 | { 6 | X concat(X arg1, X arg2); 7 | } 8 | 9 | public class CustomFunctionalInterface { 10 | 11 | public static void main(String[] args) { 12 | 13 | // String::concat 14 | Concat concatFun = (s, str) -> s.concat(str); 15 | 16 | var output = concatFun.concat("golden", " eagle"); 17 | System.out.println(output); 18 | 19 | // Integer::sum 20 | Concat concatFun2 = (a, b) -> Integer.sum(a, b); 21 | var output2 = concatFun2.concat(2, 3); 22 | System.out.println(output2); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /functional/IntPredicateEx2.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.util.Arrays; 4 | import java.util.function.IntPredicate; 5 | 6 | public class IntPredicateEx2 { 7 | 8 | public static void main(String[] args) { 9 | 10 | int nums[] = { 2, 3, 1, 5, 6, 7, 8, 9, 12 }; 11 | 12 | IntPredicate p = n -> n > 5; 13 | 14 | Arrays.stream(nums).filter(p).forEach(System.out::println); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /functional/PredicateCompose.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.util.Arrays; 4 | import java.util.function.IntPredicate; 5 | 6 | public class PredicateCompose { 7 | 8 | public static void main(String[] args) { 9 | 10 | int[] nums = {2, 3, 1, 5, 6, 7, 8, 9, 12}; 11 | 12 | IntPredicate p1 = n -> n > 3; 13 | IntPredicate p2 = n -> n < 9; 14 | 15 | Arrays.stream(nums).filter(p1.and(p2)).forEach(System.out::println); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /functional/PredicateEx.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.util.List; 4 | import java.util.function.Predicate; 5 | 6 | class BiggerThanFive implements Predicate { 7 | 8 | @Override 9 | public boolean test(Integer v) { 10 | 11 | Integer five = 5; 12 | 13 | return v > five; 14 | } 15 | } 16 | 17 | public class PredicateEx { 18 | 19 | public static void main(String[] args) { 20 | 21 | List nums = List.of(2, 3, 1, 5, 6, 7, 8, 9, 12); 22 | 23 | BiggerThanFive btf = new BiggerThanFive<>(); 24 | nums.stream().filter(btf).forEach(System.out::println); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /functional/PredicateNegate.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.util.Arrays; 4 | import java.util.function.IntPredicate; 5 | 6 | public class PredicateNegate { 7 | 8 | public static void main(String[] args) { 9 | 10 | int[] nums = {2, 3, 1, 5, 6, 7, 8, 9, 12}; 11 | 12 | IntPredicate p = n -> n > 5; 13 | 14 | Arrays.stream(nums).filter(p).forEach(System.out::println); 15 | 16 | System.out.println("**********"); 17 | 18 | Arrays.stream(nums).filter(p.negate()).forEach(System.out::println); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /functional/SupplierEx.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.util.Random; 4 | import java.util.function.Supplier; 5 | 6 | class RandomIntSupplier implements Supplier { 7 | 8 | @Override 9 | public Integer get() { 10 | 11 | return new Random().nextInt(); 12 | } 13 | } 14 | 15 | public class SupplierEx { 16 | 17 | public static void main(String[] args) { 18 | 19 | var ris = new RandomIntSupplier(); 20 | var res = ris.get(); 21 | 22 | System.out.println(res); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /functional/SupplierEx2.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.util.Random; 4 | import java.util.function.Supplier; 5 | 6 | // Supplier represents a supplier of results. 7 | 8 | public class SupplierEx2 { 9 | 10 | public static void main(String[] args) { 11 | 12 | Supplier randIntFun = () -> new Random().nextLong(); 13 | 14 | var value = randIntFun.get(); 15 | System.out.println(value); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /functional/SupplierEx4.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.util.function.Supplier; 4 | import java.util.stream.Stream; 5 | 6 | public class SupplierEx4 { 7 | 8 | public static void main(String[] args) { 9 | 10 | Supplier> streamSupplier = 11 | () -> Stream.of("cloud", "wood", "falcon", "sky", "forest") 12 | .filter(s -> s.startsWith("w")); 13 | 14 | var res = streamSupplier.get().anyMatch(s -> true); 15 | System.out.println(res); 16 | 17 | var res2 = streamSupplier.get().noneMatch(s -> true); 18 | System.out.println(res2); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /functional/UnaryOperatorEx.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.util.function.UnaryOperator; 4 | 5 | // UnaryOperator represents an operation on a single operand that produces 6 | // a result of the same type as its operand. This is a specialization 7 | // of Function for the case where the operand and result are of the same type. 8 | 9 | public class UnaryOperatorEx { 10 | 11 | public static void main(String[] args) { 12 | 13 | UnaryOperator op1 = t -> t + 10; 14 | UnaryOperator op2 = t -> t * 10; 15 | 16 | int a = op1.andThen(op2).apply(5); 17 | System.out.println(a); 18 | 19 | int b = op1.compose(op2).apply(5); 20 | System.out.println(b); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /generics/GenericRandomValEx.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.util.List; 4 | import java.util.Random; 5 | 6 | public class GenericRandomValEx { 7 | 8 | public static void main(String[] args) { 9 | 10 | var words = List.of("rock", "sky", "blue", "ocean", "falcon"); 11 | var vals = List.of(2, 3, 4, 5, 6, 7, 8); 12 | 13 | var e1 = getRandomElement(words); 14 | System.out.println(e1); 15 | 16 | var e2 = getRandomElement(vals); 17 | System.out.println(e2); 18 | } 19 | 20 | private static T getRandomElement(List list) { 21 | 22 | var random = new Random(); 23 | int idx = random.nextInt(list.size()); 24 | return list.get(idx); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /intellij.md: -------------------------------------------------------------------------------- 1 | # IntelliJ tips 2 | 3 | ## Shortcuts 4 | 5 | - `Alt + J` - Select next identifier 6 | - `Alt + F1 + 1` - Select file in Project view 7 | - `Ctrl + Alt + Shift + J` - Select all identifiers 8 | - `Alt + 1` - Toggle project visibility 9 | - `Ctrl + B` - Go to definition 10 | - `Shift + F10` - Run app 11 | - `Shift + Shift` - Select Anything 12 | - `Ctrl + Alt + L` - Reformat code 13 | - `Ctrl + Alt + O` - Organize imports 14 | - `Ctrl + Q` - Quick info 15 | - `Ctrl + Alt + G` - Add carets at the end of selection 16 | - `Ctrl + D` - Duplicate line 17 | - `Ctrl + Shift + Down` - Move statement down 18 | -------------------------------------------------------------------------------- /io/JavaPropertiesEx.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.io.FileInputStream; 4 | import java.io.IOException; 5 | import java.util.Properties; 6 | 7 | public class JavaPropertiesEx { 8 | 9 | public static void main(String[] args) throws IOException { 10 | 11 | var props = new Properties(); 12 | 13 | try (var fis = new FileInputStream("src/resource/db.properties")) { 14 | 15 | props.load(fis); 16 | } 17 | 18 | var url = props.getProperty("db.url"); 19 | var user = props.getProperty("db.user"); 20 | var password = props.getProperty("db.password"); 21 | 22 | System.out.println(url); 23 | System.out.println(user); 24 | System.out.println(password); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /io/JavaReadResourceEx.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.io.IOException; 4 | import java.nio.file.Files; 5 | import java.nio.file.Paths; 6 | 7 | public class JavaReadResourceEx { 8 | 9 | public static void main(String[] args) throws IOException { 10 | 11 | var fileName = "src/resources/words.txt"; 12 | 13 | var lines = Files.readAllLines(Paths.get(fileName)); 14 | 15 | lines.stream().forEach(System.out::println); 16 | 17 | // Files.lines(Paths.get(fileName)).forEach(System.out::println); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /io/JavaReadResourceEx2.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.io.IOException; 4 | import java.net.URISyntaxException; 5 | import java.nio.file.Files; 6 | import java.nio.file.Paths; 7 | 8 | // Reading a file with getResource() 9 | 10 | public class JavaReadResourceEx2 { 11 | 12 | public static void main(String[] args) throws IOException, URISyntaxException { 13 | 14 | var filePath = "resources/words.txt"; 15 | 16 | var uri = JavaReadResourceEx2.class.getClassLoader() 17 | .getResource(filePath).toURI(); 18 | 19 | var mainPath = Paths.get(uri).toString(); 20 | 21 | var lines = Files.readAllLines(Paths.get(mainPath)); 22 | lines.stream().forEach(System.out::println); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /io/README.md: -------------------------------------------------------------------------------- 1 | `Files.list` - non-recursive listing 2 | `Files.walk` - recursive listing 3 | 4 | `SimpleFileVisitor` - complex visiting of files with `Files.walkFileTree` 5 | `Files.newDirectoryStream` - functional, non-recursive iteration over a directory 6 | 7 | Java properties are standard configuration files. The resources are usually placed 8 | into `src/resources` or `src/main/resources`. 9 | 10 | `RandomAccessFile` - allows to directly manipulate the contents of a file 11 | -------------------------------------------------------------------------------- /io/RandomAccessFileEx.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.io.IOException; 4 | import java.io.RandomAccessFile; 5 | 6 | // RandomAccessFile allows to directly manipulate 7 | // the contents of a file 8 | public class RandomAccessFileEx { 9 | 10 | public static void main(String[] args) throws IOException { 11 | 12 | try (var raf = new RandomAccessFile("test.txt", "rw")) { 13 | 14 | raf.writeBytes("golden ring"); 15 | 16 | raf.seek(0); 17 | System.out.println(raf.readLine()); 18 | 19 | raf.seek(7); 20 | raf.writeBytes("eagle"); 21 | 22 | raf.seek(0); 23 | System.out.println(raf.readLine()); 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /io/channel/data1.txt: -------------------------------------------------------------------------------- 1 | abcdefghijklmnopqrstuvwxyz 2 | -------------------------------------------------------------------------------- /io/copyfile/CopyFileChannel.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.io.IOException; 4 | import java.io.RandomAccessFile; 5 | 6 | public class CopyFileChannel { 7 | 8 | public static void main(String[] args) throws IOException { 9 | 10 | var source = new RandomAccessFile("src/resources/bugs.txt", "r"); 11 | var dest = new RandomAccessFile("src/resources/bugs2.txt", "rw"); 12 | 13 | try (var sfc = source.getChannel(); 14 | var dfc = dest.getChannel()) { 15 | 16 | dfc.transferFrom(sfc, 0, sfc.size()); 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /io/copyfile/CopyFileJava7.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.io.File; 4 | import java.io.IOException; 5 | import java.nio.file.Files; 6 | import java.nio.file.StandardCopyOption; 7 | 8 | public class CopyFileJava7 { 9 | 10 | public static void main(String[] args) throws IOException { 11 | 12 | var source = new File("src/resources/bugs.txt"); 13 | var dest = new File("src/resources/bugs2.txt"); 14 | 15 | Files.copy(source.toPath(), dest.toPath(), 16 | StandardCopyOption.REPLACE_EXISTING); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /io/copyfile/CopyFileStream2.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.io.IOException; 4 | import java.nio.file.Files; 5 | import java.nio.file.Paths; 6 | 7 | public class CopyFileStream2 { 8 | 9 | public static void main(String[] args) throws IOException { 10 | 11 | var source = Paths.get("src/resources/bugs.txt"); 12 | var dest = Paths.get("src/resources/bugs2.txt"); 13 | 14 | try (var fis = Files.newInputStream(source); 15 | var fos = Files.newOutputStream(dest)) { 16 | 17 | byte[] buffer = new byte[1024]; 18 | int length; 19 | 20 | while ((length = fis.read(buffer)) > 0) { 21 | 22 | fos.write(buffer, 0, length); 23 | } 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /io/copyfile/bugs.txt: -------------------------------------------------------------------------------- 1 | Assasin bug, Avondale spider, Backswimmer, 2 | Bamboo moth, Banana moth, Bed bug, 3 | Black cocroach, Blue moon, Bumble Bee, 4 | Carpenter Bee, Cattle tick, Cave Weta, 5 | Cicada, Cinnibar, Click beetle, Clothes moth, 6 | Codling moth, Centipede, Earwig, Eucalypt longhorn beetle, 7 | Field Grasshopper, Garden slug, Garden soldier, 8 | German cockroach, German wasp, Giant dragonfly, 9 | Giraffe weevil, Grass grub, Grass looper, 10 | Green planthopper, Green house spider, Gum emperor, 11 | Gum leaf skeletoniser, Hornet, Mealybug, 12 | Mites, Mole Cricket, Monarch butterfly, 13 | Mosquito, Silverfish, Wasp, 14 | Water boatman, Winged weta, Wolf spider, 15 | Yellow Jacket, Yellow Admiral 16 | -------------------------------------------------------------------------------- /io/db.properties: -------------------------------------------------------------------------------- 1 | db.url=jdbc:mysql://localhost:3306/testdb 2 | db.user=user12 3 | db.passwd=s$cret 4 | -------------------------------------------------------------------------------- /io/directorystream/DirectoryStreamGlobEx.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.io.IOException; 4 | import java.nio.file.Files; 5 | import java.nio.file.Paths; 6 | 7 | public class DirectoryStreamGlobEx { 8 | 9 | public static void main(String[] args) throws IOException { 10 | 11 | var dirName = Paths.get("C:/Users/Jano/Downloads"); 12 | 13 | try (var paths = Files.newDirectoryStream(dirName, "*.pdf")) { 14 | 15 | paths.forEach(path -> System.out.println(path)); 16 | } 17 | } 18 | } 19 | 20 | -------------------------------------------------------------------------------- /io/file/JavaCopyFile.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.io.File; 4 | import java.io.IOException; 5 | import java.nio.file.Files; 6 | import java.nio.file.StandardCopyOption; 7 | 8 | public class JavaCopyFile { 9 | 10 | public static void main(String[] args) throws IOException { 11 | 12 | var source = new File("src/resources/bugs.txt"); 13 | var dest = new File("src/resources/bugs2.txt"); 14 | 15 | Files.copy(source.toPath(), dest.toPath(), 16 | StandardCopyOption.REPLACE_EXISTING); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /io/file/JavaDeleteFile.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.io.IOException; 4 | import java.nio.file.Files; 5 | import java.nio.file.Path; 6 | import java.nio.file.Paths; 7 | 8 | public class JavaDeleteFile { 9 | 10 | public static void main(String[] args) throws IOException { 11 | 12 | Path myPath = Paths.get("src/resources/myfile.txt"); 13 | 14 | boolean fileDeleted = Files.deleteIfExists(myPath); 15 | 16 | if (fileDeleted) { 17 | 18 | System.out.println("File deleted"); 19 | } else { 20 | 21 | System.out.println("File does not exist"); 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /io/file/JavaFileSize.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.io.IOException; 4 | import java.nio.file.Files; 5 | import java.nio.file.Path; 6 | import java.nio.file.Paths; 7 | 8 | public class JavaFileSize { 9 | 10 | public static void main(String[] args) throws IOException { 11 | 12 | Path myPath = Paths.get("src/resources/bugs.txt"); 13 | 14 | long fileSize = Files.size(myPath); 15 | 16 | System.out.format("File size: %d bytes%n", fileSize); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /io/file/JavaGetFileOwner.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.io.IOException; 4 | import java.nio.file.Files; 5 | import java.nio.file.Path; 6 | import java.nio.file.Paths; 7 | import java.nio.file.attribute.UserPrincipal; 8 | 9 | public class JavaGetFileOwner { 10 | 11 | public static void main(String[] args) throws IOException { 12 | 13 | Path myPath = Paths.get("src/resources/bugs.txt"); 14 | 15 | UserPrincipal userPrincipal = Files.getOwner(myPath); 16 | String owner = userPrincipal.getName(); 17 | 18 | System.out.println(owner); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /io/file/JavaMoveFile.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.io.IOException; 4 | import java.nio.file.Files; 5 | import java.nio.file.Path; 6 | import java.nio.file.Paths; 7 | 8 | public class JavaMoveFile { 9 | 10 | public static void main(String[] args) throws IOException { 11 | 12 | Path myPath = Paths.get("src/resources/myfile.txt"); 13 | Path myPath2 = Paths.get("src/resources/myfile2.txt"); 14 | 15 | Files.move(myPath, myPath2); 16 | 17 | System.out.println("File moved"); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /io/file/JavaReadFile.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.io.IOException; 4 | import java.nio.charset.StandardCharsets; 5 | import java.nio.file.Files; 6 | import java.nio.file.Path; 7 | import java.nio.file.Paths; 8 | import java.util.List; 9 | 10 | public class JavaReadFile { 11 | 12 | public static void main(String[] args) throws IOException { 13 | 14 | Path myPath = Paths.get("src/resources/bugs.txt"); 15 | 16 | List lines = Files.readAllLines(myPath, StandardCharsets.UTF_8); 17 | 18 | lines.forEach(line -> System.out.println(line)); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /io/file/bugs.txt: -------------------------------------------------------------------------------- 1 | Assasin bug, Avondale spider, Backswimmer, 2 | Bamboo moth, Banana moth, Bed bug, 3 | Black cocroach, Blue moon, Bumble Bee, 4 | Carpenter Bee, Cattle tick, Cave Weta, 5 | Cicada, Cinnibar, Click beetle, Clothes moth, 6 | Codling moth, Centipede, Earwig, Eucalypt longhorn beetle, 7 | Field Grasshopper, Garden slug, Garden soldier, 8 | German cockroach, German wasp, Giant dragonfly, 9 | Giraffe weevil, Grass grub, Grass looper, 10 | Green planthopper, Green house spider, Gum emperor, 11 | Gum leaf skeletoniser, Hornet, Mealybug, 12 | Mites, Mole Cricket, Monarch butterfly, 13 | Mosquito, Silverfish, Wasp, 14 | Water boatman, Winged weta, Wolf spider, 15 | Yellow Jacket, Yellow Admiral 16 | -------------------------------------------------------------------------------- /io/fileslist/FilesListCount.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.io.IOException; 4 | import java.nio.file.Files; 5 | import java.nio.file.Paths; 6 | 7 | public class FilesListCount { 8 | 9 | public static void main(String[] args) throws IOException { 10 | 11 | var homeDir = System.getProperty("user.home") 12 | + System.getProperty("file.separator") + "Downloads"; 13 | 14 | var nOfPdfFiles = Files.list(Paths.get(homeDir)).filter(path -> path.toString() 15 | .endsWith(".pdf")).count(); 16 | 17 | System.out.printf("There are %d PDF files", nOfPdfFiles); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /io/fileslist/FilesListDirectories.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.io.File; 4 | import java.io.IOException; 5 | import java.nio.file.Files; 6 | 7 | public class FilesListDirectories { 8 | 9 | public static void main(String[] args) throws IOException { 10 | 11 | var homeDir = System.getProperty("user.home"); 12 | 13 | Files.list(new File(homeDir).toPath()) 14 | .filter(path -> path.toFile().isDirectory()) 15 | .forEach(System.out::println); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /io/fileslist/FilesListEx.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.io.IOException; 4 | import java.nio.file.Files; 5 | import java.nio.file.Paths; 6 | 7 | public class FilesListEx { 8 | 9 | public static void main(String[] args) throws IOException { 10 | 11 | Files.list(Paths.get(".")) 12 | .forEach(path -> System.out.println(path)); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /io/fileslist/FilesListExtension.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.io.IOException; 4 | import java.nio.file.Files; 5 | import java.nio.file.Paths; 6 | 7 | public class FilesListExtension { 8 | 9 | public static void main(String[] args) throws IOException { 10 | 11 | var homeDir = System.getProperty("user.home") 12 | + System.getProperty("file.separator") + "Downloads"; 13 | 14 | Files.list(Paths.get(homeDir)).filter(path -> path.toString().endsWith(".pdf")) 15 | .forEach(System.out::println); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /io/fileswalk/FilesWalkDirectoriesEx.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.io.IOException; 4 | import java.nio.file.Files; 5 | import java.nio.file.Path; 6 | import java.nio.file.Paths; 7 | import java.util.stream.Stream; 8 | 9 | public class FilesWalkDirectoriesEx { 10 | 11 | public static void main(String[] args) throws IOException { 12 | 13 | var dirName = "C:/Users/Jano/Downloads"; 14 | 15 | try (Stream paths = Files.walk(Paths.get(dirName))) { 16 | paths.filter(Files::isDirectory) 17 | .forEach(System.out::println); 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /io/fileswalk/FilesWalkFileExtensionEx.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.io.IOException; 4 | import java.nio.file.Files; 5 | import java.nio.file.Path; 6 | import java.nio.file.Paths; 7 | import java.util.stream.Stream; 8 | 9 | public class FilesWalkFileExtensionEx { 10 | 11 | public static void main(String[] args) throws IOException { 12 | 13 | var dirName = "C:/Users/Jano/Downloads"; 14 | 15 | try (Stream paths = Files.walk(Paths.get(dirName), 2)) { 16 | paths.map(path -> path.toString()).filter(f -> f.endsWith(".pdf")) 17 | .forEach(System.out::println); 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /io/fileswalk/FilesWalkRegularFilesEx.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.io.IOException; 4 | import java.nio.file.Files; 5 | import java.nio.file.Path; 6 | import java.nio.file.Paths; 7 | import java.util.stream.Stream; 8 | 9 | public class FilesWalkRegularFilesEx { 10 | 11 | public static void main(String[] args) throws IOException { 12 | 13 | var dirName = "C:/Users/Jano/Downloads"; 14 | 15 | try (Stream paths = Files.walk(Paths.get(dirName), 2)) { 16 | paths.filter(Files::isRegularFile) 17 | .forEach(System.out::println); 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /io/input.md: -------------------------------------------------------------------------------- 1 | # Input 2 | 3 | 4 | ## Scanner 5 | 6 | Read input from user from command line 7 | 8 | ```java 9 | import java.io.IOException; 10 | import java.util.Scanner; 11 | 12 | void main() throws IOException { 13 | 14 | try (var scanner = new Scanner(System.in)) { 15 | 16 | System.out.print("Enter your name: "); 17 | String name = scanner.nextLine(); // Read a line of text (including spaces) 18 | 19 | String msg = STR."Hello \{name}!"; 20 | System.out.println(msg); 21 | } 22 | } 23 | ``` 24 | -------------------------------------------------------------------------------- /io/readtext/ReadAllBytesEx.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.io.IOException; 4 | import java.nio.file.Files; 5 | import java.nio.file.Paths; 6 | 7 | public class ReadAllBytesEx { 8 | 9 | public static void main(String[] args) throws IOException { 10 | 11 | var fileName = "src/resources/thermopylae.txt"; 12 | var filePath = Paths.get(fileName); 13 | 14 | byte[] data = Files.readAllBytes(filePath); 15 | var content = new String(data); 16 | 17 | System.out.println(content); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /io/readtext/thermopylae.txt: -------------------------------------------------------------------------------- 1 | The Battle of Thermopylae was fought between an alliance of Greek city-states, 2 | led by King Leonidas of Sparta, and the Persian Empire of Xerxes I over the 3 | course of three days, during the second Persian invasion of Greece. 4 | -------------------------------------------------------------------------------- /io/simplefilevisitor/deletesubtree/FileVisitorDeleteSubTree.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.io.IOException; 4 | import java.nio.file.Files; 5 | import java.nio.file.Paths; 6 | import java.util.HashSet; 7 | 8 | public class FileVisitorDeleteSubTree { 9 | 10 | public static void main(String[] args) throws IOException { 11 | 12 | var myPath = "C:/Users/Jano/Documents/data/"; 13 | var myVisitor = new MyFileVisitor(); 14 | 15 | Files.walkFileTree(Paths.get(myPath), new HashSet<>(), 3, myVisitor); 16 | 17 | } 18 | } -------------------------------------------------------------------------------- /io/streams/filestream/FileInputStreamEx.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.io.FileInputStream; 4 | import java.io.FileNotFoundException; 5 | import java.io.IOException; 6 | 7 | public class FileInputStreamEx { 8 | 9 | public static void main(String[] args) throws FileNotFoundException, IOException { 10 | 11 | String fileName = "/home/janbodnar/tmp/smallfile.txt"; 12 | 13 | try (FileInputStream fis = new FileInputStream(fileName)) { 14 | 15 | char c1 = (char) fis.read(); 16 | char c2 = (char) fis.read(); 17 | char c3 = (char) fis.read(); 18 | 19 | System.out.println(c1); 20 | System.out.println(c2); 21 | System.out.println(c3); 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /io/streams/filestream/FileInputStreamEx2.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.io.FileInputStream; 4 | import java.io.FileNotFoundException; 5 | import java.io.IOException; 6 | 7 | public class FileInputStreamEx2 { 8 | 9 | public static void main(String[] args) throws FileNotFoundException, IOException { 10 | 11 | String fileName = "/home/janbodnar/tmp/smallfile.txt"; 12 | 13 | try (FileInputStream fis = new FileInputStream(fileName)) { 14 | 15 | int i; 16 | 17 | while ((i = fis.read()) != -1) { 18 | System.out.print((char) i); 19 | } 20 | } 21 | 22 | System.out.println(); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /io/streams/filestream/FileOutputStreamAppend.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.io.FileNotFoundException; 4 | import java.io.FileOutputStream; 5 | import java.io.IOException; 6 | 7 | public class FileOutputStreamAppend { 8 | 9 | public static void main(String[] args) throws FileNotFoundException, IOException { 10 | 11 | String fileName = "/home/janbodnar/tmp/newfile.txt"; 12 | 13 | try (FileOutputStream fos = new FileOutputStream(fileName, true)) { 14 | 15 | String text = "Today is a beautiful day"; 16 | byte[] mybytes = text.getBytes(); 17 | 18 | fos.write(mybytes); 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /io/streams/filestream/FileOutputStreamEnconding.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.io.FileOutputStream; 4 | import java.io.IOException; 5 | import java.io.OutputStreamWriter; 6 | import java.nio.charset.StandardCharsets; 7 | 8 | public class FileOutputStreamEnconding { 9 | 10 | public static void main(String[] args) throws IOException { 11 | 12 | var fileName = "src/resources/newfile.txt"; 13 | 14 | try (var fos = new FileOutputStream(fileName); 15 | var osw = new OutputStreamWriter(fos, 16 | StandardCharsets.UTF_8)) { 17 | 18 | var text = "Сегодня был прекрасный день."; 19 | 20 | osw.write(text); 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /io/streams/filestream/FileOutputStreamEx.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.io.FileNotFoundException; 4 | import java.io.FileOutputStream; 5 | import java.io.IOException; 6 | 7 | public class FileOutputStreamEx { 8 | 9 | public static void main(String[] args) throws FileNotFoundException, IOException { 10 | 11 | String fileName = "/home/janbodnar/tmp/newfile.txt"; 12 | 13 | try (FileOutputStream fos = new FileOutputStream(fileName)) { 14 | 15 | String text = "Today is a beautiful day"; 16 | byte[] mybytes = text.getBytes(); 17 | 18 | fos.write(mybytes); 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /io/streams/filestream/JavaFileWriterEx.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.io.FileWriter; 4 | import java.io.IOException; 5 | 6 | // FileWriter has limitation, it uses only default encoding 7 | 8 | public class JavaFileWriterEx { 9 | 10 | public static void main(String[] args) throws IOException { 11 | 12 | try (FileWriter writer = new FileWriter("src/resources/myfile.txt")) { 13 | writer.write("Today is a sunny day"); 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /io/streams/inputstream/JavaInputStreamURL.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.IOException; 5 | import java.io.InputStream; 6 | import java.io.InputStreamReader; 7 | import java.net.URL; 8 | 9 | public class JavaInputStreamURL { 10 | 11 | public static void main(String[] args) throws IOException { 12 | 13 | String webSite = "http://www.something.com"; 14 | URL url = new URL(webSite); 15 | 16 | try (InputStream is = url.openStream(); 17 | BufferedReader br = new BufferedReader( 18 | new InputStreamReader(is))) { 19 | 20 | br.lines().forEach(System.out::println); 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /io/streams/inputstream/ball.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/janbodnar/Java-Advanced/9c90c857505ec7d1fff6979ac8e5fa8ea527c57f/io/streams/inputstream/ball.png -------------------------------------------------------------------------------- /io/streams/inputstream/thermopylae.txt: -------------------------------------------------------------------------------- 1 | The Battle of Thermopylae was fought between an alliance of Greek city-states, 2 | led by King Leonidas of Sparta, and the Persian Empire of Xerxes I over the 3 | course of three days, during the second Persian invasion of Greece. 4 | -------------------------------------------------------------------------------- /io/streams/inputstreamreader/russiantext.txt: -------------------------------------------------------------------------------- 1 | Пе́рвая мирова́я война́ (28 июля 1914 — 11 ноября 1918) — один 2 | из самых широкомасштабных вооружённых конфликтов в истории человечества. 3 | Формальным поводом к войне послужили события в Сараеве, 4 | где 28 июня 1914 года девятнадцатилетний боснийский серб, студент 5 | Гаврило Принцип осуществил покушение, в результате которого был убит 6 | австрийский эрцгерцог Франц Фердинанд и его морганатическая жена София Хотек. 7 | -------------------------------------------------------------------------------- /io/words.txt: -------------------------------------------------------------------------------- 1 | coin 2 | blue 3 | mobile 4 | master 5 | agriculture 6 | automatic 7 | special 8 | water 9 | butterfly 10 | franc 11 | lovely 12 | -------------------------------------------------------------------------------- /iteration/ClassicForEx.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.util.List; 4 | 5 | public class ClassicForEx { 6 | 7 | public static void main(String[] args) { 8 | 9 | var items = List.of("coin", "ball", "lamp", "spoon"); 10 | 11 | for (int i=0; i users = Map.of( 10 | "Jane Smith", "janesmith@example.com", 11 | "John Doe", "jdoe@example.com", 12 | "Peter Black", "peterblack@example.com" 13 | ); 14 | 15 | for (Map.Entry entry : users.entrySet()) { 16 | System.out.printf("%s %s%n", entry.getKey(), entry.getValue()); 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /iteration/HashMapForEachEx.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.util.Map; 4 | 5 | public class HashMapForEachEx { 6 | 7 | public static void main(String[] args) { 8 | 9 | Map users = Map.of( 10 | "Jane Smith", "janesmith@example.com", 11 | "John Doe", "jdoe@example.com", 12 | "Peter Black", "peterblack@example.com" 13 | ); 14 | 15 | users.forEach((key, value) -> System.out.printf("%s %s%n", key, value)); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /iteration/HashMapIteratorEx.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.util.Iterator; 4 | import java.util.Map; 5 | 6 | public class HashMapIteratorEx { 7 | 8 | public static void main(String[] args) { 9 | 10 | Map users = Map.of( 11 | "Jane Smith", "janesmith@example.com", 12 | "John Doe", "jdoe@example.com", 13 | "Peter Black", "peterblack@example.com" 14 | ); 15 | 16 | Iterator it = users.entrySet().iterator(); 17 | 18 | while (it.hasNext()) { 19 | 20 | var entry = (Map.Entry) it.next(); 21 | System.out.printf("%s %s%n", entry.getKey(), entry.getValue()); 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /iteration/ListForEachEx.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.util.List; 4 | 5 | // Java 8 introduced the forEach() method 6 | 7 | public class ListForEachEx { 8 | 9 | public static void main(String[] args) { 10 | 11 | var items = List.of("coin", "ball", "lamp", "spoon"); 12 | 13 | items.forEach(System.out::println); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /iteration/ListIteratorEx.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.util.List; 4 | 5 | // Iterator brings the Iterator design pattern, which is a common behavioral 6 | // pattern used to access the elements of a collection object in sequential 7 | // manner without any need to know its underlying representation. 8 | 9 | public class ListIteratorEx { 10 | 11 | public static void main(String[] args) { 12 | 13 | var items = List.of("coin", "ball", "lamp", "spoon"); 14 | 15 | var it = items.iterator(); 16 | 17 | while (it.hasNext()) { 18 | 19 | System.out.println(it.next()); 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /iteration/foreach/ForEachArray.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.util.Arrays; 4 | 5 | public class ForEachArray { 6 | 7 | public static void main(String[] args) { 8 | 9 | int[] nums = { 3, 4, 2, 1, 6, 7 }; 10 | 11 | Arrays.stream(nums).forEach(System.out::println); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /iteration/foreach/ForEachConsumer.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | import java.util.function.Consumer; 6 | 7 | public class ForEachConsumer { 8 | 9 | public static void main(String[] args) { 10 | 11 | List items = new ArrayList<>(); 12 | 13 | items.add("coins"); 14 | items.add("pens"); 15 | items.add("keys"); 16 | items.add("sheets"); 17 | 18 | items.forEach(new Consumer() { 19 | @Override 20 | public void accept(String name) { 21 | System.out.println(name); 22 | } 23 | }); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /iteration/foreach/ForEachFilterList.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | public class ForEachFilterList { 7 | 8 | public static void main(String[] args) { 9 | 10 | List items = new ArrayList<>(); 11 | 12 | items.add("coins"); 13 | items.add("pens"); 14 | items.add("keys"); 15 | items.add("sheets"); 16 | 17 | items.stream().filter(item -> (item.length() == 4)).forEach(System.out::println); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /iteration/foreach/ForEachListLambda.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | public class ForEachListLambda { 7 | 8 | public static void main(String[] args) { 9 | 10 | List items = new ArrayList<>(); 11 | 12 | items.add("coins"); 13 | items.add("pens"); 14 | items.add("keys"); 15 | items.add("sheets"); 16 | 17 | items.forEach((String name) -> { 18 | System.out.println(name); 19 | }); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /iteration/foreach/ForEachMap.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | 6 | public class ForEachMap { 7 | 8 | public static void main(String[] args) { 9 | 10 | Map items = new HashMap<>(); 11 | 12 | items.put("coins", 3); 13 | items.put("pens", 2); 14 | items.put("keys", 1); 15 | items.put("sheets", 12); 16 | 17 | items.forEach((k, v) -> { 18 | System.out.printf("%s : %d%n", k, v); 19 | }); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /iteration/foreach/ForEachMap2.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | import java.util.function.Consumer; 6 | 7 | public class ForEachMap2 { 8 | 9 | public static void main(String[] args) { 10 | 11 | HashMap map = new HashMap<>(); 12 | 13 | map.put("cups", 6); 14 | map.put("clocks", 2); 15 | map.put("pens", 12); 16 | 17 | Consumer> action = entry -> 18 | { 19 | System.out.printf("key: %s", entry.getKey()); 20 | System.out.printf(" value: %s%n", entry.getValue()); 21 | }; 22 | 23 | map.entrySet().forEach(action); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /iteration/foreach/ForEachSet.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.util.HashSet; 4 | import java.util.Set; 5 | 6 | public class ForEachSet { 7 | 8 | public static void main(String[] args) { 9 | 10 | Set brands = new HashSet<>(); 11 | 12 | brands.add("Nike"); 13 | brands.add("IBM"); 14 | brands.add("Google"); 15 | brands.add("Apple"); 16 | 17 | brands.forEach((e) -> { System.out.println(e); }); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /jdbc/cars_derby.sql: -------------------------------------------------------------------------------- 1 | CREATE TABLE CARS(ID BIGINT NOT NULL PRIMARY KEY GENERATED ALWAYS AS IDENTITY 2 | (START WITH 1, INCREMENT BY 1), NAME VARCHAR(30), PRICE INT); 3 | INSERT INTO CARS(Name, Price) VALUES('Audi', 52642); 4 | INSERT INTO CARS(Name, Price) VALUES('Mercedes', 57127); 5 | INSERT INTO CARS(Name, Price) VALUES('Skoda', 9000); 6 | INSERT INTO CARS(Name, Price) VALUES('Volvo', 29000); 7 | INSERT INTO CARS(Name, Price) VALUES('Bentley', 350000); 8 | INSERT INTO CARS(Name, Price) VALUES('Citroen', 21000); 9 | INSERT INTO CARS(Name, Price) VALUES('Hummer', 41400); 10 | INSERT INTO CARS(Name, Price) VALUES('Volkswagen', 21600); 11 | -------------------------------------------------------------------------------- /jdbc/db.properties: -------------------------------------------------------------------------------- 1 | db.url=jdbc:derby://localhost:1527/testdb 2 | db.user=app 3 | db.passwd=app 4 | -------------------------------------------------------------------------------- /jdbc/images_derby.sql: -------------------------------------------------------------------------------- 1 | CREATE TABLE IMAGES(ID INT PRIMARY KEY, DATA BLOB); 2 | -------------------------------------------------------------------------------- /json/gson/GsonPrettyPrinting.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import com.google.gson.Gson; 4 | import com.google.gson.GsonBuilder; 5 | import java.util.HashMap; 6 | import java.util.Map; 7 | 8 | public class GsonPrettyPrinting { 9 | 10 | public static void main(String[] args) { 11 | 12 | Gson gson = new GsonBuilder() 13 | .setPrettyPrinting() 14 | .create(); 15 | 16 | Map items = new HashMap<>(); 17 | 18 | items.put("chair", 3); 19 | items.put("pencil", 1); 20 | items.put("book", 5); 21 | 22 | gson.toJson(items, System.out); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /json/gson/GsonToJson.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import com.google.gson.Gson; 4 | import java.util.HashMap; 5 | import java.util.Map; 6 | 7 | public class GsonToJson { 8 | 9 | public static void main(String[] args) { 10 | 11 | Map colours = new HashMap<>(); 12 | colours.put(1, "blue"); 13 | colours.put(2, "yellow"); 14 | colours.put(3, "green"); 15 | 16 | Gson gson = new Gson(); 17 | 18 | String output = gson.toJson(colours); 19 | 20 | System.out.println(output); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /json/gson/cars.json: -------------------------------------------------------------------------------- 1 | [ {"name":"Audi","model":"2012","price":22000,"colours":["gray","red","white"]}, 2 | {"name":"Skoda","model":"2016","price":14000,"colours":["black","gray","white"]}, 3 | {"name":"Volvo","model":"2010","price":19500,"colours":["black","silver","beige"]} ] 4 | -------------------------------------------------------------------------------- /json/gson/items.json: -------------------------------------------------------------------------------- 1 | [ {"name":"chair","quantity":3}, {"name":"book","quantity":5}, {"name":"pencil","quantity":1} ] 2 | -------------------------------------------------------------------------------- /json/gson/users.json: -------------------------------------------------------------------------------- 1 | [{"firstName":"Peter","lastName":"Flemming"}, {"firstName":"Nicole","lastName":"White"}, 2 | {"firstName":"Robin","lastName":"Bullock"} ] 3 | -------------------------------------------------------------------------------- /json/jsonp/JsonObjectBuilderEx.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import javax.json.Json; 4 | import java.time.LocalDate; 5 | 6 | public class JsonObjectBuilderEx { 7 | 8 | public static void main(String[] args) { 9 | 10 | var born = LocalDate.of(1992, 3, 2).toString(); 11 | 12 | var json = Json.createObjectBuilder() 13 | .add("name", "John Doe") 14 | .add("occupation", "gardener") 15 | .add("born", born).build(); 16 | 17 | var result = json.toString(); 18 | 19 | System.out.println(result); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /json/jsonp/users.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "name": "John Doe", 4 | "occupation": "gardener", 5 | "born": "1992-03-02" 6 | }, 7 | { 8 | "name": "Brian Flemming", 9 | "occupation": "teacher", 10 | "born": "1967-11-22" 11 | }, 12 | { 13 | "name": "Lucy Black", 14 | "occupation": "accountant", 15 | "born": "1995-04-07" 16 | }, 17 | { 18 | "name": "William Bean", 19 | "occupation": "pilot", 20 | "born": "1977-10-31" 21 | } 22 | ] 23 | -------------------------------------------------------------------------------- /junit5/README.md: -------------------------------------------------------------------------------- 1 | For the examples, we need the `junit-jupiter-engine`, `junit-jupiter-params`, and a current version of `maven-surefire-plugin`. 2 | 3 | Jupiter 4 | 5 | ~~~ 6 | 7 | org.junit.jupiter 8 | junit-jupiter-engine 9 | 5.3.2 10 | test 11 | 12 | 13 | 14 | org.junit.jupiter 15 | junit-jupiter-params 16 | 5.3.2 17 | test 18 | 19 | ~~~ 20 | 21 | Maven surefire plugin 22 | 23 | ~~~ 24 | 25 | maven-surefire-plugin 26 | 3.0.0-M1 27 | 28 | ~~~ 29 | -------------------------------------------------------------------------------- /junit5/beforeall/Application.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import com.zetcode.utils.MathUtils; 4 | 5 | import java.util.List; 6 | 7 | public class Application { 8 | 9 | public static void main(String[] args) { 10 | 11 | var vals = List.of(2, 4, -2, 4, 0, -1, 9, 2, -3); 12 | 13 | System.out.println("Positive values"); 14 | 15 | var poss = MathUtils.positive(vals); 16 | poss.forEach(System.out::println); 17 | 18 | System.out.println("Negative values"); 19 | var negs = MathUtils.negative(vals); 20 | negs.forEach(System.out::println); 21 | 22 | System.out.println("The sum of values"); 23 | var sum = MathUtils.sum(vals); 24 | System.out.println(sum); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /junit5/beforeall/MathUtils.java: -------------------------------------------------------------------------------- 1 | package com.zetcode.utils; 2 | 3 | import java.util.List; 4 | import java.util.stream.Collectors; 5 | 6 | public class MathUtils { 7 | 8 | public static Integer sum(List vals) { 9 | 10 | var sum = vals.stream().reduce(Integer::sum); 11 | 12 | return sum.get(); 13 | } 14 | 15 | public static List positive(List vals) { 16 | 17 | return vals.stream().filter(val -> val > 0).collect(Collectors.toList()); 18 | 19 | } 20 | 21 | public static List negative(List vals) { 22 | 23 | return vals.stream().filter(val -> val < 0).collect(Collectors.toList()); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /junit5/csvfilesource/Application.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import com.zetcode.utils.MathUtils; 4 | 5 | public class Application { 6 | 7 | public static void main(String[] args) { 8 | 9 | int x = 2; 10 | int y = 3; 11 | int z = 4; 12 | 13 | int sum = MathUtils.sum(x, y, z); 14 | 15 | System.out.printf("%d + %d + %d = %d%n",x,y, z, sum ); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /junit5/csvfilesource/MathUtils.java: -------------------------------------------------------------------------------- 1 | package com.zetcode.utils; 2 | 3 | public class MathUtils { 4 | 5 | public static int sum(int x, int y, int z) { 6 | 7 | return x + y + z; 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /junit5/csvfilesource/MathUtilsTest.java: -------------------------------------------------------------------------------- 1 | package com.zetcode.utils; 2 | 3 | import org.junit.jupiter.api.DisplayName; 4 | import org.junit.jupiter.params.ParameterizedTest; 5 | import org.junit.jupiter.params.provider.CsvFileSource; 6 | 7 | import static org.junit.jupiter.api.Assertions.assertEquals; 8 | 9 | class MathUtilsTest { 10 | 11 | @DisplayName("should calculate the correct sum") 12 | @ParameterizedTest(name = "{index} => x={0}, y={1}, z={2} sum={3}") 13 | @CsvFileSource(resources = "/test-data.csv", numLinesToSkip = 1) 14 | void sum(int x, int y, int z, int sum) { 15 | 16 | var mySum = MathUtils.sum(x, y, z); 17 | 18 | assertEquals(mySum, sum); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /junit5/csvfilesource/test-data.csv: -------------------------------------------------------------------------------- 1 | x, y, z, sum 2 | 3, 2, 1, 6 3 | -2, -2, 4, 0 4 | 2, 0, -1, 1 5 | 3, 3, 2, 8 6 | -------------------------------------------------------------------------------- /junit5/parameterized/Application.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import com.zetcode.utils.StringUtils; 4 | 5 | import java.util.List; 6 | 7 | public class Application { 8 | 9 | public static void main(String[] args) { 10 | 11 | var words = List.of("rodor", "book", "Sator Arepo Tenet Opera Rotas", 12 | "kayak", "madam", "level"); 13 | 14 | words.forEach(w -> { 15 | 16 | if (StringUtils.isPalindrome(w)) { 17 | System.out.printf("%s is a palindrome%n", w); 18 | } else { 19 | System.out.printf("%s is not a palindrome%n", w); 20 | } 21 | }); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /junit5/parameterized/StringUtils.java: -------------------------------------------------------------------------------- 1 | package com.zetcode.utils; 2 | 3 | public class StringUtils { 4 | 5 | public static boolean isPalindrome(String text) { 6 | 7 | var cleaned = text.replaceAll("\\s+", "").toLowerCase(); 8 | var plain = new StringBuilder(cleaned); 9 | 10 | var reversed = plain.reverse().toString(); 11 | 12 | return reversed.equals(cleaned); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /junit5/parameterized/StringUtilsTest.java: -------------------------------------------------------------------------------- 1 | package com.zetcode.utils; 2 | 3 | import org.junit.jupiter.params.ParameterizedTest; 4 | import org.junit.jupiter.params.provider.ValueSource; 5 | 6 | import static org.junit.jupiter.api.Assertions.assertTrue; 7 | 8 | class StringUtilsTest { 9 | 10 | @ParameterizedTest 11 | @ValueSource(strings = { "racecar", "radar", "level", "refer", "deified", "civic" }) 12 | void isPalindrome(String word) { 13 | 14 | assertTrue(StringUtils.isPalindrome(word)); 15 | } 16 | 17 | } 18 | 19 | -------------------------------------------------------------------------------- /junit5/repeatedtest/Application.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import com.zetcode.sort.MySelectionSort; 4 | 5 | public class Application { 6 | 7 | public static void main(String[] args) { 8 | 9 | int[] arr1 = {9, 3, 4, 12, 61, 17, 31, 8, 42, 11}; 10 | int[] arr2 = MySelectionSort.doSort(arr1); 11 | 12 | for (int el : arr2) { 13 | 14 | System.out.printf("%d ", el); 15 | } 16 | 17 | System.out.println(); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /junit5/repeatedtest/MySelectionSort.java: -------------------------------------------------------------------------------- 1 | package com.zetcode.sort; 2 | 3 | public class MySelectionSort { 4 | 5 | public static int[] doSort(int[] arr){ 6 | 7 | for (int i = 0; i < arr.length; i++) 8 | { 9 | int idx = i; 10 | 11 | for (int j = i + 1; j < arr.length; j++) { 12 | 13 | if (arr[j] < arr[idx]) { 14 | idx = j; 15 | } 16 | } 17 | 18 | int smallerNumber = arr[idx]; 19 | 20 | arr[idx] = arr[i]; 21 | arr[i] = smallerNumber; 22 | } 23 | 24 | return arr; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /junit5/selenium/README.md: -------------------------------------------------------------------------------- 1 | ``` 2 | 3 | 4 | 5 | org.seleniumhq.selenium 6 | selenium-java 7 | 3.141.59 8 | 9 | 10 | 11 | org.junit.jupiter 12 | junit-jupiter-engine 13 | 5.3.2 14 | test 15 | 16 | 17 | 18 | ``` 19 | -------------------------------------------------------------------------------- /lambda/JavaLambdaEx2.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | @FunctionalInterface 4 | interface MessageRenderer { 5 | 6 | public void render(String msg); 7 | } 8 | 9 | public class JavaLambdaEx2 { 10 | 11 | public static void main(String[] args) { 12 | 13 | MessageRenderer consoleMessageRenderer = (msg)-> { 14 | System.out.println(msg); 15 | }; 16 | 17 | consoleMessageRenderer.render("Today is a sunny day"); 18 | 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /lambda/JavaLambdaEx3.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | @FunctionalInterface 4 | interface Addition { 5 | 6 | public int add(int a, int b); 7 | } 8 | 9 | public class JavaLambdaEx3 { 10 | 11 | public static void main(String[] args) { 12 | 13 | 14 | Addition addition = (x, y) -> (x + y); 15 | 16 | System.out.println(addition.add(4, 5)); 17 | System.out.println(addition.add(5, 5)); 18 | System.out.println(addition.add(6, 6)); 19 | 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /lambda/JavaLambdaEx4.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.util.Arrays; 4 | import java.util.List; 5 | 6 | public class JavaLambdaEx4 { 7 | 8 | public static void main(String[] args) { 9 | 10 | List words = Arrays.asList("astronaut", "actor", "pen", 11 | "book", "story", "cold", "house", "eagle", "cloud"); 12 | 13 | words.stream().filter(word -> word.matches("[abc].*")) 14 | .forEach(e -> System.out.println(e)); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /lambda/JavaLambdaEx6.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.util.List; 4 | import java.util.function.Consumer; 5 | 6 | public class JavaLambdaEx6 { 7 | 8 | public static void main(String[] args) { 9 | 10 | var names = List.of("Peter", "Johanna", "Roger", "Julia"); 11 | 12 | names.forEach(((Consumer) e -> System.out.println(e.toUpperCase())) 13 | .andThen(e -> System.out.println(e.toLowerCase()))); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /lambda/User.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | public class User { 4 | 5 | private String name; 6 | private String email; 7 | 8 | public User(String name, String email) { 9 | this.name = name; 10 | this.email = email; 11 | } 12 | 13 | public String getName() { 14 | return name; 15 | } 16 | 17 | public void setName(String name) { 18 | this.name = name; 19 | } 20 | 21 | public String getEmail() { 22 | return email; 23 | } 24 | 25 | public void setEmail(String email) { 26 | this.email = email; 27 | } 28 | 29 | @Override 30 | public String toString() { 31 | return "User{" + "name=" + name + ", email=" + email + '}'; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /lambda/constructorreference/Cat.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.util.StringJoiner; 4 | 5 | public class Cat { 6 | 7 | private String name; 8 | private Integer age; 9 | 10 | public Cat(String name, Integer age) { 11 | this.name = name; 12 | this.age = age; 13 | } 14 | 15 | @Override 16 | public String toString() { 17 | return new StringJoiner(", ", Cat.class.getSimpleName() + "[", "]") 18 | .add("name='" + name + "'") 19 | .add("age=" + age) 20 | .toString(); 21 | } 22 | } 23 | 24 | -------------------------------------------------------------------------------- /lambda/constructorreference/CatFactory.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | @FunctionalInterface 4 | public interface CatFactory { 5 | 6 | Cat getCat(String name, Integer age); 7 | } 8 | -------------------------------------------------------------------------------- /lambda/constructorreference/ConstructorReferenceEx.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | public class ConstructorReferenceEx { 4 | 5 | public static void main(String[] args) { 6 | 7 | CatFactory catFactory = Cat::new; 8 | var cat = catFactory.getCat("Ollie", 2); 9 | 10 | System.out.println(cat); 11 | } 12 | } 13 | 14 | 15 | -------------------------------------------------------------------------------- /mockito/argumentcaptor/ArgumentCaptorEx.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import com.zetcode.service.MessageService; 4 | 5 | import java.time.LocalDateTime; 6 | 7 | public class ArgumentCaptorEx { 8 | 9 | public static void main(String[] args) { 10 | 11 | var messageService = new MessageService(); 12 | var message = messageService.getMessage("Hello there", LocalDateTime.now()); 13 | 14 | System.out.println(message); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /mockito/argumentcaptor/MessageService.java: -------------------------------------------------------------------------------- 1 | package com.zetcode.service; 2 | 3 | import java.time.LocalDateTime; 4 | 5 | public class MessageService { 6 | 7 | public String getMessage(String message, LocalDateTime dateTime) { 8 | 9 | return String.format("%s %s", message, dateTime); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /mockito/callorder/CallOrder.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import com.zetcode.service.TimeService; 4 | 5 | public class CallOrder { 6 | 7 | public static void main(String[] args) { 8 | 9 | var timeService = new TimeService(); 10 | 11 | System.out.println(timeService.getTime()); 12 | System.out.println(timeService.getDate()); 13 | System.out.println(timeService.getDateTime()); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /mockito/callorder/TimeService.java: -------------------------------------------------------------------------------- 1 | package com.zetcode.service; 2 | 3 | import java.time.LocalDate; 4 | import java.time.LocalDateTime; 5 | import java.time.LocalTime; 6 | 7 | public class TimeService { 8 | 9 | public LocalTime getTime() { 10 | 11 | return LocalTime.now(); 12 | } 13 | 14 | public LocalDate getDate() { 15 | 16 | return LocalDate.now(); 17 | } 18 | 19 | public LocalDateTime getDateTime() { 20 | 21 | return LocalDateTime.now(); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /mockito/helloservice/HelloService.java: -------------------------------------------------------------------------------- 1 | package com.zetcode.service; 2 | 3 | public class HelloService { 4 | 5 | public String getMessage() { 6 | 7 | return "Hello there!"; 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /mockito/helloservice/SimpleEx.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import com.zetcode.service.HelloService; 4 | 5 | public class SimpleEx { 6 | 7 | public static void main(String[] args) { 8 | 9 | var helloService = new HelloService(); 10 | System.out.println(helloService.getMessage()); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /mockito/nofcalls/MessageService.java: -------------------------------------------------------------------------------- 1 | package com.zetcode.service; 2 | 3 | public class MessageService { 4 | 5 | private static int count = 0; 6 | 7 | public void say() { 8 | 9 | count++; 10 | 11 | if (count == 1) { 12 | 13 | System.out.printf("Method called %d time%n", count); 14 | } else { 15 | 16 | System.out.printf("Method called %d times%n", count); 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /mockito/nofcalls/VerifyNumberOfCalls.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import com.zetcode.service.MessageService; 4 | 5 | public class VerifyNumberOfCalls { 6 | 7 | public static void main(String[] args) { 8 | 9 | var messageService = new MessageService(); 10 | 11 | messageService.say(); 12 | messageService.say(); 13 | messageService.say(); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /mockito/throwexception/ThrowException.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import com.zetcode.util.StringUtils; 4 | 5 | public class ThrowException { 6 | 7 | public static void main(String[] args) { 8 | 9 | var word = "falcon"; 10 | 11 | var reversed = new StringUtils().reverse(word); 12 | System.out.println(reversed); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /mongodb/MongoCommand.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import com.mongodb.client.MongoClients; 4 | import org.bson.Document; 5 | 6 | import java.util.Map; 7 | 8 | public class MongoCommand { 9 | 10 | public static void main(String[] args) { 11 | 12 | try (var mongoClient = MongoClients.create("mongodb://localhost:27017")) { 13 | 14 | var database = mongoClient.getDatabase("testdb"); 15 | 16 | var stats = database.runCommand(new Document("dbstats", 1)); 17 | 18 | for (Map.Entry set : stats.entrySet()) { 19 | 20 | System.out.format("%s: %s%n", set.getKey(), set.getValue()); 21 | } 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /mongodb/README.md: -------------------------------------------------------------------------------- 1 | MongoDB Java examples. 2 | 3 | We use `mongo-java-driver`. 4 | 5 | 6 | org.mongodb 7 | mongo-java-driver 8 | 3.10.2 9 | 10 | -------------------------------------------------------------------------------- /net/README.md: -------------------------------------------------------------------------------- 1 | # Java NET 2 | -------------------------------------------------------------------------------- /net/downloadimage/DownloadImageChannel.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.io.FileOutputStream; 4 | import java.io.IOException; 5 | import java.net.URL; 6 | import java.nio.channels.Channels; 7 | 8 | public class DownloadImageChannel { 9 | 10 | public static void main(String[] args) throws IOException { 11 | 12 | var urlFile = "http://httpbin.org/image/jpeg"; 13 | 14 | var url = new URL(urlFile); 15 | 16 | try (var rbc = Channels.newChannel(url.openStream()); 17 | var fos = new FileOutputStream("jackal.jpg");) { 18 | 19 | fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /net/socket/README.md: -------------------------------------------------------------------------------- 1 | `Socket` and `SocketServer` are used for TCP protocol. 2 | `DatagramSocket` and `DatagramPacket` are used for UDP protocol. 3 | 4 | https://zetcode.com/java/socket/ 5 | -------------------------------------------------------------------------------- /patterns/builder/BuilderPatternEx.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.time.LocalDate; 4 | 5 | public class BuilderPatternEx { 6 | 7 | public static void main(String[] args) { 8 | 9 | var task1 = new TaskBuilder().setName("Task A").setDescription("finish book") 10 | .setDueDate(LocalDate.of(2019, 5, 11)).build(); 11 | 12 | System.out.println(task1); 13 | 14 | var task2 = new TaskBuilder().setName("Task B").setDescription("go shopping") 15 | .setDueDate(LocalDate.of(2019, 3, 12)).build(); 16 | 17 | System.out.println(task2); 18 | 19 | 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /patterns/factory/FactoryMethodPatternEx.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | public class FactoryMethodPatternEx { 4 | 5 | public static void main(String[] args) { 6 | 7 | var cat = PetFactory.create(Cat.class, "Micky", "Persian cat"); 8 | System.out.println(cat); 9 | 10 | var dog = PetFactory.create(Dog.class, "Max", "Dalmatian"); 11 | System.out.println(dog); 12 | 13 | var parrot = PetFactory.create(Parrot.class, "Frisky", "Gray parrot"); 14 | System.out.println(parrot); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /patterns/factory/Pet.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | public interface Pet { 4 | 5 | String getName(); 6 | 7 | void setName(String name); 8 | } 9 | -------------------------------------------------------------------------------- /patterns/factory/PetFactory.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | public class PetFactory { 4 | 5 | public static Pet create(Class clazz, String name, String type) { 6 | 7 | if (clazz.equals(Cat.class)) { 8 | 9 | return new Cat(name, type); 10 | } 11 | 12 | if (clazz.equals(Dog.class)) { 13 | 14 | return new Dog(name, type); 15 | } 16 | 17 | if (clazz.equals(Parrot.class)) { 18 | 19 | return new Parrot(name, type); 20 | } 21 | 22 | throw new IllegalArgumentException("Invalid Pet"); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /pitfalls/Associativity.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | public class Associativity { 4 | 5 | public static void main(String[] args) { 6 | 7 | // left-to-right associativity 8 | int val = 9 / 3 * 3; 9 | 10 | System.out.println(val); 11 | 12 | int val2 = 0; 13 | 14 | // right-to-left associativity 15 | val2 *= 3 + 1; 16 | 17 | System.out.println(val2); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /pitfalls/IncrementOperator.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | // there is a subtle difference between the 4 | // prefix and suffix increment operators 5 | 6 | public class IncrementOperator { 7 | 8 | public static void main(String[] args) { 9 | 10 | int num = 0; 11 | 12 | num = num++; 13 | 14 | System.out.println(num); 15 | 16 | num = ++num; 17 | 18 | System.out.println(num); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /pitfalls/IntegerEqual.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | // The == operator compares object references and equals() 4 | // object values. Java internally caches integers 5 | // from -128 to +127, so comparing them with == 'works'. 6 | // we should use equals 7 | 8 | public class IntegerEqual { 9 | 10 | public static void main(String[] args) { 11 | 12 | Integer a = 127; 13 | Integer b = 127; 14 | Integer c = 128; 15 | Integer d = 128; 16 | 17 | System.out.println(a == b); 18 | System.out.println(c == d); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /pitfalls/ListRemoveElement.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.util.ArrayList; 4 | 5 | // java.util.ConcurrentModificationException is thrown 6 | // either use iterator pattern, or removeIf method 7 | 8 | public class ListRemoveElement { 9 | 10 | public static void main(String[] args) { 11 | 12 | var words = new ArrayList<>(); 13 | words.add("forest"); 14 | words.add("wood"); 15 | words.add("sky"); 16 | words.add("book"); 17 | words.add("rock"); 18 | 19 | for (var word : words) { 20 | 21 | if ("rock".equals(word)) { 22 | 23 | words.remove(word); 24 | } 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /pitfalls/StringEqual.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.util.Arrays; 4 | 5 | // the program throws a NullPointerException 6 | // we should swap the sides: "rock".equals(word) 7 | 8 | public class StringEqual { 9 | 10 | public static void main(String[] args) { 11 | 12 | var words = Arrays.asList("wood", "forest", "falcon", null, "sky", "rock"); 13 | 14 | for (var word : words) { 15 | 16 | if (word.equals("rock")) { 17 | 18 | System.out.println("The list contains rock"); 19 | } 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /regex/JavaRegexCaseInsensitive.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.util.List; 4 | import java.util.regex.Matcher; 5 | import java.util.regex.Pattern; 6 | 7 | public class JavaRegexCaseInsensitive { 8 | 9 | public static void main(String[] args) { 10 | 11 | List users = List.of("dog", "Dog", "DOG", "Doggy"); 12 | 13 | Pattern p = Pattern.compile("dog", Pattern.CASE_INSENSITIVE); 14 | 15 | users.forEach((user) -> { 16 | 17 | Matcher m = p.matcher(user); 18 | 19 | if (m.matches()) { 20 | System.out.printf("%s matches%n", user); 21 | } else { 22 | System.out.printf("%s does not match%n", user); 23 | } 24 | }); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /regex/JavaRegexWordBoundaries.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.util.regex.Matcher; 4 | import java.util.regex.Pattern; 5 | 6 | public class JavaRegexWordBoundaries { 7 | 8 | public static void main(String[] args) { 9 | 10 | var text = "This island is beautiful"; 11 | 12 | Pattern p = Pattern.compile("\\bis\\b"); 13 | Matcher matcher = p.matcher(text); 14 | 15 | while (matcher.find()) 16 | { 17 | System.out.printf("%s at %d", matcher.group(), matcher.start()); 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /regex/data.csv: -------------------------------------------------------------------------------- 1 | 22, 1, 3, 4, 5, 17, 18 2 | 2, 13, 4, 1, 8, 4 3 | 3, 21, 4, 5, 1, 48, 9, 42 4 | -------------------------------------------------------------------------------- /resteasy/README.md: -------------------------------------------------------------------------------- 1 | JAX-RS specification is a Java API for RESTful Web Services over the HTTP protocol. 2 | RESTEasy is a portable implementation of these specifications which can run in any 3 | Servlet container. 4 | RESTEasy also comes with additional features on top of plain JAX-RS functionalities. 5 | 6 | *A RESTFul application* follows the REST architectural style, which is used for designing networked applications. 7 | RESTful applications generate HTTP requests performing CRUD (Create/Read/Update/Delete) operations on resources. 8 | RESTFul applications typically return data in JSON or XML format. 9 | 10 | In our examples, we use Resteasy with Undertow server. We include Weld. 11 | -------------------------------------------------------------------------------- /resteasy/context/AppConfig.java: -------------------------------------------------------------------------------- 1 | package com.zetcode.conf; 2 | 3 | import com.zetcode.ws.InfoResource; 4 | import java.util.HashSet; 5 | import java.util.Set; 6 | import javax.ws.rs.ApplicationPath; 7 | import javax.ws.rs.core.Application; 8 | 9 | @ApplicationPath("/") 10 | public class AppConfig extends Application { 11 | 12 | @Override 13 | public Set> getClasses() { 14 | Set> set = new HashSet<>(); 15 | set.add(InfoResource.class); 16 | return set; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /resteasy/context/beans.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | -------------------------------------------------------------------------------- /resteasy/hello/AppConfig.java: -------------------------------------------------------------------------------- 1 | package com.zetcode.conf; 2 | 3 | import com.zetcode.ws.HelloResource; 4 | import java.util.HashSet; 5 | import java.util.Set; 6 | import javax.ws.rs.ApplicationPath; 7 | import javax.ws.rs.core.Application; 8 | 9 | @ApplicationPath("/") 10 | public class AppConfig extends Application { 11 | 12 | @Override 13 | public Set> getClasses() { 14 | Set> set = new HashSet<>(); 15 | set.add(HelloResource.class); 16 | return set; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /resteasy/hello/HelloResource.java: -------------------------------------------------------------------------------- 1 | package com.zetcode.ws; 2 | 3 | import javax.ws.rs.GET; 4 | import javax.ws.rs.Path; 5 | import javax.ws.rs.Produces; 6 | import javax.ws.rs.core.MediaType; 7 | import javax.ws.rs.core.Response; 8 | 9 | @Path("hello") 10 | public class HelloResource { 11 | 12 | @GET 13 | @Produces(MediaType.TEXT_PLAIN) 14 | public Response hello() { 15 | 16 | var msg = "Hello there"; 17 | 18 | return Response.status(200).entity(msg).build(); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /resteasy/hello/beans.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | -------------------------------------------------------------------------------- /resteasy/jsonres/AppConfig.java: -------------------------------------------------------------------------------- 1 | package com.zetcode.conf; 2 | 3 | import com.zetcode.ws.CityResource; 4 | 5 | import javax.ws.rs.ApplicationPath; 6 | import javax.ws.rs.core.Application; 7 | import java.util.HashSet; 8 | import java.util.Set; 9 | 10 | @ApplicationPath("/") 11 | public class AppConfig extends Application { 12 | 13 | @Override 14 | public Set> getClasses() { 15 | Set> set = new HashSet<>(); 16 | set.add(CityResource.class); 17 | return set; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /resteasy/jsonres/ICityService.java: -------------------------------------------------------------------------------- 1 | package com.zetcode.service; 2 | 3 | import com.zetcode.model.City; 4 | import java.util.List; 5 | 6 | public interface ICityService { 7 | 8 | List findAll(); 9 | } 10 | -------------------------------------------------------------------------------- /resteasy/jsonres/beans.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | -------------------------------------------------------------------------------- /resteasy/pathparam/AppConfig.java: -------------------------------------------------------------------------------- 1 | package com.zetcode.conf; 2 | 3 | import com.zetcode.wx.ReverseResource; 4 | 5 | import javax.ws.rs.ApplicationPath; 6 | import javax.ws.rs.core.Application; 7 | import java.util.HashSet; 8 | import java.util.Set; 9 | 10 | @ApplicationPath("/") 11 | public class AppConfig extends Application { 12 | 13 | @Override 14 | public Set> getClasses() { 15 | 16 | Set> set = new HashSet<>(); 17 | set.add(ReverseResource.class); 18 | return set; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /resteasy/pathparam/ReverseResource.java: -------------------------------------------------------------------------------- 1 | package com.zetcode.wx; 2 | 3 | import javax.ws.rs.GET; 4 | import javax.ws.rs.Path; 5 | import javax.ws.rs.PathParam; 6 | import javax.ws.rs.Produces; 7 | import javax.ws.rs.core.MediaType; 8 | import javax.ws.rs.core.Response; 9 | 10 | @Path("reverse") 11 | public class ReverseResource { 12 | 13 | @GET 14 | @Path("/{word}") 15 | @Produces(MediaType.TEXT_PLAIN) 16 | public Response getMsg(@PathParam("word") String msg) { 17 | 18 | var builder = new StringBuilder(msg); 19 | var output = builder.reverse().toString(); 20 | 21 | return Response.status(200).entity(output).build(); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /resteasy/pathparam/beans.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | -------------------------------------------------------------------------------- /resteasy/queryparam/AppConfig.java: -------------------------------------------------------------------------------- 1 | package com.zetcode.conf; 2 | 3 | import com.zetcode.ws.MessageResource; 4 | 5 | import javax.ws.rs.ApplicationPath; 6 | import javax.ws.rs.core.Application; 7 | import java.util.HashSet; 8 | import java.util.Set; 9 | 10 | @ApplicationPath("/") 11 | public class AppConfig extends Application { 12 | 13 | @Override 14 | public Set> getClasses() { 15 | 16 | Set> set = new HashSet<>(); 17 | set.add(MessageResource.class); 18 | return set; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /resteasy/queryparam/beans.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | -------------------------------------------------------------------------------- /resteasy/uploadfile/AppConfig.java: -------------------------------------------------------------------------------- 1 | package com.zetcode.conf; 2 | 3 | import com.zetcode.service.FileUploadService; 4 | 5 | import javax.ws.rs.ApplicationPath; 6 | import javax.ws.rs.core.Application; 7 | import java.util.HashSet; 8 | import java.util.Set; 9 | 10 | @ApplicationPath("/") 11 | public class AppConfig extends Application { 12 | 13 | @Override 14 | public Set> getClasses() { 15 | Set> set = new HashSet<>(); 16 | set.add(FileUploadService.class); 17 | return set; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /resteasy/uploadfile/README.md: -------------------------------------------------------------------------------- 1 | The project needs the `resteasy-multipart-provider` dependency. 2 | 3 | 4 | The project structure: 5 | 6 | ``` 7 | pom.xml 8 | src 9 | ├───main 10 | │ ├───java 11 | │ │ └───com 12 | │ │ └───zetcode 13 | │ │ │ UploadFileEx.java 14 | │ │ ├───conf 15 | │ │ │ AppConfig.java 16 | │ │ ├───form 17 | │ │ │ FileUploadForm.java 18 | │ │ └───service 19 | │ │ FileUploadService.java 20 | │ └───resources 21 | ├───test 22 | │ └───java 23 | └───web 24 | index.html 25 | ``` 26 | -------------------------------------------------------------------------------- /resteasy/weburl/AppConfig.java: -------------------------------------------------------------------------------- 1 | package com.zetcode.conf; 2 | 3 | import com.zetcode.wx.UrlInfoRes; 4 | 5 | import javax.ws.rs.ApplicationPath; 6 | import javax.ws.rs.core.Application; 7 | import java.util.HashSet; 8 | import java.util.Set; 9 | 10 | @ApplicationPath("/") 11 | public class AppConfig extends Application { 12 | 13 | @Override 14 | public Set> getClasses() { 15 | Set> set = new HashSet<>(); 16 | set.add(UrlInfoRes.class); 17 | return set; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /resteasy/weburl/beans.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | -------------------------------------------------------------------------------- /springboot/jpa/onetomany/Application.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class Application { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(Application.class, args); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /springboot/jpa/onetomany/EmployeeRepository.java: -------------------------------------------------------------------------------- 1 | package com.zetcode.repository; 2 | 3 | import com.zetcode.model.Employee; 4 | import org.springframework.data.jpa.repository.JpaRepository; 5 | import org.springframework.stereotype.Repository; 6 | 7 | @Repository 8 | public interface EmployeeRepository extends JpaRepository { 9 | 10 | } 11 | -------------------------------------------------------------------------------- /springboot/jpa/onetomany/TaskRepository.java: -------------------------------------------------------------------------------- 1 | package com.zetcode.repository; 2 | 3 | import com.zetcode.model.Task; 4 | import org.springframework.data.jpa.repository.JpaRepository; 5 | import org.springframework.stereotype.Repository; 6 | 7 | @Repository 8 | public interface TaskRepository extends JpaRepository { 9 | 10 | } 11 | -------------------------------------------------------------------------------- /springboot/jpa/onetomany/application.properties: -------------------------------------------------------------------------------- 1 | spring.main.banner-mode=off 2 | logging.pattern.console=%clr(%d{yy-MM-dd E HH:mm:ss.SSS}){blue} %clr(%-5p) %clr(%logger{0}){blue} %clr(%m){faint}%n 3 | -------------------------------------------------------------------------------- /strings/Base64MimeEncoder.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.io.FileInputStream; 4 | import java.io.IOException; 5 | import java.util.Base64; 6 | 7 | public class Base64MimeEncoder { 8 | 9 | public static void main(String[] args) throws IOException { 10 | 11 | try (var fis = new FileInputStream("src/resources/favicon.ico")) { 12 | 13 | byte[] bytes = fis.readAllBytes(); 14 | var encodedString = Base64.getMimeEncoder().encodeToString(bytes); 15 | 16 | System.out.println(encodedString); 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /strings/ConcatStrings.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | public class ConcatStrings { 4 | 5 | public static void main(String[] args) { 6 | 7 | int age = 34; 8 | String name = "Peter"; 9 | 10 | System.out.println(name + " is " + age + " years old"); 11 | System.out.printf("%s is %d years old%n", name, age); 12 | System.out.println(String.format("%s is %d years old", name, age)); 13 | 14 | var sb = new StringBuilder(name); 15 | sb.append(" is ").append(age).append(" years old"); 16 | System.out.println(sb); 17 | 18 | System.out.println(name.concat(" is ").concat(String.valueOf(age)).concat(" years old")); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /strings/ConcatenateStrings.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | public class ConcatenateStrings { 4 | 5 | public static void main(String[] args) { 6 | 7 | System.out.println("Return" + " of " + "the king."); 8 | System.out.println("Return".concat(" of ").concat("the king.")); 9 | 10 | StringBuilder sb = new StringBuilder(); 11 | sb.append("Return"); 12 | sb.append(" of "); 13 | sb.append("the king."); 14 | 15 | System.out.println(sb); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /strings/Conversions.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | public class Conversions { 4 | 5 | public static void main(String[] args) { 6 | 7 | System.out.format("There are %d %s.%n", 5, "pencils"); 8 | System.out.printf("The rock weighs %f kilograms.%n", 5.345); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /strings/GetBytes.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.util.Arrays; 4 | 5 | public class GetBytes { 6 | 7 | public static void main(String[] args) { 8 | 9 | var text = "Wuthering Heights"; 10 | 11 | byte[] bytes = text.getBytes(); 12 | System.out.println(Arrays.toString(bytes)); 13 | 14 | var text2 = new String(bytes); 15 | System.out.println(text2); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /strings/MutableImmutableEx.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | public class MutableImmutableEx { 4 | 5 | public static void main(String[] args) { 6 | 7 | var word = "rock"; 8 | var word2 = word.replace('r', 'd'); 9 | 10 | System.out.println(word2); 11 | 12 | var builder = new StringBuilder("rock"); 13 | builder.replace(0, 1, "d"); 14 | 15 | System.out.println(builder); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /strings/PrecisionSpecifier.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | public class PrecisionSpecifier { 4 | 5 | public static void main(String[] args) { 6 | 7 | System.out.format("%.3g%n", 0.0000006); 8 | System.out.format("%.3f%n", 54.34263); 9 | System.out.format("%.3s%n", "ZetCode"); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /strings/SplitStringGuavaEx.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import com.google.common.base.Splitter; 4 | 5 | // needs Guava dependency 6 | 7 | public class SplitStringGuavaEx { 8 | 9 | public static void main(String[] args) { 10 | 11 | var input = " falcon, \t\tforest\t, \t\t, moderate, sky\n"; 12 | 13 | var result = Splitter.on(',') 14 | .trimResults() 15 | .omitEmptyStrings() 16 | .splitToList(input); 17 | 18 | result.forEach(System.out::println); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /strings/SplitStringLimitEx.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.util.Arrays; 4 | 5 | public class SplitStringLimitEx { 6 | 7 | public static void main(String[] args) { 8 | 9 | var names = "Jane-Paul-Ferenc-David-Robert-Julia"; 10 | 11 | var output = names.split("-", 4); 12 | 13 | Arrays.stream(output).forEach(System.out::println); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /strings/StringBuilderElements.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | public class StringBuilderElements { 4 | 5 | public static void main(String[] args) { 6 | 7 | StringBuilder sb = new StringBuilder("Misty mountains"); 8 | System.out.println(sb); 9 | 10 | sb.deleteCharAt(sb.length()-1); 11 | System.out.println(sb); 12 | 13 | sb.append('s'); 14 | System.out.println(sb); 15 | 16 | sb.insert(0, 'T'); 17 | sb.insert(1, 'h'); 18 | sb.insert(2, 'e'); 19 | sb.insert(3, ' '); 20 | System.out.println(sb); 21 | 22 | sb.setCharAt(4, 'm'); 23 | System.out.println(sb); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /strings/StringEnds.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | public class StringEnds { 4 | 5 | public static void main(String[] args) { 6 | 7 | var words = "club\nsky\nblue\ncup\ncoin\nnew\ncent\nowl\nfalcon\nwar\nice"; 8 | 9 | var wstream = words.lines(); 10 | wstream.forEach(word -> { 11 | 12 | if (word.endsWith("n") || word.endsWith("y")) { 13 | System.out.println(word); 14 | } 15 | }); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /strings/StringMatch.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | public class StringMatch { 4 | 5 | public static void main(String[] args) { 6 | 7 | var words = """ 8 | book 9 | bookshelf 10 | bookworm 11 | bookcase 12 | bookish 13 | bookkeeper 14 | booklet 15 | bookmark 16 | """; 17 | 18 | var wstream = words.lines(); 19 | 20 | wstream.forEach(word -> { 21 | if (word.matches("book(worm|mark|keeper)?")) { 22 | System.out.println(word); 23 | } 24 | }); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /strings/StringStarts.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | public class StringStarts { 4 | 5 | public static void main(String[] args) { 6 | 7 | var words = "club\nsky\nblue\ncup\ncoin\nnew\ncent\nowl\nfalcon\nwar\nice"; 8 | 9 | var wstream = words.lines(); 10 | wstream.forEach(word -> { 11 | 12 | if (word.startsWith("c")) { 13 | System.out.println(word); 14 | } 15 | }); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /strings/WidthSpecifier.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | public class WidthSpecifier { 4 | 5 | public static void main(String[] args) { 6 | 7 | System.out.println(1); 8 | System.out.println(16); 9 | System.out.println(1655); 10 | System.out.println(16567); 11 | System.out.println(166701); 12 | 13 | System.out.format("%10d%n", 1); 14 | System.out.format("%10d%n", 16); 15 | System.out.format("%10d%n", 1655); 16 | System.out.format("%10d%n", 16567); 17 | System.out.format("%10d%n", 166701); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /strings/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/janbodnar/Java-Advanced/9c90c857505ec7d1fff6979ac8e5fa8ea527c57f/strings/favicon.ico -------------------------------------------------------------------------------- /strings/thermopylae.txt: -------------------------------------------------------------------------------- 1 | The Battle of Thermopylae was fought between an alliance of Greek city-states, 2 | led by King Leonidas of Sparta, and the Persian Empire of Xerxes I over the 3 | course of three days, during the second Persian invasion of Greece. 4 | It took place simultaneously with the naval battle at Artemisium, in August 5 | or September 480 BC, at the narrow coastal pass of Thermopylae. 6 | The Persian invasion was a delayed response to the defeat of the first Persian 7 | invasion of Greece, which had been ended by the Athenian victory at the Battle 8 | of Marathon in 490 BC. Xerxes had amassed a huge army and navy, and set out to 9 | conquer all of Greece. 10 | -------------------------------------------------------------------------------- /templates/README.md: -------------------------------------------------------------------------------- 1 | Working with templates 2 | -------------------------------------------------------------------------------- /templates/emailsfreemarker/customers.csv: -------------------------------------------------------------------------------- 1 | name, amount, duedate 2 | Peter Fonda, 3455, 2018-12-12 3 | John Willis, 2198, 2019-1-10 4 | Lucy Smith, 353, 2018-12-27 5 | John Doe, 55, 2018-12-28 6 | -------------------------------------------------------------------------------- /templates/emailsfreemarker/emails.ftl: -------------------------------------------------------------------------------- 1 | <#setting locale="en_EN"> 2 | <#list customers as customer> 3 | 4 | Dear ${customer.name}, 5 | 6 | we would like to inform you that your debt ${customer.amount?string.currency} is 7 | due ${customer.dueDate?date}. 8 | 9 | Best regards, 10 | 11 | Your bank 12 | 13 | 14 | -------------------------------------------------------------------------------- /validation/README.md: -------------------------------------------------------------------------------- 1 | Bean Validation is a Java specification for data validation in Java. Hibernate Validator 2 | is a reference implementation of the specification. 3 | 4 | Bean Validation 5 | 6 | * allows to define constraints on object models via annotations 7 | * allows write custom constraints in an extensible way 8 | * provides the APIs to validate objects and object graphs 9 | * provides the APIs to validate parameters and return values of methods and constructors 10 | * reports the set of violations (localized) 11 | * runs on Java SE but is integrated in Java EE 6 and later; Bean Validation 2.0 is part of Java EE 8 12 | 13 | For Java 11+, we need to all add JAXB dependencies, which were dropped from Java SE. 14 | -------------------------------------------------------------------------------- /validation/ValidateValue.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import javax.validation.Validation; 4 | import javax.validation.Validator; 5 | import javax.validation.ValidatorFactory; 6 | import javax.validation.constraints.Min; 7 | 8 | public class ValidateValue { 9 | 10 | @Min(5) 11 | private String word; 12 | 13 | public static void main(String[] args) { 14 | 15 | ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); 16 | Validator validator = factory.getValidator(); 17 | 18 | validator.validateValue(ValidateValue.class, "word", "cup") 19 | .forEach(System.out::println); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /validation/customconstraint/checkcase/CaseMode.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | public enum CaseMode { 4 | UPPER, 5 | LOWER; 6 | } 7 | -------------------------------------------------------------------------------- /validation/customconstraint/checkcase/ValidationMessages.properties: -------------------------------------------------------------------------------- 1 | licensePlate.case = Case mode must be {value}. 2 | -------------------------------------------------------------------------------- /validation/customvalidationmessage/ValidationMessages.properties: -------------------------------------------------------------------------------- 1 | licensePlate.size = '${validatedValue}' is an invalid licence plate. It must be between {min} and {max} characters. 2 | licensePlate.notnull = The value must not be null 3 | -------------------------------------------------------------------------------- /validation/localizedvalidationmessages/README.md: -------------------------------------------------------------------------------- 1 | Set the properties' file encoding to UTF8 in IntelliJ IDEA. 2 | -------------------------------------------------------------------------------- /validation/localizedvalidationmessages/ValidationMessages_sk.properties: -------------------------------------------------------------------------------- 1 | licensePlate.size = '${validatedValue}' je invalidná štátna poznávacia značka. ŠPZ musí mať \ 2 | minimum {min} a maximálne {max} znakov. 3 | licensePlate.notnull = Hodnota nesmie byť null. 4 | -------------------------------------------------------------------------------- /web/embeddedjetty/plaintext/JettyServer.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import org.eclipse.jetty.server.Server; 4 | 5 | public class JettyServer { 6 | 7 | public static void main(String[] args) throws Exception { 8 | 9 | var server = new Server(8080); 10 | 11 | server.setHandler(new MyHandler()); 12 | server.start(); 13 | server.join(); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /web/embeddedjetty/secureres/myrealm.properties: -------------------------------------------------------------------------------- 1 | # user name: password, list of roles 2 | admin:aDm79*H4,admin,user 3 | user7:u7&**L1,user 4 | 5 | -------------------------------------------------------------------------------- /web/httpclient/GetRequestAsync.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.net.URI; 4 | import java.net.http.HttpClient; 5 | import java.net.http.HttpRequest; 6 | import java.net.http.HttpResponse; 7 | 8 | public class GetRequestAsync { 9 | 10 | public static void main(String[] args) { 11 | 12 | HttpClient client = HttpClient.newHttpClient(); 13 | HttpRequest request = HttpRequest.newBuilder() 14 | .uri(URI.create("http://webcode.me")) 15 | .build(); 16 | 17 | client.sendAsync(request, HttpResponse.BodyHandlers.ofString()) 18 | .thenApply(HttpResponse::body) 19 | .thenAccept(System.out::println) 20 | .join(); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /web/httpclient/post-undertow/README.md: -------------------------------------------------------------------------------- 1 | We need `undertow-core` and `junit-jupiter`. 2 | -------------------------------------------------------------------------------- /web/httpclient/postreq/README.md: -------------------------------------------------------------------------------- 1 | We need `jackson-databind` dependency. 2 | -------------------------------------------------------------------------------- /web/security/tomcat/containerloginform/README.md: -------------------------------------------------------------------------------- 1 | The example demonstrates how to use container-based login form in Tomcat. The user is defined 2 | in `tomcat-users.xml`. 3 | Need to add SSL support. 4 | 5 | 6 | Project structure: 7 | 8 | ``` 9 | pom.xml 10 | src 11 | ├───main 12 | │ ├───java 13 | │ │ └───com 14 | │ │ └───zetcode 15 | │ │ └───web 16 | │ │ AdminServlet.java 17 | │ │ LogoutServlet.java 18 | │ ├───resources 19 | │ └───webapp 20 | │ │ index.jsp 21 | │ └───WEB-INF 22 | │ error.jsp 23 | │ login.jsp 24 | │ logout.jsp 25 | │ web.xml 26 | └───test 27 | └───java 28 | ``` 29 | 30 | -------------------------------------------------------------------------------- /web/security/tomcat/containerloginform/error.jsp: -------------------------------------------------------------------------------- 1 | <%@ page contentType="text/html;charset=UTF-8" %> 2 | 3 | 4 | Login failure 5 | 6 | 7 |

8 | Failed to log in. 9 |

10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /web/security/tomcat/containerloginform/index.jsp: -------------------------------------------------------------------------------- 1 | <%@ page contentType="text/html;charset=UTF-8" %> 2 | 3 | 4 | Home page 5 | 6 | 7 |

8 | This is home page. 9 |

10 | 11 | <% 12 | if (request.getUserPrincipal() != null) { 13 | out.print(request.getUserPrincipal().getName()); 14 | } 15 | %> 16 | 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /web/servlet/chart/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Chart 5 | 6 | 7 | 8 | 9 | 10 | Show chart 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /web/servlet/deploywebxml/README.md: -------------------------------------------------------------------------------- 1 | Old school servlet deployment with `web.xml` deployment descriptor. It can be 2 | replaced with `@WebServet` annotation. 3 | 4 | -------------------------------------------------------------------------------- /web/servlet/deploywebxml/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 7 | Home page 8 | 9 | 10 | 11 | Show First servlet 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /web/servlet/directorylistings/data.txt: -------------------------------------------------------------------------------- 1 | some data 2 | -------------------------------------------------------------------------------- /web/servlet/directorylistings/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Home page 6 | 7 | 8 | 9 |

10 | Home page 11 |

12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /web/servlet/directorylistings/web.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 8 | 9 | 10 | org.eclipse.jetty.servlet.Default.dirAllowed 11 | true 12 | 13 | 14 | 15 | 16 | 30 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /web/servlet/dispatcher/show.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | HTML Page 5 | 6 | 7 | 8 | 9 |

This is an HTML page

10 | 11 | 12 | -------------------------------------------------------------------------------- /web/servlet/dispatcher/show.jsp: -------------------------------------------------------------------------------- 1 | <%@page contentType="text/html" pageEncoding="UTF-8"%> 2 | 3 | 4 | 5 | 6 | JSP Page 7 | 8 | 9 |

This is a JSP page

10 | 11 | 12 | -------------------------------------------------------------------------------- /web/servlet/errorpage/404.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 404 - not found 5 | 6 | 7 | 8 | 9 | 10 |

404 - not found

11 | 12 |

13 | Document cannot be found 14 |

15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /web/servlet/errorpage/README.md: -------------------------------------------------------------------------------- 1 | 2 | Directory structure: 3 | 4 | ``` 5 | pom.xml 6 | src 7 | ├───main 8 | │ ├───java 9 | │ ├───resources 10 | │ └───webapp 11 | │ │ 404.html 12 | │ │ error.html 13 | │ │ index.html 14 | │ └───WEB-INF 15 | │ web.xml 16 | └───test 17 | └───java 18 | ``` 19 | -------------------------------------------------------------------------------- /web/servlet/errorpage/error.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Error 5 | 6 | 7 | 8 | 9 | 10 |

An error has occurred

11 | 12 |

13 | Generic error. 14 |

15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /web/servlet/errorpage/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Home page 5 | 6 | 7 | 8 | 9 |

10 | 11 | Go to default page 12 |

13 | 14 | 15 | -------------------------------------------------------------------------------- /web/servlet/forwardservlet/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Home page 5 | 6 | 7 | 8 |

9 | Call servlet 10 |

11 | 12 | 13 | -------------------------------------------------------------------------------- /web/servlet/freemarkersimple/index.ftl: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Freemarker test 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | <#list cars as car> 17 | 18 | 19 | 20 | 21 | 22 | 23 |
NamePopulation
${car.name}${car.price}
24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /web/servlet/freemarkersimple/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Get cars 5 | 6 | 7 | 8 | 9 | Get cars 10 | 11 | 12 | -------------------------------------------------------------------------------- /web/servlet/headers/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Headers 5 | 6 | 7 | 8 | 9 | Show headers 10 | 11 | 12 | -------------------------------------------------------------------------------- /web/servlet/plaintext/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Home page 5 | 6 | 7 | 8 | 9 | Call MyServlet 10 | 11 | 12 | -------------------------------------------------------------------------------- /web/servlet/postreq/index.jsp: -------------------------------------------------------------------------------- 1 | <%@page contentType="text/html" pageEncoding="UTF-8"%> 2 | 3 | 4 | 5 | 6 | HTTP POST request 7 | 8 | 9 | 10 |

HTTP POST request

11 | 12 |
13 | 14 | 15 | 16 |
17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /web/servlet/readcsvwar/README.md: -------------------------------------------------------------------------------- 1 | This is a simple web application which returns country names from a CSV file located 2 | within a WAR. We use Opencsv library to load the data and JSP/JSTL to display it. 3 | 4 | Project structure: 5 | ``` 6 | pom.xml 7 | src 8 | ├───main 9 | │ ├───java 10 | │ │ └───com 11 | │ │ └───zetcode 12 | │ │ ├───bean 13 | │ │ │ Country.java 14 | │ │ ├───service 15 | │ │ │ CountryService.java 16 | │ │ └───web 17 | │ │ ReadCountries.java 18 | │ ├───resources 19 | │ │ countries.csv 20 | │ └───webapp 21 | │ index.jsp 22 | │ listCountries.jsp 23 | │ showError.jsp 24 | └───test 25 | └───java 26 | ``` 27 | -------------------------------------------------------------------------------- /web/servlet/readcsvwar/countries.csv: -------------------------------------------------------------------------------- 1 | Name, Population 2 | Slovakia,5429000 3 | Norway,5271000 4 | Croatia,4225000 5 | Russia,143439000 6 | Mexico,122273000 7 | Vietnam,95261000 8 | Sweden,9967000 9 | Iceland,337600 10 | Israel,8622000 11 | Hungary,9830000 12 | Germany,82175700 13 | Japan,126650000 14 | -------------------------------------------------------------------------------- /web/servlet/readcsvwar/index.jsp: -------------------------------------------------------------------------------- 1 | <%@page contentType="text/html" pageEncoding="UTF-8"%> 2 | 3 | 4 | 5 | 6 | List countries 7 | 8 | 9 | List countries 10 | 11 | 12 | -------------------------------------------------------------------------------- /web/servlet/readcsvwar/showError.jsp: -------------------------------------------------------------------------------- 1 | <%@page contentType="text/html" pageEncoding="UTF-8"%> 2 | 3 | 4 | 5 | 6 | Error 7 | 8 | 9 |

No countries found

10 | 11 | 12 | -------------------------------------------------------------------------------- /web/servlet/scss/ICityService.java: -------------------------------------------------------------------------------- 1 | package com.zetcode.service; 2 | 3 | import com.zetcode.bean.City; 4 | 5 | import java.util.List; 6 | 7 | public interface ICityService { 8 | 9 | List findAll(); 10 | } 11 | -------------------------------------------------------------------------------- /web/servlet/scss/index.jsp: -------------------------------------------------------------------------------- 1 | <%@page contentType="text/html" pageEncoding="UTF-8"%> 2 | 3 | 4 | 5 | 6 | Home page 7 | 8 | 9 | 10 | Show cities 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /web/servlet/scss/style.scss: -------------------------------------------------------------------------------- 1 | $myfont: Helvetica, sans-serif; 2 | $mycolor: SteelBlue; 3 | $medium-size: 2em; 4 | 5 | body { 6 | font: $myfont; 7 | } 8 | 9 | .first { 10 | 11 | font-size: $medium-size; 12 | color: $mycolor; 13 | } 14 | -------------------------------------------------------------------------------- /web/servlet/sendimage/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Servlet image 5 | 6 | 7 | 8 | 9 | Get image 10 | 11 | 12 | -------------------------------------------------------------------------------- /web/servlet/sendimage/sid.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/janbodnar/Java-Advanced/9c90c857505ec7d1fff6979ac8e5fa8ea527c57f/web/servlet/sendimage/sid.jpg -------------------------------------------------------------------------------- /web/servlet/sendjson/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Home page 5 | 6 | 7 | 8 | 9 | GetCities 10 | 11 | 12 | -------------------------------------------------------------------------------- /web/servlet/welcomefilelist/default.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Default page 5 | 6 | 7 | 8 | 9 | 10 |

11 | This is default.html 12 |

13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /web/servlet/welcomefilelist/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Home page 5 | 6 | 7 | 8 | 9 | 10 |

11 | This is index.html 12 |

13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /web/servlet/welcomefilelist/index.jsp: -------------------------------------------------------------------------------- 1 | <%@page contentType="text/html" pageEncoding="UTF-8"%> 2 | 3 | 4 | 5 | 6 | Home Page 7 | 8 | 9 |

This is index.jsp

10 | 11 | 12 | -------------------------------------------------------------------------------- /web/undertow/routing/PlainTextHandler.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import io.undertow.server.HttpHandler; 4 | import io.undertow.server.HttpServerExchange; 5 | import io.undertow.util.Headers; 6 | 7 | public class PlainTextHandler implements HttpHandler { 8 | 9 | private final String value; 10 | 11 | public PlainTextHandler(String value) { 12 | this.value = value; 13 | } 14 | 15 | @Override 16 | public void handleRequest(HttpServerExchange exchange) { 17 | 18 | exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "text/plain"); 19 | exchange.getResponseSender().send(value + "\n"); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /web/undertow/routing/RoutingHandlers.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import io.undertow.server.HttpHandler; 4 | import io.undertow.server.HttpServerExchange; 5 | import io.undertow.util.Headers; 6 | 7 | public class RoutingHandlers { 8 | 9 | public static HttpHandler plainTextHandler(String value) { 10 | 11 | return new PlainTextHandler(value); 12 | } 13 | 14 | public static void notFoundHandler(HttpServerExchange exchange) { 15 | 16 | exchange.setStatusCode(404); 17 | exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "text/plain"); 18 | exchange.getResponseSender().send("Page Not Found"); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /web/undertow/sendimage/sid.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/janbodnar/Java-Advanced/9c90c857505ec7d1fff6979ac8e5fa8ea527c57f/web/undertow/sendimage/sid.jpg -------------------------------------------------------------------------------- /web/undertow/servlet/HelloServlet.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import javax.servlet.http.HttpServlet; 4 | import javax.servlet.http.HttpServletRequest; 5 | import javax.servlet.http.HttpServletResponse; 6 | import java.io.IOException; 7 | 8 | public class HelloServlet extends HttpServlet { 9 | 10 | @Override 11 | protected void doGet(HttpServletRequest request, HttpServletResponse response) 12 | throws IOException { 13 | 14 | response.setContentType("text/plain;charset=UTF-8"); 15 | 16 | var msg = getServletConfig().getInitParameter("message"); 17 | var out = response.getOutputStream(); 18 | 19 | out.print(msg); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /web/undertow/simple/UndertowSimple.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import io.undertow.Undertow; 4 | import io.undertow.util.Headers; 5 | 6 | public class UndertowSimple { 7 | 8 | public static void main(String[] args) { 9 | 10 | Undertow server = Undertow.builder() 11 | .addHttpListener(8080, "localhost") 12 | .setHandler(exchange -> { 13 | exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "text/plain"); 14 | exchange.getResponseSender().send("Hello there"); 15 | }).build(); 16 | 17 | server.start(); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /web/undertow/welcomepage/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Home page 6 | 7 | 8 |

9 | Home page. 10 |

11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /words.properties: -------------------------------------------------------------------------------- 1 | w1 = Earth 2 | w2 = ocean 3 | -------------------------------------------------------------------------------- /words_de.properties: -------------------------------------------------------------------------------- 1 | w1 = Erde 2 | w2 = ozean 3 | -------------------------------------------------------------------------------- /words_sk.properties: -------------------------------------------------------------------------------- 1 | w1 = Zem 2 | w2 = oceán 3 | -------------------------------------------------------------------------------- /xml/XMLHttpRequest/fetchdata1.js: -------------------------------------------------------------------------------- 1 | var getXML = (url, callback) => { 2 | 3 | let xhr = new XMLHttpRequest(); 4 | xhr.open('GET', url, true); 5 | xhr.responseType = 'xml'; 6 | 7 | xhr.onload = () => { 8 | 9 | let status = xhr.status; 10 | 11 | if (status == 200) { 12 | callback(null, xhr.response); 13 | } else { 14 | callback(status); 15 | } 16 | }; 17 | 18 | xhr.send(); 19 | }; 20 | 21 | getXML('http://webcode.me/users.xml', (err, data) => { 22 | 23 | if (err != null) { 24 | console.error(err); 25 | } else { 26 | 27 | console.log(data); 28 | } 29 | }); 30 | -------------------------------------------------------------------------------- /xml/XMLHttpRequest/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | Consume XML request 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 |
    18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /xml/dom/users.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Robert 5 | Brown 6 | programmer 7 | 8 | 9 | Pamela 10 | Kyle 11 | writer 12 | 13 | 14 | Lucy 15 | Smith 16 | teacher 17 | 18 | 19 | -------------------------------------------------------------------------------- /xml/jackson/binding/readjson/JacksonReadJsonEx.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import com.fasterxml.jackson.core.type.TypeReference; 4 | import com.fasterxml.jackson.databind.ObjectMapper; 5 | 6 | import java.io.File; 7 | import java.io.IOException; 8 | import java.util.List; 9 | 10 | public class JacksonReadJsonEx { 11 | 12 | public static void main(String[] args) throws IOException { 13 | 14 | var mapper = new ObjectMapper(); 15 | var fileName = new File("src/main/resources/users.json"); 16 | 17 | List users = mapper.readValue(fileName, new TypeReference>(){}); 18 | 19 | users.forEach(System.out::println); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /xml/jackson/binding/readjson/README.md: -------------------------------------------------------------------------------- 1 | We need `jackson-core` and `jackson-databind` dependencies. 2 | -------------------------------------------------------------------------------- /xml/jackson/binding/readjson/Users.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import java.util.List; 4 | 5 | public class Users { 6 | 7 | private List users; 8 | 9 | public List getUsers() { 10 | return users; 11 | } 12 | 13 | public void setUsers(List users) { 14 | this.users = users; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /xml/jackson/binding/readjson/users.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "id": 1, 4 | "firstname": "Robert", 5 | "lastname": "Brown", 6 | "occupation": "programmer" 7 | }, 8 | { 9 | "id": 2, 10 | "firstname": "Pamela", 11 | "lastname": "Kyle", 12 | "occupation": "writer" 13 | }, 14 | { 15 | "id": 3, 16 | "firstname": "Lucy", 17 | "lastname": "Smith", 18 | "occupation": "teacher" 19 | }, 20 | { 21 | "id": 4, 22 | "firstname": "John", 23 | "lastname": "Doe", 24 | "occupation": "gardener" 25 | } 26 | ] 27 | -------------------------------------------------------------------------------- /xml/jackson/binding/writejson/README.md: -------------------------------------------------------------------------------- 1 | We need `jackson-core` and `jackson-databind` dependencies. 2 | -------------------------------------------------------------------------------- /xml/jackson/object2xml/README.md: -------------------------------------------------------------------------------- 1 | We need `jackson-dataformat-xml` and `woodstox-core-asl`. 2 | -------------------------------------------------------------------------------- /xml/jackson/stream/users.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "id": 1, 4 | "firstname": "Robert", 5 | "lastname": "Brown", 6 | "occupation": "programmer" 7 | }, 8 | { 9 | "id": 2, 10 | "firstname": "Pamela", 11 | "lastname": "Kyle", 12 | "occupation": "writer" 13 | }, 14 | { 15 | "id": 3, 16 | "firstname": "Lucy", 17 | "lastname": "Smith", 18 | "occupation": "teacher" 19 | }, 20 | { 21 | "id": 4, 22 | "firstname": "John", 23 | "lastname": "Doe", 24 | "occupation": "gardener" 25 | } 26 | ] 27 | -------------------------------------------------------------------------------- /xml/jackson/treemodel/README.md: -------------------------------------------------------------------------------- 1 | We need `jackson-core` and `jackson-databind`. 2 | -------------------------------------------------------------------------------- /xml/jackson/treemodel/readjson/users.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "id": 1, 4 | "firstname": "Robert", 5 | "lastname": "Brown", 6 | "occupation": "programmer" 7 | }, 8 | { 9 | "id": 2, 10 | "firstname": "Pamela", 11 | "lastname": "Kyle", 12 | "occupation": "writer" 13 | }, 14 | { 15 | "id": 3, 16 | "firstname": "Lucy", 17 | "lastname": "Smith", 18 | "occupation": "teacher" 19 | }, 20 | { 21 | "id": 4, 22 | "firstname": "John", 23 | "lastname": "Doe", 24 | "occupation": "gardener" 25 | } 26 | ] 27 | -------------------------------------------------------------------------------- /xml/sax/JavaReadXmlSaxEx.java: -------------------------------------------------------------------------------- 1 | package com.zetcode; 2 | 3 | import org.xml.sax.SAXException; 4 | 5 | import javax.xml.parsers.ParserConfigurationException; 6 | import java.io.IOException; 7 | 8 | public class JavaReadXmlSaxEx { 9 | 10 | public static void main(String[] args) 11 | throws ParserConfigurationException, SAXException, IOException { 12 | 13 | var handler = new MyHandler(); 14 | var lines = handler.parseUsers(); 15 | 16 | lines.forEach(System.out::println); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /xml/sax/users.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Robert 5 | Brown 6 | programmer 7 | 8 | 9 | Pamela 10 | Kyle 11 | writer 12 | 13 | 14 | Lucy 15 | Smith 16 | teacher 17 | 18 | 19 | -------------------------------------------------------------------------------- /xml/stax/users.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Robert 5 | Brown 6 | programmer 7 | 8 | 9 | Pamela 10 | Kyle 11 | writer 12 | 13 | 14 | Lucy 15 | Smith 16 | teacher 17 | 18 | 19 | John 20 | Doe 21 | gardener 22 | 23 | 24 | -------------------------------------------------------------------------------- /xml/xlsfo/README.md: -------------------------------------------------------------------------------- 1 | For correct IDEA validation, we need to manually donwload "http://www.w3.org/1999/XSL/Format" schema from 2 | https://svn.apache.org/repos/asf/xmlgraphics/fop/trunk/fop/src/foschema/fop.xsd 3 | -------------------------------------------------------------------------------- /xml/xlsfo/contacts.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | Paul Wilson 4 | 5 | Lucy New 6 | 26345745674 7 | 8 | 9 | John Doe 10 | 32452363456 11 | 12 | 13 | -------------------------------------------------------------------------------- /xml/xlst/xml2csv/stylesheet.xls: -------------------------------------------------------------------------------- 1 | 2 | 3 | 5 | 6 | 7 | 8 | 9 | 10 | , , , 11 | 12 | 13 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /xml/xlst/xml2csv/users.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Robert 5 | Brown 6 | programmer 7 | 8 | 9 | Pamela 10 | Kyle 11 | writer 12 | 13 | 14 | Lucy 15 | Smith 16 | teacher 17 | 18 | 19 | John 20 | Doe 21 | gardener 22 | 23 | 24 | -------------------------------------------------------------------------------- /xml/xpath/users.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Robert 5 | Brown 6 | programmer 7 | 8 | 9 | Pamela 10 | Kyle 11 | writer 12 | 13 | 14 | Lucy 15 | Smith 16 | teacher 17 | 18 | 19 | John 20 | Doe 21 | gardener 22 | 23 | 24 | --------------------------------------------------------------------------------