pax_global_header00006660000000000000000000000064140005465030014507gustar00rootroot0000000000000052 comment=b1db053efc562a789d1763656e00723497054228 cactoos-0.49/000077500000000000000000000000001400054650300130765ustar00rootroot00000000000000cactoos-0.49/.0pdd.yml000066400000000000000000000001751400054650300145310ustar00rootroot00000000000000errors: - yegor256@gmail.com # alerts: # github: # - yegor256 tags: - pdd - bug tickets: - inherit-milestone cactoos-0.49/.gitattributes000066400000000000000000000003631400054650300157730ustar00rootroot00000000000000# Check out all text files in UNIX format, with LF as end of line # Don't change this file. If you have any ideas about it, please # submit a separate issue about it and we'll discuss. * text=auto eol=lf *.java ident *.xml ident *.png binary cactoos-0.49/.github/000077500000000000000000000000001400054650300144365ustar00rootroot00000000000000cactoos-0.49/.github/ISSUE_TEMPLATE.md000066400000000000000000000013621400054650300171450ustar00rootroot00000000000000Make sure the title of the issue explains the problem you are having. Also, the description of the issue must clearly explain what is broken, not what you want us to implement. Go through this checklist and make sure you answer "YES" to all points: - You have all pre-requisites listed in README.md installed - You are sure that you are not reporting a duplicate (search all issues) - You say "is broken" or "doesn't work" in the title - You tell us what you are trying to do - You explain the results you are getting - You suggest an alternative result you would like to see This article will help you understand what we are looking for: http://www.yegor256.com/2014/11/24/principles-of-bug-tracking.html Thank you for your contribution! cactoos-0.49/.github/PULL_REQUEST_TEMPLATE.md000066400000000000000000000020431400054650300202360ustar00rootroot00000000000000Many thanks for your contribution, we truly appreciate it. We will appreciate it even more, if you make sure that you can say "YES" to each point in this short checklist: - You made a small amount of changes (less than 100 lines, less than 10 files) - You made changes related to only one bug (create separate PRs for separate problems, or leave puzzles) - You are ready to defend your changes (there will be a code review) - You don't touch what you don't understand - You ran the build locally and it passed - Title begins with the issue's number, then a short title - Description begins with the issue's number, then enumerates the changes - summarized - in bulletpoints - Description does not contain GitHub keywords (https://help.github.com/articles/closing-issues-using-keywords/). - You ran the build locally and it passed (see .travis.yml for all checks performed on PRs) This article will help you understand what we are looking for: http://www.yegor256.com/2015/02/09/serious-code-reviewer.html Thank you for your contribution! cactoos-0.49/.github/workflows/000077500000000000000000000000001400054650300164735ustar00rootroot00000000000000cactoos-0.49/.github/workflows/build.yml000066400000000000000000000025041400054650300203160ustar00rootroot00000000000000name: build on: push: branches: [ master ] pull_request: jobs: test: name: Tests strategy: matrix: os: [ubuntu-18.04, macOS-10.15, windows-2019] java: [8, 11, 15] runs-on: ${{ matrix.os }} steps: - uses: actions/checkout@v2 - name: Java ${{ matrix.java }} uses: actions/setup-java@v1 with: java-version: ${{ matrix.java }} - name: Test run: mvn clean test --errors --batch-mode - name: CodeCov uses: codecov/codecov-action@v1.0.13 if: matrix.os == 'ubuntu-18.04' && github.repository == 'yegor256/cactoos' timeout-minutes: 10 with: file: target/coverage/jacoco.xml lint: name: Linters runs-on: ubuntu-18.04 steps: - uses: actions/checkout@v2 - name: Ruby 2.7 uses: actions/setup-ruby@v1 with: ruby-version: 2.7 - name: Install pdd, xcop run: | gem install pdd gem install xcop - name: JDK 1.8 uses: actions/setup-java@v1 with: java-version: 1.8 - name: Puzzles run: pdd --file=/dev/null - name: Qulice run: mvn -P qulice clean install -DskipTests=true --errors --batch-mode - name: Site run: mvn -P site clean site --errors --batch-mode cactoos-0.49/.gitignore000066400000000000000000000001251400054650300150640ustar00rootroot00000000000000target/ .idea .DS_Store *.iml .project .settings .classpath .recommenders /nbproject/cactoos-0.49/.pdd000066400000000000000000000002171400054650300136460ustar00rootroot00000000000000--source=. --verbose --exclude target/**/* --exclude src/site/resources/**/* --rule min-words:20 --rule min-estimate:15 --rule max-estimate:90 cactoos-0.49/.rultor.yml000066400000000000000000000017611400054650300152330ustar00rootroot00000000000000docker: image: g4s8/rultor:alpine3.10 assets: settings.xml: yegor256/home#assets/cactoos/settings.xml pubring.gpg: yegor256/home#assets/pubring.gpg secring.gpg: yegor256/home#assets/secring.gpg architect: - victornoel - yegor256 merge: script: | pdd -f /dev/null mvn clean install -Pqulice --errors --settings ../settings.xml mvn clean site -Psite --errors --settings ../settings.xml deploy: script: | pdd -f /dev/null mvn clean deploy -Pqulice --errors --settings ../settings.xml release: sensitive: - settings.xml script: |- [[ "${tag}" =~ ^[0-9]+(\.[0-9]+)*$ ]] || exit -1 gpg --import /home/r/pubring.gpg gpg --allow-secret-key-import --no-tty --batch --import /home/r/secring.gpg mvn versions:set "-DnewVersion=${tag}" --settings ../settings.xml git commit -am "${tag}" # note: -Pcactoos is needed to have the gpg and sonar secrets injected mvn clean deploy -Psonar -Pcactoos -Pqulice -Psonatype --errors --settings ../settings.xml cactoos-0.49/2019-12-05.md000066400000000000000000000012721400054650300144570ustar00rootroot00000000000000Cactoos version: 0.43 - released in 05/12/2019 Scope status: 1. Convert status testing assertions to EO ones [30%] 1. Use `Sliced` decorator to compose decorators which uses collection slicing (HeadOf, TailOf, etc) [40%] 1. Qulice update [100%] 1. Fix Rultor x Travis x Appveyor build results [100%] 1. Collections rethinking [0%] Issues: 1. Cactoos and cactoos-matchers have circular dependencies that must be fixed. I suggest merging the projects again. 1. 0crat is taking more than 10 days to remove issues from performers, which is causing some slow in reassigning work from users that abandoned project but didn't quit it formally. Risks 1. Low REV and QA staff delay deliveries [3/3] cactoos-0.49/LICENSE.txt000066400000000000000000000021211400054650300147150ustar00rootroot00000000000000 The MIT License (MIT) Copyright (c) 2017-2020 Yegor Bugayenko Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. cactoos-0.49/README.md000066400000000000000000000265271400054650300143710ustar00rootroot00000000000000 [![Donate via Zerocracy](https://www.0crat.com/contrib-badge/C63314D6Z.svg)](https://www.0crat.com/contrib/C63314D6Z) [![EO principles respected here](https://www.elegantobjects.org/badge.svg)](https://www.elegantobjects.org) [![Managed by Zerocracy](https://www.0crat.com/badge/C63314D6Z.svg)](https://www.0crat.com/p/C63314D6Z) [![DevOps By Rultor.com](http://www.rultor.com/b/yegor256/cactoos)](http://www.rultor.com/p/yegor256/cactoos) [![We recommend IntelliJ IDEA](https://www.elegantobjects.org/intellij-idea.svg)](https://www.jetbrains.com/idea/) [![Build Status](https://travis-ci.org/yegor256/cactoos.svg?branch=master)](https://travis-ci.org/yegor256/cactoos) [![Build status](https://ci.appveyor.com/api/projects/status/8vs8huy61og6jwif?svg=true)](https://ci.appveyor.com/project/yegor256/cactoos) [![Javadoc](http://www.javadoc.io/badge/org.cactoos/cactoos.svg)](http://www.javadoc.io/doc/org.cactoos/cactoos) [![PDD status](http://www.0pdd.com/svg?name=yegor256/cactoos)](http://www.0pdd.com/p?name=yegor256/cactoos) [![Maven Central](https://img.shields.io/maven-central/v/org.cactoos/cactoos.svg)](https://maven-badges.herokuapp.com/maven-central/org.cactoos/cactoos) [![License](https://img.shields.io/badge/license-MIT-green.svg)](https://github.com/yegor256/cactoos/blob/master/LICENSE.txt) [![jpeek report](https://i.jpeek.org/org.cactoos/cactoos/badge.svg)](https://i.jpeek.org/org.cactoos/cactoos/) [![Test Coverage](https://img.shields.io/codecov/c/github/yegor256/cactoos.svg)](https://codecov.io/github/yegor256/cactoos?branch=master) [![SonarQube](https://img.shields.io/badge/sonar-ok-green.svg)](https://sonarcloud.io/dashboard?id=org.cactoos%3Acactoos) [![Hits-of-Code](https://hitsofcode.com/github/yegor256/cactoos)](https://hitsofcode.com/view/github/yegor256/cactoos) Project architect: [@victornoel](https://github.com/victornoel) **ATTENTION**: We're still in a very early alpha version, the API may and _will_ change frequently. Please, use it at your own risk, until we release version 1.0. You can view our progress towards this release [here](https://github.com/yegor256/cactoos/milestone/1). Cactoos is a collection of object-oriented Java primitives. **Motivation**. We are not happy with [JDK](https://en.wikipedia.org/wiki/Java_Development_Kit), [Guava](https://github.com/google/guava), and [Apache Commons](https://commons.apache.org/) because they are procedural and not object-oriented. They do their job, but mostly through static methods. Cactoos is suggesting to do almost exactly the same, but through objects. **Principles**. These are the [design principles](https://www.elegantobjects.org#principles) behind Cactoos. **How to use**. The library has no dependencies. All you need is this (get the latest version [here](https://github.com/yegor256/cactoos/releases)): Maven: ```xml org.cactoos cactoos ``` Gradle: ```groovy dependencies { compile 'org.cactoos:cactoos:' } ``` Java version required: 1.8+. StackOverflow tag is [cactoos](https://stackoverflow.com/questions/tagged/cactoos). ## Input/Output More about it here: [Object-Oriented Declarative Input/Output in Cactoos](http://www.yegor256.com/2017/06/22/object-oriented-input-output-in-cactoos.html). To read a text file in UTF-8: ```java String text = new TextOf( new File("/code/a.txt") ).asString(); ``` To write a text into a file: ```java new LengthOf( new TeeInput( "Hello, world!", new File("/code/a.txt") ) ).intValue(); ``` To read a binary file from classpath: ```java byte[] data = new BytesOf( new ResourceOf("foo/img.jpg") ).asBytes(); ``` ## Text/Strings To format a text: ```java String text = new FormattedText( "How are you, %s?", name ).asString(); ``` To manipulate with a text: ```java // To lower case new Lowered( new TextOf("Hello") ); // To upper case new Upper( new TextOf("Hello") ); ``` ## Iterables/Collections/Lists/Sets More about it here: [Lazy Loading and Caching via Sticky Cactoos Primitives](http://www.yegor256.com/2017/10/17/lazy-loading-caching-sticky-cactoos.html). To filter a collection: ```java Collection filtered = new ListOf<>( new Filtered<>( s -> s.length() > 4, new IterableOf<>("hello", "world", "dude") ) ); ``` To flatten one iterable: ```java new Joined<>( new Mapped<>( iter -> new IterableOf<>( new ListOf<>(iter).toArray(new Integer[]{}) ), new IterableOf<>(1, 2, 3, 4, 5, 6)) ) ); // Iterable ``` To flatten and join several iterables: ```java new Joined<>( new Mapped<>( iter -> new IterableOf<>( new ListOf<>(iter).toArray(new Integer[]{}) ), new Joined<>( new IterableOf<>(new IterableOf<>(1, 2, 3)), new IterableOf<>(new IterableOf<>(4, 5, 6)) ) ) ); // Iterable ``` To iterate a collection: ```java new And( new Mapped<>( new FuncOf<>( input -> { System.out.printf("Item: %s\n", input); } ), new IterableOf<>("how", "are", "you", "?") ) ).value(); ``` Or even more compact: ```java new ForEach( input -> System.out.printf( "Item: %s\n", input ) ).exec("how", "are", "you", "?"); ``` To sort a list of words in the file: ```java List sorted = new ListOf<>( new Sorted<>( new Split( new TextOf( new File("/tmp/names.txt") ), new TextOf("\\s+") ) ) ); ``` To count elements in an iterable: ```java int total = new LengthOf( new IterableOf<>("how", "are", "you") ).intValue(); ``` To create a set of elements by providing variable arguments: ```java final Set unique = new SetOf( "one", "two", "one", "three" ); ``` To create a set of elements from existing iterable: ```java final Set words = new SetOf<>( new IterableOf<>("abc", "bcd", "abc", "ccc") ); ``` To create a sorted iterable with unique elements from existing iterable: ```java final Iterable sorted = new Sorted<>( new SetOf<>( new IterableOf<>("abc", "bcd", "abc", "ccc") ) ); ``` To create a sorted set from existing vararg elements using comparator: ```java final Set sorted = new org.cactoos.set.Sorted<>( (first, second) -> first.compareTo(second), "abc", "bcd", "abc", "ccc", "acd" ); ``` To create a sorted set from existing iterable using comparator: ```java final Set sorted = new org.cactoos.set.Sorted<>( (first, second) -> first.compareTo(second), new IterableOf<>("abc", "bcd", "abc", "ccc", "acd") ); ``` ## Funcs and Procs This is a traditional `foreach` loop: ```java for (String name : names) { System.out.printf("Hello, %s!\n", name); } ``` This is its object-oriented alternative (no streams!): ```java new And( n -> { System.out.printf("Hello, %s!\n", n); }, names ).value(); ``` This is an endless `while/do` loop: ```java while (!ready) { System.out.prinln("Still waiting..."); } ``` Here is its object-oriented alternative: ```java new And( ready -> { System.out.println("Still waiting..."); return !ready; }, new Endless<>(booleanParameter) ).value(); ``` ## Dates and Times From our `org.cactoos.time` package. Our classes are divided in two groups: those that parse strings into date/time objects, and those that format those objects into strings. For example, this is the traditional way of parsing a string into an [OffsetDateTime](https://docs.oracle.com/javase/8/docs/api/java/time/OffsetDateTime.html): ```java final OffsetDateTime date = OffsetDateTime.parse("2007-12-03T10:15:30+01:00"); ``` Here is its object-oriented alternative (no static method calls!) using `OffsetDateTimeOf`, which is a `Scalar`: ```java final OffsetDateTime date = new OffsetDateTimeOf("2007-12-03T10:15:30+01:00").value(); ``` To format an `OffsetDateTime` into a `Text`: ```java final OffsetDateTime date = ...; final String text = new TextOf(date).asString(); ``` ## Our objects vs. their static methods Cactoos | Guava | Apache Commons | JDK 8 ------ | ------ | ------ | ------ `And` | `Iterables.all()` | - | - `Filtered` | `Iterables.filter()` | ? | - `FormattedText` | - | - | `String.format()` `IsBlank` | - | `StringUtils.isBlank()`| - `Joined` | - | - | `String.join()` `LengthOf` | - | - | `String#length()` `Lowered` | - | - | `String#toLowerCase()` `Normalized` | - | `StringUtils.normalize()` | - `Or` | `Iterables.any()` | - | - `Repeated` | - | `StringUtils.repeat()` | - `Replaced` | - | - | `String#replace()` `Reversed` | - | - | `StringBuilder#reverse()` `Rotated` | - | `StringUtils.rotate()`| - `Split` | - | - | `String#split()` `StickyList` | `Lists.newArrayList()` | ? | `Arrays.asList()` `Sub` | - | - | `String#substring()` `SwappedCase` | - | `StringUtils.swapCase()` | - `TextOf` | ? | `IOUtils.toString()` | - `TrimmedLeft` | - | `StringUtils.stripStart()` | - `TrimmedRight` | - | `StringUtils.stripEnd()` | - `Trimmed` | - | `StringUtils.stripAll()` | `String#trim()` `Upper` | - | - | `String#toUpperCase()` ## Questions Ask your questions related to cactoos library on [Stackoverflow](https://stackoverflow.com/questions/ask) with [cactoos](https://stackoverflow.com/tags/cactoos/info) tag. ## How to contribute? Just fork the repo and send us a pull request. Make sure your branch builds without any warnings/issues: ``` mvn clean verify -Pqulice ``` To run a build similar to the CI with Docker only, use: ``` docker run \ --tty \ --interactive \ --workdir=/main \ --volume=${PWD}:/main \ --volume=cactoos-mvn-cache:/root/.m2 \ --rm \ maven:3-jdk-8 \ bash -c "mvn clean install site -Pqulice -Psite --errors; chown -R $(id -u):$(id -g) target/" ``` To remove the cache used by Docker-based build: ``` docker volume rm cactoos-mvn-cache ``` Note: [Checkstyle](https://en.wikipedia.org/wiki/Checkstyle) is used as a static code analyze tool with [checks list](http://checkstyle.sourceforge.net/checks.html) in GitHub precommits. ## Contributors - [@yegor256](https://github.com/yegor256) as Yegor Bugayenko ([Blog](http://www.yegor256.com)) - [@g4s8](https://github.com/g4s8) as Kirill Che. (g4s8.public@gmail.com) - [@fabriciofx](https://github.com/fabriciofx) as Fabrício Cabral - [@englishman](https://github.com/englishman) as Andriy Kryvtsun - [@VsSekorin](https://github.com/VsSekorin) as Vseslav Sekorin - [@DronMDF](https://github.com/DronMDF) as Andrey Valyaev - [@dusan-rychnovsky](https://github.com/dusan-rychnovsky) as Dušan Rychnovský ([Blog](http://blog.dusanrychnovsky.cz/)) - [@timmeey](https://github.com/timmeey) as Tim Hinkes ([Blog](https://blog.timmeey.de)) - [@alex-semenyuk](https://github.com/alex-semenyuk) as Alexey Semenyuk - [@smallcreep](https://github.com/smallcreep) as Ilia Rogozhin - [@memoyil](https://github.com/memoyil) as Mehmet Yildirim - [@llorllale](https://github.com/llorllale) as George Aristy - [@driver733](https://github.com/driver733) as Mikhail Yakushin - [@izrik](https://github.com/izrik) as Richard Sartor - [@Vatavuk](https://github.com/Vatavuk) as Vedran Grgo Vatavuk - [@dgroup](https://github.com/dgroup) as Yurii Dubinka - [@iakunin](https://github.com/iakunin) as Maksim Iakunin - [@fanifieiev](https://github.com/fanifieiev) as Fevzi Anifieiev - [@victornoel](https://github.com/victornoel) as Victor Noël - [@paulodamaso](https://github.com/paulodamaso) as Paulo Lobo cactoos-0.49/pom.xml000066400000000000000000000247641400054650300144300ustar00rootroot00000000000000 4.0.0 com.jcabi parent 0.50.5 org.cactoos cactoos 0.49 jar cactoos Object-oriented Java Primitives https://github.com/yegor256/cactoos 2017 Cactoos https://github.com/yegor256/cactoos MIT https://raw.githubusercontent.com/yegor256/cactoos/master/LICENSE.txt site 1 Yegor Bugayenko yegor256@gmail.com yegor256.com http://www.yegor256.com Architect Developer -7 GitHub https://github.com/yegor256/cactoos/issues scm:git:git@github.com:yegor256/cactoos.git scm:git:git@github.com:yegor256/cactoos.git https://github.com/yegor256/cactoos rultor http://www.rultor.com/s/cactoos github-pages https://github.com/yegor256/cactoos org.takes takes 1.1 test org.llorllale cactoos-matchers 0.22 test org.cactoos cactoos com.google.code.findbugs annotations 3.0.1 provided net.jcip jcip-annotations com.google.code.findbugs jsr305 org.junit.vintage junit-vintage-engine test junit junit 4.13 test org.hamcrest hamcrest-core 1.3 test org.apache.maven.plugins maven-verifier-plugin 1.1 main package verify src/verifier/verifications.xml org.apache.maven.plugins maven-verifier-plugin org.jacoco jacoco-maven-plugin 0.8.6 file ${project.build.directory}/coverage jacoco-initialize prepare-agent jacoco-check test check report BUNDLE INSTRUCTION COVEREDRATIO 0.61 LINE COVEREDRATIO 0.65 BRANCH COVEREDRATIO 0.65 COMPLEXITY COVEREDRATIO 0.57 METHOD COVEREDRATIO 0.57 CLASS MISSEDCOUNT 15 qulice com.qulice qulice-maven-plugin 0.18.19 checkstyle:/src/site/resources/.* de.thetaphi forbiddenapis 2.6 ./src/test/resources/forbidden-apis.txt org/cactoos/bytes/*.class org/cactoos/map/*.class org/cactoos/time/*.class org/cactoos/collection/*.class org/cactoos/experimental/*.class org/cactoos/func/*.class testCheck sonar https://sonarcloud.io yegor256-github org.sonarsource.scanner.maven sonar-maven-plugin 3.7.0.1746 verify sonar cactoos-0.49/src/000077500000000000000000000000001400054650300136655ustar00rootroot00000000000000cactoos-0.49/src/main/000077500000000000000000000000001400054650300146115ustar00rootroot00000000000000cactoos-0.49/src/main/java/000077500000000000000000000000001400054650300155325ustar00rootroot00000000000000cactoos-0.49/src/main/java/org/000077500000000000000000000000001400054650300163215ustar00rootroot00000000000000cactoos-0.49/src/main/java/org/cactoos/000077500000000000000000000000001400054650300177545ustar00rootroot00000000000000cactoos-0.49/src/main/java/org/cactoos/BiFunc.java000066400000000000000000000035131400054650300217670ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos; /** * Function that accepts two arguments. * *

If you don't want to have any checked exceptions being thrown * out of your {@link BiFunc}, you can use * {@link org.cactoos.func.UncheckedBiFunc} decorator. Also * you may try {@link org.cactoos.func.IoCheckedBiFunc}.

* *

There is no thread-safety guarantee. * * @param Type of input * @param Type of input * @param Type of output * @since 0.9 */ public interface BiFunc { /** * Apply it. * @param first The first argument * @param second The second argument * @return The result * @throws Exception If fails */ Z apply(X first, Y second) throws Exception; } cactoos-0.49/src/main/java/org/cactoos/BiProc.java000066400000000000000000000041611400054650300217770ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos; import org.cactoos.proc.IoCheckedBiProc; import org.cactoos.proc.UncheckedBiProc; /** * Proc that accepts two arguments. * *

If you don't want to have any checked exceptions being thrown * out of your {@link BiProc}, you can use * {@link UncheckedBiProc} decorator. Also * you may try {@link IoCheckedBiProc}.

* *

There is no thread-safety guarantee. * * @param Type of input * @param Type of input * @since 0.20 * @todo #1445:30min Introduce BiProcOf on the model of ProcOf, FuncOf, etc * with constructors taking Func, BiFunc, Proc and BiProc as primary. * Add tests similar to those of ProcOfTest, FuncOfTest, etc to fully cover * the implementation. Use it where needed, for example in AndWithIndexTest. */ public interface BiProc { /** * Execute it. * @param first The first argument * @param second The second argument * @throws Exception If fails */ void exec(X first, Y second) throws Exception; } cactoos-0.49/src/main/java/org/cactoos/Bytes.java000066400000000000000000000027041400054650300217100ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos; /** * Bytes. * *

There is no thread-safety guarantee. * * @see org.cactoos.bytes.BytesOf * @since 0.1 */ public interface Bytes { /** * Convert it to the byte array. * @return The byte array * @throws Exception If fails */ byte[] asBytes() throws Exception; } cactoos-0.49/src/main/java/org/cactoos/Fallback.java000066400000000000000000000067101400054650300223220ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos; import org.cactoos.iterable.IterableOf; import org.cactoos.iterable.Mapped; import org.cactoos.scalar.InheritanceLevel; import org.cactoos.scalar.MinOf; /** * Fallback from a {@link Throwable}. * *

There is no thread-safety guarantee. * * @param Type of input * @since 1.0 */ public interface Fallback extends Func { /** * Calculate level of support of the given exception type. * @param exception Exception * @return Level of support: greater or equals to 0 if the target * is supported and {@link Integer#MIN_VALUE} otherwise */ int support(Throwable exception); /** * Fallback from exception. * *

There is no thread-safety guarantee. * * @param Type of result * @since 1.0 */ final class From implements Fallback { /** * The list of exceptions supported by this instance. */ private final Iterable> exceptions; /** * Function that converts exceptions to the required type. */ private final Func func; /** * Ctor. * @param exp Supported exception type * @param func Function that converts the given exception into required one */ @SuppressWarnings("unchecked") public From(final Class exp, final Func func) { this(new IterableOf<>(exp), func); } /** * Ctor. * @param exps Supported exceptions types * @param func Function that converts the given exception into required one */ public From( final Iterable> exps, final Func func) { this.exceptions = exps; this.func = func; } @Override public T apply(final Throwable exp) throws Exception { return this.func.apply(exp); } @Override public int support(final Throwable exception) { return new MinOf( new Mapped<>( supported -> new InheritanceLevel(exception.getClass(), supported).value(), this.exceptions ) ).intValue(); } } } cactoos-0.49/src/main/java/org/cactoos/Func.java000066400000000000000000000037671400054650300215270ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos; /** * Function. * *

If you don't want to have any checked exceptions being thrown * out of your {@link Func}, you can use * {@link org.cactoos.func.UncheckedFunc} decorator. Also * you may try {@link org.cactoos.func.IoCheckedFunc}.

* *

If you want to cache the result of the {@link Func} and * make sure it doesn't calculate anything twice, you can use * {@link org.cactoos.func.StickyFunc} decorator.

* *

There is no thread-safety guarantee. * * @param Type of input * @param Type of output * @see org.cactoos.func.StickyFunc * @see org.cactoos.func.UncheckedFunc * @see org.cactoos.func.IoCheckedFunc * @since 0.1 */ public interface Func { /** * Apply it. * @param input The argument * @return The result * @throws Exception If fails */ Y apply(X input) throws Exception; } cactoos-0.49/src/main/java/org/cactoos/Input.java000066400000000000000000000035761400054650300217310ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos; import java.io.InputStream; /** * Input. * *

Here is for example how {@link Input} can be used * in order to read the content of a text file:

* *
 String content = new TextOf(
 *   new InputOf(new File("/tmp/names.txt"))
 * ).asString();
* *

Here {@link org.cactoos.io.InputOf} implements * {@link Input} and behaves like * one, providing read-only access to * the encapsulated {@link java.io.File}.

* *

There is no thread-safety guarantee. * * @see org.cactoos.io.InputOf * @since 0.1 */ public interface Input { /** * Get read access to it. * @return InputStream to read from * @throws Exception If something goes wrong */ InputStream stream() throws Exception; } cactoos-0.49/src/main/java/org/cactoos/Output.java000066400000000000000000000042401400054650300221170ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos; import java.io.OutputStream; import org.cactoos.io.OutputTo; import org.cactoos.io.TeeInput; /** * Output. * *

Here is for example how {@link Output} can be used * together with {@link Input} in order to modify the content * of a text file:

* *
 new LengthOf(
 *   new TeeInput(
 *     new InputOf(new TextOf("Hello, world!")),
 *     new OutputTo(new File("/tmp/names.txt"))
 *   )
 * ).asValue();
* *

Here {@link OutputTo} implements {@link Output} and behaves like * one, providing write-only access to the encapsulated * {@link java.io.File}. The {@link TeeInput} copies the content of the * input to the output. The {@link org.cactoos.scalar.LengthOf} * calculates the size of the copied data.

* *

There is no thread-safety guarantee. * * @see OutputTo * @since 0.1 */ public interface Output { /** * Get write access to it. * @return OutputStream to write to * @throws Exception If something goes wrong */ OutputStream stream() throws Exception; } cactoos-0.49/src/main/java/org/cactoos/Proc.java000066400000000000000000000033501400054650300215230ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos; import org.cactoos.proc.IoCheckedProc; import org.cactoos.proc.UncheckedProc; /** * Procedure. * *

If you don't want to have any checked exceptions being thrown * out of your {@link Proc}, you can use * {@link UncheckedProc} decorator. Also * you may try {@link IoCheckedProc}.

* *

There is no thread-safety guarantee. * * @param Type of input * @see org.cactoos.func.FuncOf * @since 0.1 */ public interface Proc { /** * Execute it. * @param input The argument * @throws Exception If fails */ void exec(X input) throws Exception; } cactoos-0.49/src/main/java/org/cactoos/Scalar.java000066400000000000000000000036621400054650300220330ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos; import org.cactoos.scalar.IoChecked; import org.cactoos.scalar.Sticky; import org.cactoos.scalar.Unchecked; /** * Scalar. * *

If you don't want to have any checked exceptions being thrown * out of your {@link Scalar}, you can use * {@link Unchecked} decorator. Also * you may try {@link IoChecked}.

* *

If you want to cache the result of the {@link Scalar} and * make sure it doesn't calculate anything twice, you can use * {@link Sticky} decorator.

* *

There is no thread-safety guarantee. * * @param Type of result * @see Sticky * @see Unchecked * @see IoChecked * @since 0.1 */ public interface Scalar { /** * Convert it to the value. * @return The value * @throws Exception If fails */ T value() throws Exception; } cactoos-0.49/src/main/java/org/cactoos/Text.java000066400000000000000000000031411400054650300215420ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos; /** * Text. * *

If you don't want to have any checked exceptions being thrown * out of your {@link Text}, you can use * {@link org.cactoos.text.UncheckedText} decorator.

* *

There is no thread-safety guarantee. * * @see org.cactoos.text.TextOf * @since 0.1 */ public interface Text { /** * Convert it to the string. * @return The string * @throws Exception If fails */ String asString() throws Exception; } cactoos-0.49/src/main/java/org/cactoos/bytes/000077500000000000000000000000001400054650300211025ustar00rootroot00000000000000cactoos-0.49/src/main/java/org/cactoos/bytes/Base64Bytes.java000066400000000000000000000040731400054650300240040ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.bytes; import java.util.Base64; import org.cactoos.Bytes; /** * Decodes all origin bytes using the Base64 encoding scheme. * * @since 0.20.2 */ public final class Base64Bytes implements Bytes { /** * Origin bytes. */ private final Bytes origin; /** * The decoder. */ private final Base64.Decoder decoder; /** * Ctor uses a RFC4648 {@link java.util.Base64.Decoder}. * * @param origin Origin bytes */ public Base64Bytes(final Bytes origin) { this(origin, Base64.getDecoder()); } /** * Ctor. * * @param origin Origin bytes. * @param dec Decoder to use. */ public Base64Bytes(final Bytes origin, final Base64.Decoder dec) { this.origin = origin; this.decoder = dec; } @Override public byte[] asBytes() throws Exception { return this.decoder.decode(this.origin.asBytes()); } } cactoos-0.49/src/main/java/org/cactoos/bytes/BytesBase64.java000066400000000000000000000041101400054650300237740ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.bytes; import java.util.Base64; import org.cactoos.Bytes; /** * Encodes all origin bytes using the Base64 encoding scheme. * * @since 0.20.2 */ public final class BytesBase64 implements Bytes { /** * Origin bytes. */ private final Bytes origin; /** * The encoder to use. */ private final Base64.Encoder encoder; /** * Ctor uses a RFC4648 {@link java.util.Base64.Encoder}. * * @param origin Origin bytes. */ public BytesBase64(final Bytes origin) { this(origin, Base64.getEncoder()); } /** * Ctor. * * @param origin Origin bytes. * @param enc The encoder to use. */ public BytesBase64(final Bytes origin, final Base64.Encoder enc) { this.origin = origin; this.encoder = enc; } @Override public byte[] asBytes() throws Exception { return this.encoder.encode(this.origin.asBytes()); } } cactoos-0.49/src/main/java/org/cactoos/bytes/BytesOf.java000066400000000000000000000223731400054650300233270ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.bytes; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.InputStream; import java.io.PrintStream; import java.io.Reader; import java.nio.ByteBuffer; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.nio.file.Path; import java.util.Collection; import java.util.Iterator; import java.util.List; import org.cactoos.Bytes; import org.cactoos.Input; import org.cactoos.Text; import org.cactoos.io.InputOf; import org.cactoos.iterable.IterableOf; import org.cactoos.list.ListOf; /** * A {@link Bytes} that encapsulates other sources of data. * *

There is no thread-safety guarantee. * * @since 0.12 */ public final class BytesOf implements Bytes { /** * The bytes. */ private final Bytes origin; /** * Ctor. * @param input The input */ public BytesOf(final Input input) { this(new InputAsBytes(input)); } /** * Ctor. * @param input The input * @since 0.29.2 */ public BytesOf(final InputStream input) { this(new InputAsBytes(new InputOf(input))); } /** * Ctor. * @param file The input * @since 0.13 */ public BytesOf(final File file) { this(new InputOf(file)); } /** * Ctor. * @param path The input * @since 0.13 */ public BytesOf(final Path path) { this(new InputOf(path)); } /** * Ctor. * @param input The input * @param max Max length of the buffer for reading */ public BytesOf(final Input input, final int max) { this(new InputAsBytes(input, max)); } /** * Ctor. * @param rdr Reader */ public BytesOf(final Reader rdr) { this(new ReaderAsBytes(rdr)); } /** * Ctor. * @param rdr Reader * @param charset Charset */ public BytesOf(final Reader rdr, final Charset charset) { this(new ReaderAsBytes(rdr, charset)); } /** * Ctor. * @param rdr Reader * @param charset Charset */ public BytesOf(final Reader rdr, final CharSequence charset) { this(new ReaderAsBytes(rdr, charset)); } /** * Ctor. * @param rdr Reader * @param charset Charset * @param max Buffer size */ public BytesOf(final Reader rdr, final Charset charset, final int max) { this(new ReaderAsBytes(rdr, charset, max)); } /** * Ctor. * @param rdr Reader * @param max Buffer size * @since 0.13.3 */ public BytesOf(final Reader rdr, final int max) { this(new ReaderAsBytes(rdr, max)); } /** * Ctor. * @param rdr Reader * @param charset Charset * @param max Buffer size */ public BytesOf(final Reader rdr, final CharSequence charset, final int max) { this(new ReaderAsBytes(rdr, charset, max)); } /** * Ctor. * * @param input The source */ public BytesOf(final CharSequence input) { this(input, StandardCharsets.UTF_8); } /** * Ctor. * * @param input The source * @param charset The charset */ public BytesOf(final CharSequence input, final Charset charset) { this(() -> input.toString().getBytes(charset)); } /** * Ctor. * * @param input The source * @param charset The charset */ public BytesOf(final CharSequence input, final CharSequence charset) { this(() -> input.toString().getBytes(charset.toString())); } /** * Ctor. * * @param chars The chars */ public BytesOf(final char... chars) { this(chars, StandardCharsets.UTF_8); } /** * Ctor. * * @param chars The chars * @param charset The charset */ public BytesOf(final char[] chars, final Charset charset) { this(new String(chars), charset); } /** * Ctor. * * @param chars The chars * @param charset The charset */ public BytesOf(final char[] chars, final CharSequence charset) { this(new String(chars), charset); } /** * Ctor. * @param text The source */ public BytesOf(final Text text) { this(text, StandardCharsets.UTF_8); } /** * Ctor. * @param text The source * @param charset The charset */ public BytesOf(final Text text, final Charset charset) { this(() -> text.asString().getBytes(charset)); } /** * Ctor. * @param text The source * @param charset The charset */ public BytesOf(final Text text, final CharSequence charset) { this(() -> text.asString().getBytes(charset.toString())); } /** * Ctor. * @param error The exception to serialize */ public BytesOf(final Throwable error) { this(error, StandardCharsets.UTF_8); } /** * Ctor. * @param error The exception to serialize * @param charset Charset */ public BytesOf(final Throwable error, final Charset charset) { this(error, charset.name()); } /** * Ctor. * @param error The exception to serialize * @param charset Charset */ public BytesOf(final Throwable error, final CharSequence charset) { this( () -> { try ( ByteArrayOutputStream baos = new ByteArrayOutputStream() ) { error.printStackTrace( new PrintStream(baos, true, charset.toString()) ); return baos.toByteArray(); } } ); } /** * Ctor. * @param strace The stack trace * @since 0.29 */ public BytesOf(final StackTraceElement... strace) { this(strace, StandardCharsets.UTF_8); } /** * Ctor. * @param strace The stack trace * @param charset Charset * @since 0.29 */ public BytesOf(final StackTraceElement[] strace, final Charset charset) { this(strace, charset.name()); } /** * Ctor. * @param strace The stack trace * @param charset Charset * @since 0.29 */ public BytesOf(final StackTraceElement[] strace, final CharSequence charset) { this( () -> { try ( ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream stream = new PrintStream( baos, true, charset.toString() ) ) { for (final StackTraceElement element : strace) { stream.append(element.toString()); stream.append("\n"); } return baos.toByteArray(); } } ); } /** * Ctor. * * @param bytes Bytes to encapsulate */ public BytesOf(final byte... bytes) { this(() -> bytes); } /** * Ctor. * * @param iterator Iterator of bytes */ public BytesOf(final Iterator iterator) { this(new IterableOf<>(iterator)); } /** * Ctor. * * @param bytes Iterable of bytes */ public BytesOf(final Iterable bytes) { this(() -> { final List concrete = new ListOf<>(bytes); final ByteBuffer buf = ByteBuffer.allocate( concrete.size() ); concrete.forEach(buf::put); return buf.array(); }); } /** * Ctor. * * @param bytes Collection of bytes */ public BytesOf(final Collection bytes) { this(() -> { final ByteBuffer buf = ByteBuffer.allocate( bytes.size() ); bytes.forEach(buf::put); return buf.array(); }); } /** * Ctor. * * @param bytes Bytes to encapsulate */ private BytesOf(final Bytes bytes) { this.origin = bytes; } @Override public byte[] asBytes() throws Exception { return this.origin.asBytes(); } } cactoos-0.49/src/main/java/org/cactoos/bytes/CheckedBytes.java000066400000000000000000000040301400054650300242770ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.bytes; import org.cactoos.Bytes; import org.cactoos.Func; import org.cactoos.scalar.Checked; /** * Bytes that throws exception of specified type. * * @param Exception's type. * @since 0.31 */ public final class CheckedBytes implements Bytes { /** * Original bytes. */ private final Bytes origin; /** * Function that wraps exception of {@link #origin} to the required type. */ private final Func func; /** * Ctor. * @param orig Origin bytes. * @param fnc Function that wraps exceptions. */ public CheckedBytes(final Bytes orig, final Func fnc) { this.origin = orig; this.func = fnc; } @Override public byte[] asBytes() throws E { return new Checked<>( this.origin::asBytes, this.func ).value(); } } cactoos-0.49/src/main/java/org/cactoos/bytes/DigestEnvelope.java000066400000000000000000000057741400054650300246770ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.bytes; import java.io.IOException; import java.io.InputStream; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import org.cactoos.Bytes; import org.cactoos.Input; /** * Digest Envelope. * *

There is no thread-safety guarantee. * * @since 0.29 * @checkstyle AbstractClassNameCheck (500 lines) * @checkstyle DesignForExtensionCheck (500 lines) */ @SuppressWarnings("PMD.AbstractNaming") public abstract class DigestEnvelope implements Bytes { /** * The input. */ private final Input source; /** * The buffer size. */ private final int size; /** * The algorithm. */ private final String algorithm; /** * Ctor. * @param input The input * @param algrthm The algorithm */ public DigestEnvelope(final Input input, final String algrthm) { // @checkstyle MagicNumber (1 line) this(input, 16 << 10, algrthm); } /** * Ctor. * @param input The input * @param max Buffer size * @param algrthm The algorithm */ public DigestEnvelope( final Input input, final int max, final String algrthm ) { this.source = input; this.size = max; this.algorithm = algrthm; } @Override public byte[] asBytes() throws Exception { try (InputStream stream = this.source.stream()) { final MessageDigest msg = MessageDigest.getInstance(this.algorithm); final byte[] buf = new byte[this.size]; while (true) { final int len = stream.read(buf); if (len < 0) { break; } msg.update(buf, 0, len); } return msg.digest(); } catch (final NoSuchAlgorithmException ex) { throw new IOException(ex); } } } cactoos-0.49/src/main/java/org/cactoos/bytes/EmptyBytes.java000066400000000000000000000027711400054650300240610ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.bytes; import org.cactoos.Bytes; /** * Bytes with no data. * *

There is no thread-safety guarantee. * * @since 0.2 */ public final class EmptyBytes implements Bytes { /** * Empty array of bytes. */ private static final byte[] EMPTY = {}; @Override public byte[] asBytes() { return EmptyBytes.EMPTY; } } cactoos-0.49/src/main/java/org/cactoos/bytes/HexOf.java000066400000000000000000000057561400054650300227730ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.bytes; import java.io.IOException; import java.io.UncheckedIOException; import java.util.Iterator; import org.cactoos.Bytes; import org.cactoos.Text; import org.cactoos.iterator.Mapped; import org.cactoos.text.FormattedText; /** * Decodes origin {@link Text} using the hexadecimal encoding scheme. * * @since 0.30 * @checkstyle MagicNumberCheck (500 lines) */ public final class HexOf implements Bytes { /** * Origin hexadecimal text. */ private final Text origin; /** * Ctor. * * @param origin Hexadecimal text. */ public HexOf(final Text origin) { this.origin = origin; } @Override public byte[] asBytes() throws Exception { final String hex = this.origin.asString(); if ((hex.length() & 1) == 1) { throw new IOException("Length of hexadecimal text is odd"); } final Iterator iter = new Mapped<>( c -> { final int result = Character.digit(c, 16); if (result == -1) { throw new IOException( new FormattedText( "Unexpected character '%c'", c ).asString() ); } return result; }, hex.chars().mapToObj(c -> (char) c).iterator() ); final byte[] result = new byte[hex.length() / 2]; int index = 0; while (index < hex.length()) { try { final int most = iter.next(); final int less = iter.next(); result[index >>> 1] = (byte) ((most << 4) + less); index += 2; } catch (final UncheckedIOException ex) { throw ex.getCause(); } } return result; } } cactoos-0.49/src/main/java/org/cactoos/bytes/InputAsBytes.java000066400000000000000000000051451400054650300243440ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.bytes; import java.io.ByteArrayOutputStream; import java.io.InputStream; import org.cactoos.Bytes; import org.cactoos.Input; import org.cactoos.io.OutputTo; import org.cactoos.io.TeeInput; /** * Input as Byte Array. * *

This class is for internal use only. Use {@link BytesOf} instead.

* *

There is no thread-safety guarantee. * @since 0.1 */ public final class InputAsBytes implements Bytes { /** * The input. */ private final Input source; /** * The buffer size. */ private final int size; /** * Ctor. * @param input The input */ InputAsBytes(final Input input) { // @checkstyle MagicNumber (1 line) this(input, 16 << 10); } /** * Ctor. * @param input The input * @param max Max length of the buffer for reading */ InputAsBytes(final Input input, final int max) { this.source = input; this.size = max; } @Override public byte[] asBytes() throws Exception { try ( ByteArrayOutputStream baos = new ByteArrayOutputStream(); InputStream stream = new TeeInput( this.source, new OutputTo(baos) ).stream() ) { final byte[] buf = new byte[this.size]; while (true) { if (stream.read(buf) < 0) { break; } } return baos.toByteArray(); } } } cactoos-0.49/src/main/java/org/cactoos/bytes/Md5DigestOf.java000066400000000000000000000034141400054650300240210ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.bytes; import org.cactoos.Input; /** * MD5 checksum calculation of {@link Input}. * *

There is no thread-safety guarantee. * * @since 0.29 */ @SuppressWarnings("PMD.AvoidDuplicateLiterals") public final class Md5DigestOf extends DigestEnvelope { /** * Ctor. * @param input The input */ public Md5DigestOf(final Input input) { super(input, "MD5"); } /** * Ctor. * @param input The input * @param max Buffer size */ public Md5DigestOf(final Input input, final int max) { // @checkstyle MagicNumber (1 line) super(input, max, "MD5"); } } cactoos-0.49/src/main/java/org/cactoos/bytes/NoNulls.java000066400000000000000000000036541400054650300233470ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.bytes; import org.cactoos.Bytes; /** * Bytes check for no nulls. * * @since 0.11 */ public final class NoNulls implements Bytes { /** * The input. */ private final Bytes origin; /** * Ctor. * @param bytes The input */ public NoNulls(final Bytes bytes) { this.origin = bytes; } @Override public byte[] asBytes() throws Exception { if (this.origin == null) { throw new IllegalArgumentException( "NULL instead of a valid bytes" ); } final byte[] bytes = this.origin.asBytes(); if (bytes == null) { throw new IllegalStateException( "NULL instead of a valid byte array" ); } return bytes; } } cactoos-0.49/src/main/java/org/cactoos/bytes/ReaderAsBytes.java000066400000000000000000000070451400054650300244500ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.bytes; import java.io.Reader; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import org.cactoos.Bytes; /** * Reader as {@link Bytes}. * *

This class is for internal use only. Use {@link BytesOf} instead.

* *

There is no thread-safety guarantee. * * @since 0.12 */ final class ReaderAsBytes implements Bytes { /** * The reader. */ private final Reader reader; /** * The charset. */ private final CharSequence charset; /** * The buffer size. */ private final int size; /** * Ctor. * * @param rdr Reader */ ReaderAsBytes(final Reader rdr) { this(rdr, StandardCharsets.UTF_8); } /** * Ctor. * * @param rdr Reader * @param cset Charset */ ReaderAsBytes(final Reader rdr, final Charset cset) { // @checkstyle MagicNumber (1 line) this(rdr, cset, 16 << 10); } /** * Ctor. * * @param rdr Reader * @param cset Charset * @since 0.13.2 */ ReaderAsBytes(final Reader rdr, final CharSequence cset) { // @checkstyle MagicNumber (1 line) this(rdr, cset, 16 << 10); } /** * Ctor. * * @param rdr Reader * @param cset Charset * @param max Buffer size */ ReaderAsBytes(final Reader rdr, final Charset cset, final int max) { this(rdr, cset.name(), max); } /** * Ctor. * @param rdr Reader * @param max Buffer size * @since 0.13.3 */ ReaderAsBytes(final Reader rdr, final int max) { this(rdr, StandardCharsets.UTF_8, max); } /** * Ctor. * * @param rdr Reader * @param cset Charset * @param max Buffer size */ ReaderAsBytes(final Reader rdr, final CharSequence cset, final int max) { this.reader = rdr; this.charset = cset; this.size = max; } @Override public byte[] asBytes() throws Exception { final char[] buffer = new char[this.size]; final StringBuilder builder = new StringBuilder(this.size); while (true) { final int done = this.reader.read(buffer, 0, buffer.length); if (done < 0) { break; } builder.append(buffer, 0, done); } this.reader.close(); return builder.toString().getBytes(this.charset.toString()); } } cactoos-0.49/src/main/java/org/cactoos/bytes/Sha1DigestOf.java000066400000000000000000000034251400054650300241720ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.bytes; import org.cactoos.Input; /** * SHA-1 checksum calculation of {@link Input}. * *

There is no thread-safety guarantee. * * @since 0.29 */ @SuppressWarnings("PMD.AvoidDuplicateLiterals") public final class Sha1DigestOf extends DigestEnvelope { /** * Ctor. * @param input The input */ public Sha1DigestOf(final Input input) { super(input, "SHA-1"); } /** * Ctor. * @param input The input * @param max Buffer size */ public Sha1DigestOf(final Input input, final int max) { // @checkstyle MagicNumber (1 line) super(input, max, "SHA-1"); } } cactoos-0.49/src/main/java/org/cactoos/bytes/Sha256DigestOf.java000066400000000000000000000034411400054650300243440ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.bytes; import org.cactoos.Input; /** * SHA-256 checksum calculation of {@link Input}. * *

There is no thread-safety guarantee. * * @since 0.29 */ @SuppressWarnings("PMD.AvoidDuplicateLiterals") public final class Sha256DigestOf extends DigestEnvelope { /** * Ctor. * @param input The input */ public Sha256DigestOf(final Input input) { super(input, "SHA-256"); } /** * Ctor. * @param input The input * @param max Buffer size */ public Sha256DigestOf(final Input input, final int max) { // @checkstyle MagicNumber (1 line) super(input, max, "SHA-256"); } } cactoos-0.49/src/main/java/org/cactoos/bytes/UncheckedBytes.java000066400000000000000000000047741400054650300246610ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.bytes; import org.cactoos.Bytes; import org.cactoos.Func; import org.cactoos.func.UncheckedFunc; /** * Bytes that doesn't throw checked {@link Exception}. * *

There is no thread-safety guarantee. * * @since 0.3 */ public final class UncheckedBytes implements Bytes { /** * Original bytes. */ private final Bytes bytes; /** * Fallback. */ private final Func fallback; /** * Ctor. * @param bts Encapsulated bytes */ @SuppressWarnings("PMD.AvoidThrowingRawExceptionTypes") public UncheckedBytes(final Bytes bts) { this( bts, error -> { throw new RuntimeException(error); } ); } /** * Ctor. * @param bts Encapsulated bytes * @param fbk Fallback * @since 0.5 */ public UncheckedBytes(final Bytes bts, final Func fbk) { this.bytes = bts; this.fallback = fbk; } @Override @SuppressWarnings("PMD.AvoidCatchingGenericException") public byte[] asBytes() { byte[] data; try { data = this.bytes.asBytes(); // @checkstyle IllegalCatchCheck (1 line) } catch (final Exception ex) { data = new UncheckedFunc<>(this.fallback).apply(ex); } return data; } } cactoos-0.49/src/main/java/org/cactoos/bytes/package-info.java000066400000000000000000000023041400054650300242700ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ /** * Bytes. * * @since 0.20.2 */ package org.cactoos.bytes; cactoos-0.49/src/main/java/org/cactoos/collection/000077500000000000000000000000001400054650300221075ustar00rootroot00000000000000cactoos-0.49/src/main/java/org/cactoos/collection/CollectionEnvelope.java000066400000000000000000000057621400054650300265550ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.collection; import java.util.Collection; import org.cactoos.iterable.IterableEnvelope; /** * Base collection. * *

There is no thread-safety guarantee.

* @param Element type * @since 0.23 */ public abstract class CollectionEnvelope extends IterableEnvelope implements Collection { /** * The wrapped collection. */ private final Collection col; /** * Ctor. * @param col The wrapped collection */ public CollectionEnvelope(final Collection col) { super(col); this.col = col; } @Override public final int size() { return this.col.size(); } @Override public final boolean isEmpty() { return this.col.isEmpty(); } @Override public final boolean contains(final Object object) { return this.col.contains(object); } @Override public final Object[] toArray() { return this.col.toArray(); } @Override public final T[] toArray(final T[] array) { return this.col.toArray(array); } @Override public final boolean add(final X item) { return this.col.add(item); } @Override public final boolean remove(final Object object) { return this.col.remove(object); } @Override public final boolean containsAll(final Collection list) { return this.col.containsAll(list); } @Override public final boolean addAll(final Collection list) { return this.col.addAll(list); } @Override public final boolean removeAll(final Collection list) { return this.col.removeAll(list); } @Override public final boolean retainAll(final Collection list) { return this.col.retainAll(list); } @Override public final void clear() { this.col.clear(); } } cactoos-0.49/src/main/java/org/cactoos/collection/Immutable.java000066400000000000000000000100731400054650300246720ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.collection; import java.util.Collection; import java.util.Iterator; /** * Decorator that doesn't allow any mutation of the wrapped {@link Collection}. * *

There is no thread-safety guarantee.

* * @param Type of source item * @since 1.16 * @todo #898:30min Replace all the Collections.unmodifiableCollection * with the {@link org.cactoos.collection.Immutable} from the cactoos codebase. * That should be done because Elegant Object principles are against static methods. */ @SuppressWarnings( { "PMD.TooManyMethods", "PMD.AbstractNaming" } ) public final class Immutable implements Collection { /** * Original collection. */ private final Collection col; /** * Ctor. * @param src Source collection */ public Immutable(final Collection src) { this.col = src; } @Override public int size() { return this.col.size(); } @Override public boolean isEmpty() { return this.col.isEmpty(); } @Override public Iterator iterator() { return this.col.iterator(); } @Override public boolean contains(final Object object) { return this.col.contains(object); } @Override public Object[] toArray() { return this.col.toArray(); } @Override @SuppressWarnings("PMD.UseVarargs") public T[] toArray(final T[] array) { return this.col.toArray(array); } @Override public boolean add(final X item) { throw new UnsupportedOperationException( "#add(): the collection is read-only" ); } @Override public boolean remove(final Object object) { throw new UnsupportedOperationException( "#remove(): the collection is read-only" ); } @Override public boolean containsAll(final Collection list) { return this.col.containsAll(list); } @Override public boolean addAll(final Collection list) { throw new UnsupportedOperationException( "#addAll(): the collection is read-only" ); } @Override public boolean removeAll(final Collection list) { throw new UnsupportedOperationException( "#removeAll(): the collection is read-only" ); } @Override public boolean retainAll(final Collection list) { throw new UnsupportedOperationException( "#retainAll(): the collection is read-only" ); } @Override public void clear() { throw new UnsupportedOperationException( "#clear(): the collection is read-only" ); } @Override public String toString() { return this.col.toString(); } @Override public int hashCode() { return this.col.hashCode(); } @Override public boolean equals(final Object obj) { return this.col.equals(obj); } } cactoos-0.49/src/main/java/org/cactoos/collection/NoNulls.java000066400000000000000000000113511400054650300243450ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.collection; import java.util.Collection; import java.util.Iterator; import org.cactoos.text.FormattedText; import org.cactoos.text.UncheckedText; /** * A decorator of {@link Collection} that tolerates no NULLs. * *

There is no thread-safety guarantee.

* * @param Element type * @since 0.27 */ @SuppressWarnings("PMD.TooManyMethods") public final class NoNulls implements Collection { /** * Original collection. */ private final Collection col; /** * Ctor. * @param items Original one */ public NoNulls(final Collection items) { this.col = items; } @Override public int size() { return this.col.size(); } @Override public boolean isEmpty() { return this.col.isEmpty(); } @Override public Iterator iterator() { return new org.cactoos.iterator.NoNulls(this.col.iterator()); } @Override public boolean contains(final Object item) { if (item == null) { throw new IllegalArgumentException( "Argument of #contains(T) is NULL" ); } return this.col.contains(item); } @Override public Object[] toArray() { final Object[] array = this.col.toArray(); for (int idx = 0; idx < array.length; ++idx) { if (array[idx] == null) { throw new IllegalStateException( new UncheckedText( new FormattedText( "Item #%d of #toArray() is NULL", idx ) ).asString() ); } } return array; } @Override @SuppressWarnings("PMD.UseVarargs") public T[] toArray(final T[] array) { this.col.toArray((Object[]) array); for (int idx = 0; idx < array.length; ++idx) { if (array[idx] == null) { throw new IllegalStateException( new UncheckedText( new FormattedText( "Item #%d of #toArray(array) is NULL", idx ) ).asString() ); } } return array; } @Override public boolean add(final X item) { if (item == null) { throw new IllegalStateException( "Item of #add(T) is NULL" ); } return this.col.add(item); } @Override public boolean remove(final Object item) { if (item == null) { throw new IllegalStateException( "Item of #remove(T) is NULL" ); } return this.col.remove(item); } @Override public boolean containsAll(final Collection items) { return this.col.containsAll(new NoNulls<>(items)); } @Override public boolean addAll(final Collection items) { return this.col.addAll(new NoNulls<>(items)); } @Override public boolean removeAll(final Collection items) { return this.col.removeAll(new NoNulls<>(items)); } @Override public boolean retainAll(final Collection items) { return this.col.retainAll(new NoNulls<>(items)); } @Override public void clear() { this.col.clear(); } @Override public String toString() { return this.col.toString(); } @Override public boolean equals(final Object obj) { return this.col.equals(obj); } @Override public int hashCode() { return this.col.hashCode(); } } cactoos-0.49/src/main/java/org/cactoos/collection/package-info.java000066400000000000000000000023241400054650300252770ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ /** * Collections, tests. * * @since 0.14 */ package org.cactoos.collection; cactoos-0.49/src/main/java/org/cactoos/experimental/000077500000000000000000000000001400054650300224515ustar00rootroot00000000000000cactoos-0.49/src/main/java/org/cactoos/experimental/Threads.java000066400000000000000000000075321400054650300247150ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.experimental; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import org.cactoos.Func; import org.cactoos.Scalar; import org.cactoos.func.UncheckedFunc; import org.cactoos.iterable.IterableEnvelope; import org.cactoos.iterable.IterableOf; import org.cactoos.iterable.Mapped; import org.cactoos.list.ListOf; import org.cactoos.scalar.CallableOf; /** * Allows to execute the tasks concurrently. * * @param The type of task result item. * @since 1.0.0 */ public final class Threads extends IterableEnvelope { /** * Ctor. * @param exc The executor. * @param tasks The tasks to be executed concurrently. */ @SafeVarargs public Threads(final ExecutorService exc, final Scalar... tasks) { this(exc, new IterableOf<>(tasks)); } /** * Ctor. * @param exc The executor. * @param tasks The tasks to be executed concurrently. */ public Threads(final ExecutorService exc, final Iterable> tasks) { this(input -> exc.invokeAll(new ListOf<>(input)), tasks); } /** * Ctor. * @param threads The quantity of threads which will be used within the * {@link ExecutorService}. * @param tasks The tasks to be executed concurrently. * @see Executors#newFixedThreadPool(int) */ @SafeVarargs public Threads(final int threads, final Scalar... tasks) { this(threads, new IterableOf<>(tasks)); } /** * Ctor. * @param threads The quantity of threads which will be used within the * {@link ExecutorService}. * @param tasks The tasks to be executed concurrently. * @checkstyle IndentationCheck (20 lines) */ public Threads(final int threads, final Iterable> tasks) { this( todo -> { final ExecutorService executor = Executors.newFixedThreadPool( threads ); try { return executor.invokeAll(new ListOf<>(todo)); } finally { executor.shutdown(); } }, tasks ); } /** * Ctor. * @param fnc The function to map each task into {@link Future}. * @param tasks The tasks to be executed concurrently. */ private Threads( final Func>, Iterable>> fnc, final Iterable> tasks ) { super( () -> new Mapped<>( Future::get, new UncheckedFunc<>(fnc).apply(new Mapped<>(CallableOf::new, tasks)) ).iterator() ); } } cactoos-0.49/src/main/java/org/cactoos/experimental/Timed.java000066400000000000000000000116231400054650300243610ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.experimental; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import org.cactoos.Func; import org.cactoos.Scalar; import org.cactoos.func.UncheckedFunc; import org.cactoos.iterable.IterableEnvelope; import org.cactoos.iterable.IterableOf; import org.cactoos.iterable.Mapped; import org.cactoos.list.ListOf; import org.cactoos.scalar.CallableOf; /** * Allows to execute the tasks concurrently within given timeout. * * @param The type of task result item. * @since 1.0.0 */ public final class Timed extends IterableEnvelope { /** * Ctor. * @param exc The executor. * @param timeout The maximum time to wait. * @param unit The time unit of the timeout argument. * @param tasks The tasks to be executed concurrently. * @checkstyle ParameterNumberCheck (5 lines) */ @SafeVarargs public Timed( final ExecutorService exc, final long timeout, final TimeUnit unit, final Scalar... tasks ) { this(exc, new IterableOf<>(tasks), timeout, unit); } /** * Ctor. * @param exc The executor. * @param tasks The tasks to be executed concurrently. * @param timeout The maximum time to wait. * @param unit The time unit of the timeout argument. * @checkstyle ParameterNumberCheck (5 lines) */ public Timed( final ExecutorService exc, final Iterable> tasks, final long timeout, final TimeUnit unit ) { this( input -> exc.invokeAll(new ListOf<>(input), timeout, unit), tasks ); } /** * Ctor. * @param threads The quantity of threads which will be used within the * {@link ExecutorService}. * @param timeout The maximum time to wait. * @param unit The time unit of the timeout argument. * @param tasks The tasks to be executed concurrently. * @see Executors#newFixedThreadPool(int) * @checkstyle ParameterNumberCheck (5 lines) */ @SafeVarargs public Timed( final int threads, final long timeout, final TimeUnit unit, final Scalar... tasks ) { this(threads, new IterableOf<>(tasks), timeout, unit); } /** * Ctor. * @param threads The quantity of threads which will be used within the * {@link ExecutorService}. * @param tasks The tasks to be executed concurrently. * @param timeout The maximum time to wait. * @param unit The time unit of the timeout argument. * @checkstyle IndentationCheck (20 lines) * @checkstyle ParameterNumberCheck (5 lines) */ public Timed( final int threads, final Iterable> tasks, final long timeout, final TimeUnit unit ) { this( todo -> { final ExecutorService executor = Executors.newFixedThreadPool( threads ); try { return executor.invokeAll(new ListOf<>(todo), timeout, unit); } finally { executor.shutdown(); } }, tasks ); } /** * Ctor. * @param fnc The function to map each task into {@link Future}. * @param tasks The tasks to be executed concurrently. */ private Timed( final Func>, Iterable>> fnc, final Iterable> tasks ) { super( () -> new Mapped<>( Future::get, new UncheckedFunc<>(fnc).apply(new Mapped<>(CallableOf::new, tasks)) ).iterator() ); } } cactoos-0.49/src/main/java/org/cactoos/experimental/package-info.java000066400000000000000000000031131400054650300256360ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ /** * We are running experiments with the APIs provided in this package. We * encourage you to try them out and submit any questions and feedback * here. * * Be warned, however, that the stability of this package is * not guaranteed. * APIs may come, change, and go, between any release, for any reason * whatsoever. * * @since 1.0.0 */ package org.cactoos.experimental; cactoos-0.49/src/main/java/org/cactoos/func/000077500000000000000000000000001400054650300207075ustar00rootroot00000000000000cactoos-0.49/src/main/java/org/cactoos/func/Async.java000066400000000000000000000054461400054650300226400ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.func; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.ThreadFactory; import org.cactoos.Func; import org.cactoos.Proc; /** * Func that runs in the background. * *

If you want your piece of code to be executed in the background, * use {@link Async} as following:

* *
 int length = new AsyncFunc(
 *   input -> input.length()
 * ).apply("Hello, world!").get();
* *

There is no thread-safety guarantee. * * @param Type of input * @param Type of output * @since 0.10 */ public final class Async implements Func>, Proc { /** * The func. */ private final Func func; /** * The executor service. */ private final ExecutorService executor; /** * Ctor. * @param fnc The func */ public Async(final Func fnc) { this(fnc, Executors.defaultThreadFactory()); } /** * Ctor. * @param fnc The func * @param fct Factory */ public Async(final Func fnc, final ThreadFactory fct) { this(fnc, Executors.newSingleThreadExecutor(fct)); } /** * Ctor. * @param fnc The func * @param exec Executor Service */ public Async(final Func fnc, final ExecutorService exec) { this.func = fnc; this.executor = exec; } @Override public Future apply(final X input) { return this.executor.submit( () -> this.func.apply(input) ); } @Override public void exec(final X input) { this.apply(input); } } cactoos-0.49/src/main/java/org/cactoos/func/BiFuncNoNulls.java000066400000000000000000000046261400054650300242430ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.func; import org.cactoos.BiFunc; /** * BiFunc check for no nulls. * * @param Type of input * @param Type of input * @param Type of output * @since 0.11 */ public final class BiFuncNoNulls implements BiFunc { /** * The function. */ private final BiFunc origin; /** * Ctor. * @param func The function */ public BiFuncNoNulls(final BiFunc func) { this.origin = func; } @Override public Z apply(final X first, final Y second) throws Exception { if (this.origin == null) { throw new IllegalArgumentException( "NULL instead of a valid function" ); } if (first == null) { throw new IllegalArgumentException( "NULL instead of a valid first argument" ); } if (second == null) { throw new IllegalArgumentException( "NULL instead of a valid second argument" ); } final Z result = this.origin.apply(first, second); if (result == null) { throw new IllegalStateException( "NULL instead of a valid result" ); } return result; } } cactoos-0.49/src/main/java/org/cactoos/func/BiFuncOf.java000066400000000000000000000054601400054650300232120ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.func; import org.cactoos.BiFunc; import org.cactoos.BiProc; import org.cactoos.Func; import org.cactoos.Proc; import org.cactoos.Scalar; /** * Represents many possible inputs as {@link BiFunc}. * *

There is no thread-safety guarantee. * * @param Type of input * @param Type of input * @param Type of output * @since 0.20 */ public final class BiFuncOf implements BiFunc { /** * The func. */ private final BiFunc func; /** * Ctor. * @param scalar The scalar */ public BiFuncOf(final Scalar scalar) { this((first, second) -> scalar.value()); } /** * Ctor. * @param fnc The func */ public BiFuncOf(final Func fnc) { this((first, second) -> fnc.apply(first)); } /** * Ctor. * @param proc The proc * @param result Result to return */ public BiFuncOf(final Proc proc, final Z result) { this( (first, second) -> { proc.exec(first); return result; } ); } /** * Ctor. * @param proc The proc * @param result Result to return */ public BiFuncOf(final BiProc proc, final Z result) { this( (first, second) -> { proc.exec(first, second); return result; } ); } /** * Ctor. * @param fnc Func */ public BiFuncOf(final BiFunc fnc) { this.func = fnc; } @Override public Z apply(final X first, final Y second) throws Exception { return this.func.apply(first, second); } } cactoos-0.49/src/main/java/org/cactoos/func/Chained.java000066400000000000000000000046361400054650300231160ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.func; import java.util.Collections; import org.cactoos.Func; /** * Composed function. * * @param Type of input. * @param Intermediate type. * @param Type of output. * @since 0.7 */ public final class Chained implements Func { /** * Before function. */ private final Func before; /** * Functions. */ private final Iterable> funcs; /** * After function. */ private final Func after; /** * Ctor. * @param bfr Before function * @param list Functions * @param atr After function */ public Chained(final Func bfr, final Iterable> list, final Func atr) { this.before = bfr; this.funcs = list; this.after = atr; } /** * Ctor. * @param bfr Before function * @param atr After function */ public Chained(final Func bfr, final Func atr) { this(bfr, Collections.emptyList(), atr); } @Override public Z apply(final X input) throws Exception { Y temp = this.before.apply(input); for (final Func func : this.funcs) { temp = func.apply(temp); } return this.after.apply(temp); } } cactoos-0.49/src/main/java/org/cactoos/func/CheckedBiFunc.java000066400000000000000000000043311400054650300241700ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.func; import org.cactoos.BiFunc; import org.cactoos.Func; import org.cactoos.scalar.Checked; /** * BiFunc that throws exception of specified type. * * @param Type of input * @param Type of input * @param Type of output * @param Exception's type * @since 0.32 */ public final class CheckedBiFunc implements BiFunc { /** * Original BiFunc. */ private final BiFunc origin; /** * Function that wraps exception of {@link #origin} to the required type. */ private final Func func; /** * Ctor. * @param original Original BiFunc * @param fnc Function that wraps exceptions. */ public CheckedBiFunc(final BiFunc original, final Func fnc) { this.origin = original; this.func = fnc; } @Override public Z apply(final X first, final Y second) throws E { return new Checked<>( () -> this.origin.apply(first, second), this.func ).value(); } } cactoos-0.49/src/main/java/org/cactoos/func/CheckedFunc.java000066400000000000000000000041561400054650300237220ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.func; import org.cactoos.Func; import org.cactoos.scalar.Checked; /** * Func that throws exception of specified type. * * @param Type of input * @param Type of output * @param Exception's type * @since 0.32 */ public final class CheckedFunc implements Func { /** * Original func. */ private final Func origin; /** * Function that wraps exception of {@link #origin} to the required type. */ private final Func func; /** * Ctor. * @param original Original func * @param fnc Function that wraps exceptions. */ public CheckedFunc(final Func original, final Func fnc) { this.origin = original; this.func = fnc; } @Override public Y apply(final X input) throws E { return new Checked<>( () -> this.origin.apply(input), this.func ).value(); } } cactoos-0.49/src/main/java/org/cactoos/func/Flattened.java000066400000000000000000000031521400054650300234610ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.func; import org.cactoos.Func; import org.cactoos.Scalar; /** * {@link Func} from {@link Func} of {@link Scalar}. * *

There is no thread-safety guarantee. * * @param Type of input * @param Type of output * @since 0.48 */ public final class Flattened extends FuncEnvelope { /** * Ctor. * @param sclr The func */ public Flattened(final Func> sclr) { super(x -> sclr.apply(x).value()); } } cactoos-0.49/src/main/java/org/cactoos/func/FuncEnvelope.java000066400000000000000000000033511400054650300241450ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.func; import org.cactoos.Func; /** * Envelope for Func. * *

There is no thread-safety guarantee. * * @param Type of input * @param Type of output * @since 0.41 */ public abstract class FuncEnvelope implements Func { /** * The delegate function. */ private final Func func; /** * Ctor. * @param func The function */ public FuncEnvelope(final Func func) { this.func = func; } @Override public final Y apply(final X input) throws Exception { return this.func.apply(input); } } cactoos-0.49/src/main/java/org/cactoos/func/FuncNoNulls.java000066400000000000000000000042061400054650300237620ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.func; import java.io.IOException; import org.cactoos.Func; /** * Func check for no nulls. * * @param Type of input * @param Type of output * @since 0.10 */ public final class FuncNoNulls implements Func { /** * The function. */ private final Func func; /** * Ctor. * @param fnc The function */ public FuncNoNulls(final Func fnc) { this.func = fnc; } @Override public Y apply(final X input) throws Exception { if (this.func == null) { throw new IllegalArgumentException( "NULL instead of a valid function" ); } if (input == null) { throw new IllegalArgumentException( "NULL instead of a valid input" ); } final Y result = this.func.apply(input); if (result == null) { throw new IOException("NULL instead of a valid result"); } return result; } } cactoos-0.49/src/main/java/org/cactoos/func/FuncOf.java000066400000000000000000000043051400054650300227340ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.func; import org.cactoos.Func; import org.cactoos.Proc; import org.cactoos.Scalar; /** * Represents many possible inputs as {@link Func}. * *

There is no thread-safety guarantee. * * @param Type of input * @param Type of output * @since 0.12 */ public final class FuncOf implements Func { /** * The func. */ private final Func func; /** * Ctor. * @param proc The proc * @param result Result to return */ public FuncOf(final Proc proc, final Y result) { this( input -> { proc.exec(input); return result; } ); } /** * Ctor. * @param scalar Origin scalar */ public FuncOf(final Scalar scalar) { this(input -> scalar.value()); } /** * Ctor. * @param fnc Func */ public FuncOf(final Func fnc) { this.func = fnc; } @Override public Y apply(final X input) throws Exception { return this.func.apply(input); } } cactoos-0.49/src/main/java/org/cactoos/func/FuncWithFallback.java000066400000000000000000000105101400054650300247160ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.func; import java.sql.SQLException; import java.sql.SQLRecoverableException; import org.cactoos.Fallback; import org.cactoos.Func; import org.cactoos.iterable.IterableOf; import org.cactoos.scalar.InheritanceLevel; import org.cactoos.scalar.ScalarWithFallback; /** * Func with fallbacks that enable it to recover from errors. * *

You may register several fallbacks, each for any type of exception * whatsoever. If the decorated {@link Func} throws an exception that has * an IS-A relationship with a registered fallback's exception, then that * fallback's alternative {@link Func} will be used to provide a result. * *

Example scenario: you need to fetch product data * from a database which may potentially not be available (SQLException). * As a fallback, you then fetch the data from a local cache that is * guaranteed not to fail. This is a sketch of what this code may look like: * *

 * {@code
 *    final Product product = new FuncWithFallback<>(
 *        id -> new SqlProduct().apply(id),
 *        new Fallback.From<>(
 *            SQLException.class,
 *            id -> new CachedProduct().apply(id)
 *        )
 *    ).apply(id);
 * }
 * 
* *

If you register several fallback plans for exception types belonging to * the same hierarchy, then the fallback plan whose exception type has the * closest {@link InheritanceLevel} to the exception thrown will be used. * *

Example scenario: sometimes {@code SqlProduct} from * above will throw {@link SQLRecoverableException} (a sub class of * {@link SQLException}). In such cases you may want to simply retry the same * {@link Func}: * *

 * {@code
 *    final Product product = new FuncWithFallback<>(
 *        id -> new SqlProduct().apply(id),
 *        new IterableOf<>(
 *            new Fallback.From<>(
 *                SQLException.class,
 *                id -> new CachedProduct().apply(id)
 *            ),
 *            new Fallback.From<>(
 *                SQLRecoverableException.class,
 *                id -> new SqlProduct().apply(id)    // run it again
 *            )
 *        )
 *    ).apply(id);
 * }
 * 
* *

There is no thread-safety guarantee. * * @param Type of input * @param Type of output * @see ScalarWithFallback * @since 0.2 */ public final class FuncWithFallback implements Func { /** * The func. */ private final Func func; /** * The fallbacks. */ private final Iterable> fallbacks; /** * Ctor. * @param fnc The func * @param fbks The fallbacks */ @SafeVarargs public FuncWithFallback(final Func fnc, final Fallback... fbks) { this(fnc, new IterableOf<>(fbks)); } /** * Ctor. * @param fnc The func * @param fbks The fallbacks */ public FuncWithFallback( final Func fnc, final Iterable> fbks ) { this.func = fnc; this.fallbacks = fbks; } @Override public Y apply(final X input) throws Exception { return new ScalarWithFallback<>( () -> this.func.apply(input), this.fallbacks ).value(); } } cactoos-0.49/src/main/java/org/cactoos/func/IoCheckedBiFunc.java000066400000000000000000000037511400054650300244650ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.func; import java.io.IOException; import org.cactoos.BiFunc; import org.cactoos.scalar.IoChecked; /** * Func that doesn't throw checked {@link Exception}, but throws * {@link IOException} instead. * *

There is no thread-safety guarantee. * @param Type of input * @param Type of input * @param Type of output * @since 0.13 */ public final class IoCheckedBiFunc implements BiFunc { /** * Original func. */ private final BiFunc func; /** * Ctor. * @param fnc Encapsulated func */ public IoCheckedBiFunc(final BiFunc fnc) { this.func = fnc; } @Override public Z apply(final X first, final Y second) throws IOException { return new IoChecked<>( () -> this.func.apply(first, second) ).value(); } } cactoos-0.49/src/main/java/org/cactoos/func/IoCheckedFunc.java000066400000000000000000000036111400054650300242050ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.func; import java.io.IOException; import org.cactoos.Func; import org.cactoos.scalar.IoChecked; /** * Func that doesn't throw checked {@link Exception}, but throws * {@link IOException} instead. * *

There is no thread-safety guarantee. * * @param Type of input * @param Type of output * @since 0.4 */ public final class IoCheckedFunc implements Func { /** * Original func. */ private final Func func; /** * Ctor. * @param fnc Encapsulated func */ public IoCheckedFunc(final Func fnc) { this.func = fnc; } @Override public Y apply(final X input) throws IOException { return new IoChecked<>(() -> this.func.apply(input)).value(); } } cactoos-0.49/src/main/java/org/cactoos/func/Repeated.java000066400000000000000000000044201400054650300233030ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.func; import org.cactoos.Func; /** * Func that repeats its calculation a few times before * returning the last result. * * @param Type of input * @param Type of output * @since 0.6 */ public final class Repeated implements Func { /** * Original func. */ private final Func func; /** * How many times to run. */ private final int times; /** * Ctor. * *

If {@code max} is equal or less than zero {@link #apply(Object)} * will return an exception.

* * @param fnc Func original * @param max How many times */ public Repeated(final Func fnc, final int max) { this.func = fnc; this.times = max; } @Override public Y apply(final X input) throws Exception { if (this.times <= 0) { throw new IllegalArgumentException( "The number of repetitions must be at least 1" ); } Y result = null; for (int idx = 0; idx < this.times; ++idx) { result = this.func.apply(input); } return result; } } cactoos-0.49/src/main/java/org/cactoos/func/Retry.java000066400000000000000000000101041400054650300226530ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.func; import java.time.Duration; import org.cactoos.Func; /** * Func that will try a few times before throwing an exception. * *

There is no thread-safety guarantee. * * @param Type of input * @param Type of output * @since 0.8 */ public final class Retry implements Func { /** * Original func. */ private final Func func; /** * Exit condition. */ private final Func exit; /** * Wait between executions. */ private final Duration wait; /** * Ctor. * @param fnc Func original */ public Retry(final Func fnc) { // @checkstyle MagicNumberCheck (1 line) this(fnc, 3); } /** * Ctor. * @param fnc Func original * @param attempts Maximum number of attempts */ public Retry(final Func fnc, final int attempts) { this(fnc, attempts, Duration.ZERO); } /** * Ctor. * * @param fnc Func original * @param attempts Maximum number of attempts * @param wait The executions of the function */ public Retry(final Func fnc, final int attempts, final Duration wait) { this(fnc, attempt -> attempt >= attempts, wait); } /** * Ctor. * * @param fnc Func original * @param ext Exit condition, returns TRUE if there is no more reason to try */ public Retry(final Func fnc, final Func ext) { this(fnc, ext, Duration.ZERO); } /** * Ctor. * * @param fnc Func original * @param ext Exit condition, returns TRUE if there is no more reason to try * @param wait The executions of the function */ public Retry(final Func fnc, final Func ext, final Duration wait) { this.func = fnc; this.exit = ext; this.wait = wait; } @Override @SuppressWarnings("PMD.AvoidCatchingGenericException") public Y apply(final X input) throws Exception { int attempt = 0; Exception error = new IllegalArgumentException( "An immediate exit, didn't have a chance to try at least once" ); while (!this.exit.apply(attempt)) { try { return this.func.apply(input); } catch (final InterruptedException ex) { Thread.currentThread().interrupt(); error = ex; break; // @checkstyle IllegalCatchCheck (1 line) } catch (final Exception ex) { error = ex; } if (!this.wait.isZero() && !this.wait.isNegative()) { try { Thread.sleep(this.wait.toMillis()); } catch (final InterruptedException ex) { error = ex; break; } } ++attempt; } throw error; } } cactoos-0.49/src/main/java/org/cactoos/func/SolidBiFunc.java000066400000000000000000000041221400054650300237120ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.func; import org.cactoos.BiFunc; /** * BiFunc that is thread-safe and sticky. * *

Objects of this class are thread safe.

* * @param Type of first input * @param Type of second input * @param Type of output * @since 0.24 */ public final class SolidBiFunc implements BiFunc { /** * Original func. */ private final BiFunc func; /** * Ctor. * @param fnc Func original */ public SolidBiFunc(final BiFunc fnc) { this(fnc, Integer.MAX_VALUE); } /** * Ctor. * @param fnc Func original * @param max Max buffer length * @since 0.26 */ public SolidBiFunc(final BiFunc fnc, final int max) { this.func = new SyncBiFunc<>(new StickyBiFunc<>(fnc, max)); } @Override public Z apply(final X first, final Y second) throws Exception { return this.func.apply(first, second); } } cactoos-0.49/src/main/java/org/cactoos/func/SolidFunc.java000066400000000000000000000037741400054650300234530ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.func; import org.cactoos.Func; /** * Func that is thread-safe and sticky. * *

Objects of this class are thread safe.

* * @param Type of input * @param Type of output * @since 0.24 */ public final class SolidFunc implements Func { /** * Original func. */ private final Func func; /** * Ctor. * @param fnc Original function */ public SolidFunc(final Func fnc) { this(fnc, Integer.MAX_VALUE); } /** * Ctor. * @param fnc Original function * @param max Max caching buffer length * @since 0.26 */ public SolidFunc(final Func fnc, final int max) { this.func = new SyncFunc<>(new StickyFunc<>(fnc, max)); } @Override public Y apply(final X input) throws Exception { return this.func.apply(input); } } cactoos-0.49/src/main/java/org/cactoos/func/StickyBiFunc.java000066400000000000000000000057121400054650300241140ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.func; import java.util.LinkedHashMap; import java.util.Map; import org.cactoos.BiFunc; import org.cactoos.map.MapEntry; import org.cactoos.scalar.Sticky; /** * Func that accepts two arguments and caches previously calculated values * and doesn't recalculate again. * *

Pay attention that this class is not thread-safe. It is highly * recommended to always decorate it with {@link SyncBiFunc}.

* *

This {@link BiFunc} decorator technically is an in-memory * cache.

* *

There is no thread-safety guarantee. * @param Type of input * @param Type of input * @param Type of output * @see Sticky * @since 0.13 */ public final class StickyBiFunc implements BiFunc { /** * Original func. */ private final BiFunc func; /** * Cache. */ private final Map, Z> cache; /** * Maximum cache size. */ private final int size; /** * Ctor. * @param fnc Func original */ public StickyBiFunc(final BiFunc fnc) { this(fnc, Integer.MAX_VALUE); } /** * Ctor. * @param fnc Func original * @param max Maximum buffer size * @since 0.26 */ public StickyBiFunc(final BiFunc fnc, final int max) { this.func = fnc; this.cache = new LinkedHashMap<>(0); this.size = max; } @Override public Z apply(final X first, final Y second) throws Exception { final Map.Entry key = new MapEntry<>(first, second); while (this.cache.size() > this.size) { this.cache.remove(this.cache.keySet().iterator().next()); } if (!this.cache.containsKey(key)) { this.cache.put(key, this.func.apply(first, second)); } return this.cache.get(key); } } cactoos-0.49/src/main/java/org/cactoos/func/StickyFunc.java000066400000000000000000000045761400054650300236500ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.func; import org.cactoos.BiFunc; import org.cactoos.Func; import org.cactoos.scalar.Sticky; /** * Func that caches previously calculated values and doesn't * recalculate again. * *

This {@link Func} decorator technically is an in-memory * cache.

* *

Pay attention that this class is not thread-safe. It is highly * recommended to always decorate it with {@link SyncFunc}.

* *

There is no thread-safety guarantee. * * @param Type of input * @param Type of output * @see Sticky * @since 0.1 */ public final class StickyFunc implements Func { /** * Sticky bi-func. */ private final BiFunc func; /** * Ctor. * @param fnc Func original */ public StickyFunc(final Func fnc) { this(fnc, Integer.MAX_VALUE); } /** * Ctor. * @param fnc Func original * @param max Maximum cache size * @since 0.26 */ public StickyFunc(final Func fnc, final int max) { this.func = new StickyBiFunc<>( (first, second) -> fnc.apply(first), max ); } @Override public Y apply(final X input) throws Exception { return this.func.apply(input, true); } } cactoos-0.49/src/main/java/org/cactoos/func/SyncBiFunc.java000066400000000000000000000041771400054650300235660ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.func; import org.cactoos.BiFunc; /** * BiFunc that is thread-safe. * *

Objects of this class are thread safe.

* * @param Type of first input * @param Type of second input * @param Type of output * @since 0.18 */ public final class SyncBiFunc implements BiFunc { /** * Original func. */ private final BiFunc func; /** * Sync lock. */ private final Object lock; /** * Ctor. * @param fnc Func original */ public SyncBiFunc(final BiFunc fnc) { this(fnc, fnc); } /** * Ctor. * @param fnc Func original * @param lck Sync lock */ public SyncBiFunc(final BiFunc fnc, final Object lck) { this.func = fnc; this.lock = lck; } @Override public Z apply(final X first, final Y second) throws Exception { synchronized (this.lock) { return this.func.apply(first, second); } } } cactoos-0.49/src/main/java/org/cactoos/func/SyncFunc.java000066400000000000000000000040341400054650300233030ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.func; import org.cactoos.Func; /** * Func that is thread-safe. * *

Objects of this class are thread safe.

* * @param Type of input * @param Type of output * @since 0.4 */ public final class SyncFunc implements Func { /** * Original func. */ private final Func func; /** * Sync lock. */ private final Object lock; /** * Ctor. * @param fnc Func original */ public SyncFunc(final Func fnc) { this(fnc, fnc); } /** * Ctor. * @param fnc Func original * @param lck Sync lock */ public SyncFunc(final Func fnc, final Object lck) { this.func = fnc; this.lock = lck; } @Override public Y apply(final X input) throws Exception { synchronized (this.lock) { return this.func.apply(input); } } } cactoos-0.49/src/main/java/org/cactoos/func/Timed.java000066400000000000000000000050441400054650300226170ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.func; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import org.cactoos.Func; /** * Function that gets interrupted after a certain time has passed. * @param Type of input * @param Type of output * @since 0.29.3 */ public final class Timed implements Func { /** * Origin function. */ private final Func> func; /** * Milliseconds. */ private final long time; /** * Ctor. * @param function Origin function * @param milliseconds Milliseconds */ public Timed(final Func function, final long milliseconds) { this(milliseconds, new Async<>(function)); } /** * Ctor. * @param milliseconds Milliseconds * @param async Async function */ public Timed(final long milliseconds, final Func> async) { this.func = async; this.time = milliseconds; } @Override public Y apply(final X input) throws Exception { final Future future = this.func.apply(input); try { return future.get(this.time, TimeUnit.MILLISECONDS); } catch (final InterruptedException | ExecutionException | TimeoutException exp) { future.cancel(true); throw exp; } } } cactoos-0.49/src/main/java/org/cactoos/func/UncheckedBiFunc.java000066400000000000000000000036231400054650300245360ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.func; import org.cactoos.BiFunc; import org.cactoos.scalar.Unchecked; /** * BiFunc that doesn't throw checked {@link Exception}. * *

There is no thread-safety guarantee. * * @param Type of input * @param Type of input * @param Type of output * @since 0.13 */ public final class UncheckedBiFunc implements BiFunc { /** * Original func. */ private final BiFunc func; /** * Ctor. * @param fnc Encapsulated func */ public UncheckedBiFunc(final BiFunc fnc) { this.func = fnc; } @Override public Z apply(final X first, final Y second) { return new Unchecked<>( () -> this.func.apply(first, second) ).value(); } } cactoos-0.49/src/main/java/org/cactoos/func/UncheckedFunc.java000066400000000000000000000035051400054650300242620ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.func; import org.cactoos.Func; import org.cactoos.scalar.Unchecked; /** * Func that doesn't throw checked {@link Exception}. * *

There is no thread-safety guarantee. * * @param Type of input * @param Type of output * @since 0.2 */ public final class UncheckedFunc implements Func { /** * Original func. */ private final Func func; /** * Ctor. * @param fnc Encapsulated func */ public UncheckedFunc(final Func fnc) { this.func = fnc; } @Override public Y apply(final X input) { return new Unchecked<>( () -> this.func.apply(input) ).value(); } } cactoos-0.49/src/main/java/org/cactoos/func/package-info.java000066400000000000000000000023041400054650300240750ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ /** * Functions. * * @since 0.1 */ package org.cactoos.func; cactoos-0.49/src/main/java/org/cactoos/io/000077500000000000000000000000001400054650300203635ustar00rootroot00000000000000cactoos-0.49/src/main/java/org/cactoos/io/AppendTo.java000066400000000000000000000040531400054650300227420ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.io; import java.io.File; import java.io.OutputStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardOpenOption; import org.cactoos.Output; /** * Output that appends content to a given file. * *

There is no thread-safety guarantee. * * @since 1.0 */ public final class AppendTo implements Output { /** * Source of the output. */ private final File source; /** * Ctor. * @param path Path as a source of a File. */ public AppendTo(final Path path) { this(path.toFile()); } /** * Ctor. * @param src File to which content will be appended. */ public AppendTo(final File src) { this.source = src; } @Override public OutputStream stream() throws Exception { return Files.newOutputStream( this.source.toPath(), StandardOpenOption.APPEND ); } } cactoos-0.49/src/main/java/org/cactoos/io/CheckedInput.java000066400000000000000000000040641400054650300236000ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.io; import java.io.InputStream; import org.cactoos.Func; import org.cactoos.Input; import org.cactoos.scalar.Checked; /** * Input that throws exception of specified type. * * @param Exception's type. * @since 0.31 */ public final class CheckedInput implements Input { /** * Original input. */ private final Input origin; /** * Function that wraps exception of {@link #origin} to the required type. */ private final Func func; /** * Ctor. * @param orig Origin input. * @param fnc Function that wraps exceptions. */ public CheckedInput(final Input orig, final Func fnc) { this.origin = orig; this.func = fnc; } @Override public InputStream stream() throws E { return new Checked<>( this.origin::stream, this.func ).value(); } } cactoos-0.49/src/main/java/org/cactoos/io/CheckedOutput.java000066400000000000000000000040771400054650300240050ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.io; import java.io.OutputStream; import org.cactoos.Func; import org.cactoos.Output; import org.cactoos.scalar.Checked; /** * Output that throws exception of specified type. * * @param Exception's type. * @since 0.31 */ public final class CheckedOutput implements Output { /** * Original output. */ private final Output origin; /** * Function that wraps exception of {@link #origin} to the required type. */ private final Func func; /** * Ctor. * @param orig Origin output. * @param fnc Function that wraps exceptions. */ public CheckedOutput(final Output orig, final Func fnc) { this.origin = orig; this.func = fnc; } @Override public OutputStream stream() throws E { return new Checked<>( this.origin::stream, this.func ).value(); } } cactoos-0.49/src/main/java/org/cactoos/io/DeadInput.java000066400000000000000000000027001400054650300231020ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.io; import java.io.InputStream; import org.cactoos.Input; /** * Input with no data. * *

There is no thread-safety guarantee. * * @since 0.1 */ public final class DeadInput implements Input { @Override public InputStream stream() { return new DeadInputStream(); } } cactoos-0.49/src/main/java/org/cactoos/io/DeadInputStream.java000066400000000000000000000026301400054650300242600ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.io; import java.io.InputStream; /** * InputStream with no data. * *

There is no thread-safety guarantee. * * @since 0.16 */ public final class DeadInputStream extends InputStream { @Override public int read() { return -1; } } cactoos-0.49/src/main/java/org/cactoos/io/DeadOutput.java000066400000000000000000000027201400054650300233050ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.io; import java.io.OutputStream; import org.cactoos.Output; /** * Output that accepts anything. * *

There is no thread-safety guarantee. * * @since 0.1 */ public final class DeadOutput implements Output { @Override public OutputStream stream() { return new DeadOutputStream(); } } cactoos-0.49/src/main/java/org/cactoos/io/DeadOutputStream.java000066400000000000000000000026771400054650300244740ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.io; import java.io.OutputStream; /** * OutputStream that accepts anything. * *

There is no thread-safety guarantee. * * @since 0.1 */ public final class DeadOutputStream extends OutputStream { @Override public void write(final int data) { // nothing to do here } } cactoos-0.49/src/main/java/org/cactoos/io/Directory.java000066400000000000000000000042241400054650300231740ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.io; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.Iterator; import java.util.stream.Collectors; import java.util.stream.Stream; /** * Files and folders in a directory. * *

There is no thread-safety guarantee. * * @since 0.21 */ public final class Directory implements Iterable { /** * Path of the directory. */ private final Path dir; /** * Ctor. * @param file File as a path to directory. */ public Directory(final File file) { this(file.toPath()); } /** * Ctor. * @param path Path of the dir */ public Directory(final Path path) { this.dir = path; } @Override public Iterator iterator() { try (Stream files = Files.walk(this.dir)) { return files.collect(Collectors.toList()).iterator(); } catch (final IOException ex) { throw new IllegalStateException(ex); } } } cactoos-0.49/src/main/java/org/cactoos/io/GzipInput.java000066400000000000000000000041241400054650300231600ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.io; import java.io.InputStream; import java.util.zip.GZIPInputStream; import org.cactoos.Input; /** * Input that reads compressed data from the GZIP file format. * * @since 0.29 */ public final class GzipInput implements Input { /** * The input. */ private final Input origin; /** * The buffer size. */ private final int size; /** * Ctor. * @param input The input. */ public GzipInput(final Input input) { // @checkstyle MagicNumberCheck (1 line) this(input, 16 << 10); } /** * Ctor. * @param input The input * @param max Max length of the buffer */ public GzipInput(final Input input, final int max) { this.origin = input; this.size = max; } @Override public InputStream stream() throws Exception { return new GZIPInputStream( this.origin.stream(), this.size ); } } cactoos-0.49/src/main/java/org/cactoos/io/GzipOutput.java000066400000000000000000000041501400054650300233600ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.io; import java.io.OutputStream; import java.util.zip.GZIPOutputStream; import org.cactoos.Output; /** * Output that writes compressed data in the GZIP file format. * * @since 0.29 */ public final class GzipOutput implements Output { /** * The output. */ private final Output origin; /** * The buffer size. */ private final int size; /** * Ctor. * @param output The output */ public GzipOutput(final Output output) { // @checkstyle MagicNumberCheck (1 line) this(output, 16 << 10); } /** * Ctor. * @param output The output * @param max Max length of the buffer */ public GzipOutput(final Output output, final int max) { this.origin = output; this.size = max; } @Override public OutputStream stream() throws Exception { return new GZIPOutputStream( this.origin.stream(), this.size ); } } cactoos-0.49/src/main/java/org/cactoos/io/HeadInputStream.java000066400000000000000000000066541400054650300242760ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.io; import java.io.IOException; import java.io.InputStream; /** * Input stream that only shows the first N bytes of the original stream. * *

There is no thread-safety guarantee. * * @since 0.31 */ public final class HeadInputStream extends InputStream { /** * Original input stream. */ private final InputStream origin; /** * A number of bytes that can be read from the beginning. */ private final long length; /** * Current number or read bytes. */ private long processed; /** * Ctor. * @param orig The original input stream. * @param len A number of bytes that can be read from the beginning. */ public HeadInputStream(final InputStream orig, final int len) { super(); this.origin = orig; this.length = len; } @Override public int read() throws IOException { final int adjusted; if (this.processed >= this.length) { adjusted = -1; } else { this.processed = this.processed + 1; adjusted = this.origin.read(); } return adjusted; } @Override public long skip(final long skip) throws IOException { final long adjusted; if (this.processed + skip > this.length) { adjusted = this.length - this.processed; } else { adjusted = skip; } final long skipped = this.origin.skip(adjusted); this.processed = this.processed + skipped; return skipped; } @Override public void reset() throws IOException { this.processed = 0L; this.origin.reset(); } @Override public int available() throws IOException { final int available = this.origin.available(); final int adjusted; if (this.processed + available > this.length) { adjusted = (int) (this.length - this.processed); } else { adjusted = available; } return adjusted; } @Override public void close() throws IOException { this.origin.close(); } @Override public boolean markSupported() { return this.origin.markSupported(); } @Override public void mark(final int readlimit) { this.origin.mark(readlimit); } } cactoos-0.49/src/main/java/org/cactoos/io/HeadOf.java000066400000000000000000000036371400054650300223650ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.io; import java.io.InputStream; import org.cactoos.Input; /** * Input that only shows the first N bytes of the original input. * * @since 0.31 */ public final class HeadOf implements Input { /** * The original input. */ private final Input origin; /** * Limit of bytes that can be read from the beginning. */ private final int length; /** * Ctor. * @param orig The original input. * @param len Limit of bytes that can be read from the beginning. */ public HeadOf(final Input orig, final int len) { this.origin = orig; this.length = len; } @Override public InputStream stream() throws Exception { return new HeadInputStream(this.origin.stream(), this.length); } } cactoos-0.49/src/main/java/org/cactoos/io/InputNoNulls.java000066400000000000000000000036371400054650300236510ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.io; import java.io.IOException; import java.io.InputStream; import org.cactoos.Input; /** * Input check for no nulls. * * @since 0.10 */ public final class InputNoNulls implements Input { /** * The input. */ private final Input origin; /** * Ctor. * @param input The input */ public InputNoNulls(final Input input) { this.origin = input; } @Override public InputStream stream() throws Exception { if (this.origin == null) { throw new IOException("NULL instead of a valid input"); } final InputStream stream = this.origin.stream(); if (stream == null) { throw new IOException("NULL instead of a valid stream"); } return stream; } } cactoos-0.49/src/main/java/org/cactoos/io/InputOf.java000066400000000000000000000157541400054650300226260ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.io; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.io.Reader; import java.net.URI; import java.net.URL; import java.nio.charset.Charset; import java.nio.file.Path; import org.cactoos.Bytes; import org.cactoos.Input; import org.cactoos.Scalar; import org.cactoos.Text; import org.cactoos.bytes.BytesOf; import org.cactoos.scalar.IoChecked; import org.cactoos.scalar.Unchecked; /** * An {@link Input} that encapsulates other sources of data. * *

There is no thread-safety guarantee. * * @since 0.11.8 * @checkstyle ClassDataAbstractionCouplingCheck (500 lines) */ public final class InputOf implements Input { /** * Input. */ private final Input origin; /** * Ctor. * * @param file The file */ public InputOf(final File file) { this( () -> new FileInputStream( new Unchecked<>(() -> file).value() ) ); } /** * Ctor. * * @param path The path */ public InputOf(final Path path) { this(() -> new FileInputStream(path.toFile())); } /** * Ctor. * * @param uri The URI */ public InputOf(final URI uri) { this(uri::toURL); } /** * Ctor. * * @param url The URL */ public InputOf(final URL url) { this(() -> url); } /** * Ctor. * * @param scalar The url */ public InputOf(final Scalar scalar) { this(() -> new IoChecked<>(scalar).value().openStream()); } /** * Ctor. * * @param rdr Reader */ public InputOf(final Reader rdr) { this(new BytesOf(rdr)); } /** * Ctor. * @param rdr Reader * @param charset Charset */ public InputOf(final Reader rdr, final Charset charset) { this(new BytesOf(rdr, charset)); } /** * Ctor. * @param rdr Reader * @param charset Charset */ public InputOf(final Reader rdr, final CharSequence charset) { this(new BytesOf(rdr, charset)); } /** * Ctor. * @param rdr Reader * @param max Buffer size * @since 0.13.3 */ public InputOf(final Reader rdr, final int max) { this(new BytesOf(rdr, max)); } /** * Ctor. * @param rdr Reader * @param charset Charset * @param max Buffer size */ public InputOf(final Reader rdr, final Charset charset, final int max) { this(new BytesOf(rdr, charset, max)); } /** * Ctor. * @param rdr Reader * @param charset Charset * @param max Buffer size */ public InputOf(final Reader rdr, final CharSequence charset, final int max) { this(new BytesOf(rdr, charset, max)); } /** * Ctor. * * @param chars The chars */ public InputOf(final char... chars) { this(new BytesOf(chars)); } /** * Ctor. * * @param chars The chars * @param charset The charset */ public InputOf(final char[] chars, final Charset charset) { this(new BytesOf(chars, charset)); } /** * Ctor. * * @param chars The chars * @param charset The charset */ public InputOf(final char[] chars, final CharSequence charset) { this(new BytesOf(chars, charset)); } /** * Ctor. * @param source The string */ public InputOf(final CharSequence source) { this(new BytesOf(source)); } /** * Ctor. * @param source The string * @param charset The charset */ public InputOf(final CharSequence source, final Charset charset) { this(new BytesOf(source, charset)); } /** * Ctor. * @param source The string * @param charset The charset */ public InputOf(final CharSequence source, final CharSequence charset) { this(new BytesOf(source, charset)); } /** * Ctor. * @param text The text */ public InputOf(final Text text) { this(new BytesOf(text)); } /** * Ctor. * @param text The text * @param charset The charset */ public InputOf(final Text text, final Charset charset) { this(new BytesOf(text, charset)); } /** * Ctor. * @param text The text * @param charset The charset */ public InputOf(final Text text, final CharSequence charset) { this(new BytesOf(text, charset)); } /** * Ctor. * @param error The exception to serialize */ public InputOf(final Throwable error) { this(new BytesOf(error)); } /** * Ctor. * @param error The exception to serialize * @param charset Charset */ public InputOf(final Throwable error, final Charset charset) { this(new BytesOf(error, charset)); } /** * Ctor. * @param error The exception to serialize * @param charset Charset */ public InputOf(final Throwable error, final CharSequence charset) { this(new BytesOf(error, charset)); } /** * Ctor. * @param bytes The bytes */ public InputOf(final byte[] bytes) { this(new BytesOf(bytes)); } /** * Ctor. * @param src The bytes */ public InputOf(final Bytes src) { this( () -> new IoChecked( () -> new ByteArrayInputStream(src.asBytes()) ).value() ); } /** * Ctor. * @param stream The stream */ public InputOf(final InputStream stream) { this(() -> stream); } /** * Ctor. * * @param input The input */ private InputOf(final Input input) { this.origin = input; } @Override public InputStream stream() throws Exception { return this.origin.stream(); } } cactoos-0.49/src/main/java/org/cactoos/io/InputStreamOf.java000066400000000000000000000150721400054650300237730ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.io; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.Reader; import java.net.URI; import java.net.URL; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.nio.file.Path; import org.cactoos.Bytes; import org.cactoos.Input; import org.cactoos.Scalar; import org.cactoos.Text; import org.cactoos.scalar.Sticky; import org.cactoos.scalar.Unchecked; /** * An {@link InputStream} that encapsulates other sources of data. * *

There is no thread-safety guarantee. * * @since 0.13 */ public final class InputStreamOf extends InputStream { /** * The source. */ private final Unchecked source; /** * Ctor. * @param path The path */ public InputStreamOf(final Path path) { this(new InputOf(path)); } /** * Ctor. * @param file The file */ public InputStreamOf(final File file) { this(new InputOf(file)); } /** * Ctor. * @param url The URL */ public InputStreamOf(final URL url) { this(new InputOf(url)); } /** * Ctor. * @param uri The URI */ public InputStreamOf(final URI uri) { this(new InputOf(uri)); } /** * Ctor. * @param bytes The text */ public InputStreamOf(final Bytes bytes) { this(new InputOf(bytes)); } /** * Ctor. * @param bytes The text */ public InputStreamOf(final byte[] bytes) { this(new InputOf(bytes)); } /** * Ctor. * @param text The text */ public InputStreamOf(final Text text) { this(text, StandardCharsets.UTF_8); } /** * Ctor. * @param text The text * @param charset Charset */ public InputStreamOf(final Text text, final Charset charset) { this(new InputOf(text, charset)); } /** * Ctor. * @param text The text * @param charset Charset */ public InputStreamOf(final Text text, final CharSequence charset) { this(new InputOf(text, charset)); } /** * Ctor. * @param text The text */ public InputStreamOf(final CharSequence text) { this(new InputOf(text)); } /** * Ctor. * @param text The text * @param charset Charset */ public InputStreamOf(final CharSequence text, final Charset charset) { this(new InputOf(text, charset)); } /** * Ctor. * @param text The text * @param charset Charset */ public InputStreamOf(final CharSequence text, final CharSequence charset) { this(new InputOf(text, charset)); } /** * Ctor. * @param rdr The reader * @since 0.13.2 */ public InputStreamOf(final Reader rdr) { this(rdr, StandardCharsets.UTF_8); } /** * Ctor. * @param rdr Reader * @param charset Charset * @since 0.13.2 */ public InputStreamOf(final Reader rdr, final Charset charset) { this(new InputOf(rdr, charset)); } /** * Ctor. * @param rdr Reader * @param charset Charset * @since 0.13.2 */ public InputStreamOf(final Reader rdr, final CharSequence charset) { this(new InputOf(rdr, charset)); } /** * Ctor. * @param rdr Reader * @param cset Charset * @param max Buffer size * @since 0.13.2 */ public InputStreamOf(final Reader rdr, final Charset cset, final int max) { this(new InputOf(rdr, cset, max)); } /** * Ctor. * @param rdr Reader * @param max Buffer size * @since 0.13.2 */ public InputStreamOf(final Reader rdr, final int max) { this(new InputOf(rdr, StandardCharsets.UTF_8, max)); } /** * Ctor. * @param rdr Reader * @param charset Charset * @param max Buffer size * @since 0.13.2 */ public InputStreamOf(final Reader rdr, final CharSequence charset, final int max) { this(new InputOf(rdr, charset, max)); } /** * Ctor. * @param input The input */ public InputStreamOf(final Input input) { this((Scalar) input::stream); } /** * Ctor. * @param src Source */ private InputStreamOf(final Scalar src) { super(); this.source = new Unchecked<>(new Sticky<>(src)); } @Override public int read() throws IOException { return this.source.value().read(); } @Override public int read(final byte[] buffer) throws IOException { return this.source.value().read(buffer); } @Override public int read(final byte[] buffer, final int offset, final int length) throws IOException { return this.source.value().read(buffer, offset, length); } @Override public void close() throws IOException { this.source.value().close(); } @Override public long skip(final long num) throws IOException { return this.source.value().skip(num); } @Override public int available() throws IOException { return this.source.value().available(); } @Override public void mark(final int limit) { this.source.value().mark(limit); } @Override public void reset() throws IOException { this.source.value().reset(); } @Override public boolean markSupported() { return this.source.value().markSupported(); } } cactoos-0.49/src/main/java/org/cactoos/io/InputWithFallback.java000066400000000000000000000054561400054650300246130ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.io; import java.io.IOException; import java.io.InputStream; import org.cactoos.Func; import org.cactoos.Input; import org.cactoos.func.IoCheckedFunc; /** * Input that returns an alternative input if the main one throws * {@link IOException}. * *

There is no thread-safety guarantee. * * @since 0.9 */ public final class InputWithFallback implements Input { /** * The main one. */ private final Input main; /** * The alternative one. */ private final IoCheckedFunc alternative; /** * Ctor. * @param input Main input */ public InputWithFallback(final Input input) { this(input, new DeadInput()); } /** * Ctor. * @param input Main input * @param alt Alternative */ public InputWithFallback(final Input input, final Input alt) { this(input, error -> alt); } /** * Ctor. * @param input Main input * @param alt Alternative */ public InputWithFallback(final Input input, final Func alt) { this(input, new IoCheckedFunc<>(alt)); } /** * Ctor. * @param input Main input * @param alt Alternative */ public InputWithFallback(final Input input, final IoCheckedFunc alt) { this.main = input; this.alternative = alt; } @Override public InputStream stream() throws Exception { InputStream stream; try { stream = this.main.stream(); } catch (final IOException ex) { stream = this.alternative.apply(ex).stream(); } return stream; } } cactoos-0.49/src/main/java/org/cactoos/io/Joined.java000066400000000000000000000044441400054650300224440ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.io; import java.io.InputStream; import java.io.SequenceInputStream; import org.cactoos.Input; import org.cactoos.iterable.IterableOf; import org.cactoos.iterable.Mapped; import org.cactoos.scalar.Reduced; /** * Concatenation of several inputs. * @since 0.36 */ public final class Joined implements Input { /** * The inputs. */ private final Iterable inputs; /** * Ctor. * @param ipts Iterable of inputs */ public Joined(final Iterable ipts) { this.inputs = ipts; } /** * Ctor. * @param first First input * @param rest The other inputs */ public Joined(final Input first, final Input... rest) { this( new org.cactoos.iterable.Joined<>( first, new IterableOf<>(rest) ) ); } @Override public InputStream stream() throws Exception { return new Reduced( (left, right) -> new SequenceInputStream(left, right), new Mapped<>( input -> () -> input.stream(), this.inputs ) ).value(); } } cactoos-0.49/src/main/java/org/cactoos/io/LSInputOf.java000066400000000000000000000111641400054650300230540ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.io; import java.io.InputStream; import java.io.Reader; import java.nio.charset.StandardCharsets; import org.cactoos.Input; import org.cactoos.text.TextOf; import org.cactoos.text.UncheckedText; import org.w3c.dom.ls.LSInput; /** * Input as LSInput. * *

There is no thread-safety guarantee. * * @since 0.6 * @checkstyle AbbreviationAsWordInNameCheck (10 lines) */ public final class LSInputOf implements LSInput { /** * The input. */ private final Input input; /** * PublicID. */ private final String pid; /** * SystemID. */ private final String sid; /** * Base. */ private final String base; /** * Ctor. * @param inpt Input */ public LSInputOf(final Input inpt) { this(inpt, "#public", "#system", "#base"); } /** * Ctor. * @param inpt Input * @param pubid PublicID * @param sysid SystemID * @param bse Base * @checkstyle ParameterNumberCheck (3 lines) */ public LSInputOf(final Input inpt, final String pubid, final String sysid, final String bse) { this.input = inpt; this.pid = pubid; this.sid = sysid; this.base = bse; } @Override public Reader getCharacterStream() { return new ReaderOf(this.getByteStream()); } @Override public void setCharacterStream(final Reader stream) { throw new UnsupportedOperationException( "#setCharacterStream() is not supported" ); } @Override public InputStream getByteStream() { return new UncheckedInput(this.input).stream(); } @Override public void setByteStream(final InputStream stream) { throw new UnsupportedOperationException( "#setByteStream() is not supported" ); } @Override public String getStringData() { return new UncheckedText( new TextOf(this.input) ).asString(); } @Override public void setStringData(final String data) { throw new UnsupportedOperationException( "#setStringData() is not supported" ); } @Override public String getSystemId() { return this.sid; } @Override public void setSystemId(final String sysid) { throw new UnsupportedOperationException( "#setSystemId() is not supported" ); } @Override public String getPublicId() { return this.pid; } @Override public void setPublicId(final String pubid) { throw new UnsupportedOperationException( "#setPublicId() is not supported" ); } @Override public String getBaseURI() { return this.base; } @Override public void setBaseURI(final String uri) { throw new UnsupportedOperationException( "#setBaseURI() is not supported" ); } @Override public String getEncoding() { return StandardCharsets.UTF_8.displayName(); } @Override public void setEncoding(final String encoding) { throw new UnsupportedOperationException( "#setEncoding() is not supported" ); } @Override @SuppressWarnings("PMD.BooleanGetMethodName") public boolean getCertifiedText() { return true; } @Override public void setCertifiedText(final boolean text) { throw new UnsupportedOperationException( "#setCertifiedText() is not supported" ); } } cactoos-0.49/src/main/java/org/cactoos/io/LoggingInput.java000066400000000000000000000046171400054650300236440ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.io; import java.io.InputStream; import java.util.logging.Logger; import org.cactoos.Input; /** * Logged input. * *

There is no thread-safety guarantee. * * @since 0.29 */ @SuppressWarnings("PMD.LoggerIsNotStaticFinal") public final class LoggingInput implements Input { /** * The input stream. */ private final Input origin; /** * Where the data comes from. */ private final String source; /** * The Logger. */ private final Logger logger; /** * Ctor. * @param input Data input * @param src The name of source data */ public LoggingInput(final Input input, final String src) { this(input, src, Logger.getLogger(src)); } /** * Ctor. * @param input Data input * @param src The name of source data * @param lgr Message logger */ public LoggingInput( final Input input, final String src, final Logger lgr ) { this.origin = input; this.source = src; this.logger = lgr; } @Override public InputStream stream() throws Exception { return new LoggingInputStream( this.origin.stream(), this.source, this.logger ); } } cactoos-0.49/src/main/java/org/cactoos/io/LoggingInputStream.java000066400000000000000000000164301400054650300250140ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.io; import java.io.IOException; import java.io.InputStream; import java.time.Duration; import java.time.Instant; import java.util.concurrent.atomic.AtomicLong; import java.util.logging.Level; import java.util.logging.Logger; import org.cactoos.scalar.Sticky; import org.cactoos.scalar.Unchecked; import org.cactoos.text.FormattedText; import org.cactoos.text.UncheckedText; /** * Logged input stream. * *

There is no thread-safety guarantee. * * @since 0.29 */ @SuppressWarnings({"PMD.LoggerIsNotStaticFinal", "PMD.MoreThanOneLogger"}) public final class LoggingInputStream extends InputStream { /** * The input stream. */ private final InputStream origin; /** * Where the data comes from. */ private final String source; /** * The logger. */ private final Logger logger; /** * The bytes read. */ private final AtomicLong bytes; /** * The time took to read. */ private final AtomicLong time; /** * Logger level. */ private final Unchecked level; /** * Ctor. * @param input Source of data * @param src The name of source data */ public LoggingInputStream(final InputStream input, final String src) { this(input, src, Logger.getLogger(src)); } /** * Ctor. * @param input Source of data * @param src The name of source data * @param lgr The message logger */ public LoggingInputStream( final InputStream input, final String src, final Logger lgr ) { super(); this.origin = input; this.source = src; this.logger = lgr; this.level = new Unchecked<>( new Sticky<>( () -> { Level lvl = lgr.getLevel(); if (lvl == null) { Logger parent = lgr; while (lvl == null) { parent = parent.getParent(); lvl = parent.getLevel(); } } return lvl; } ) ); this.bytes = new AtomicLong(); this.time = new AtomicLong(); } @Override public int read() throws IOException { final byte[] buf = new byte[1]; final int size; if (this.read(buf) == -1) { size = -1; } else { size = Byte.toUnsignedInt(buf[0]); } return size; } @Override public int read(final byte[] buf) throws IOException { return this.read(buf, 0, buf.length); } @Override public int read(final byte[] buf, final int offset, final int len) throws IOException { final Instant start = Instant.now(); final int byts = this.origin.read(buf, offset, len); final Instant end = Instant.now(); final long millis = Duration.between(start, end).toMillis(); if (byts > 0) { this.bytes.getAndAdd(byts); this.time.getAndAdd(millis); } final UncheckedText msg = new UncheckedText( new FormattedText( "Read %d byte(s) from %s in %dms.", this.bytes.get(), this.source, this.time.get() ) ); if (byts > 0) { if (!this.level.value().equals(Level.INFO)) { this.logger.log(this.level.value(), msg.asString()); } } else { if (this.level.value().equals(Level.INFO)) { this.logger.info(msg.asString()); } } return byts; } @Override public long skip(final long num) throws IOException { final long skipped = this.origin.skip(num); this.logger.log( this.level.value(), new UncheckedText( new FormattedText( "Skipped %d byte(s) from %s.", skipped, this.source ) ).asString() ); return skipped; } @Override public int available() throws IOException { final int avail = this.origin.available(); this.logger.log( this.level.value(), new UncheckedText( new FormattedText( "There is(are) %d byte(s) available from %s.", avail, this.source ) ).asString() ); return avail; } @Override public void close() throws IOException { this.origin.close(); this.logger.log( this.level.value(), new UncheckedText( new FormattedText( "Closed input stream from %s.", this.source ) ).asString() ); } @Override public void mark(final int limit) { this.origin.mark(limit); this.logger.log( this.level.value(), new UncheckedText( new FormattedText( "Marked position %d from %s.", limit, this.source ) ).asString() ); } @Override public void reset() throws IOException { this.origin.reset(); this.logger.log( this.level.value(), new UncheckedText( new FormattedText( "Reset input stream from %s.", this.source ) ).asString() ); } @Override public boolean markSupported() { final boolean supported = this.origin.markSupported(); final String msg; if (supported) { msg = "Mark and reset are supported from %s"; } else { msg = "Mark and reset NOT supported from %s"; } this.logger.log( this.level.value(), new UncheckedText( new FormattedText( msg, this.source ) ).asString() ); return supported; } } cactoos-0.49/src/main/java/org/cactoos/io/LoggingOutput.java000066400000000000000000000046751400054650300240510ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.io; import java.io.OutputStream; import java.util.logging.Logger; import org.cactoos.Output; /** * Logged output. * *

There is no thread-safety guarantee. * * @since 0.29 */ @SuppressWarnings("PMD.LoggerIsNotStaticFinal") public final class LoggingOutput implements Output { /** * The output stream. */ private final Output origin; /** * Where the data comes goes. */ private final String destination; /** * The Logger. */ private final Logger logger; /** * Ctor. * @param output Data output * @param dst The name of destination data */ public LoggingOutput(final Output output, final String dst) { this(output, dst, Logger.getLogger(dst)); } /** * Ctor. * @param output Data output * @param dst The name of destination data * @param lgr Message logger */ public LoggingOutput( final Output output, final String dst, final Logger lgr ) { this.origin = output; this.destination = dst; this.logger = lgr; } @Override public OutputStream stream() throws Exception { return new LoggingOutputStream( this.origin.stream(), this.destination, this.logger ); } } cactoos-0.49/src/main/java/org/cactoos/io/LoggingOutputStream.java000066400000000000000000000130401400054650300252070ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.io; import java.io.IOException; import java.io.OutputStream; import java.time.Duration; import java.time.Instant; import java.util.concurrent.atomic.AtomicLong; import java.util.logging.Level; import java.util.logging.Logger; import org.cactoos.text.FormattedText; import org.cactoos.text.UncheckedText; /** * Logged output stream. * *

There is no thread-safety guarantee. * * @since 0.29 */ @SuppressWarnings( { "PMD.AvoidDuplicateLiterals", "PMD.LoggerIsNotStaticFinal" } ) public final class LoggingOutputStream extends OutputStream { /** * The output stream. */ private final OutputStream origin; /** * Where the data comes goes. */ private final String destination; /** * The logger. */ private final Logger logger; /** * The bytes read. */ private final AtomicLong bytes; /** * The time took to read. */ private final AtomicLong time; /** * Ctor. * @param output Destination of data * @param dst The name of source data */ public LoggingOutputStream(final OutputStream output, final String dst) { this(output, dst, Logger.getLogger(dst)); } /** * Ctor. * @param output Destination of data * @param dst The name of source data * @param lgr Message logger */ public LoggingOutputStream( final OutputStream output, final String dst, final Logger lgr ) { super(); this.origin = output; this.destination = dst; this.logger = lgr; this.bytes = new AtomicLong(); this.time = new AtomicLong(); } @Override public void write(final int data) throws IOException { final byte[] buf = {(byte) data}; this.write(buf, 0, 1); } @Override public void write(final byte[] buf) throws IOException { this.write(buf, 0, buf.length); } @Override public void write(final byte[] buf, final int offset, final int len) throws IOException { final Instant start = Instant.now(); this.origin.write(buf, offset, len); final Instant end = Instant.now(); final long millis = Duration.between(start, end).toMillis(); this.bytes.getAndAdd(len); this.time.getAndAdd(millis); final Level level = this.logger.getLevel(); if (!level.equals(Level.INFO)) { this.logger.log( level, new UncheckedText( new FormattedText( "Written %d byte(s) to %s in %dms.", this.bytes.get(), this.destination, this.time.get() ) ).asString() ); } } @Override public void close() throws IOException { this.origin.close(); final Level level = this.logger.getLevel(); if (level.equals(Level.INFO)) { this.logger.log( level, new UncheckedText( new FormattedText( "Written %d byte(s) to %s in %dms.", this.bytes.get(), this.destination, this.time.get() ) ).asString() ); } this.logger.log( level, new UncheckedText( new FormattedText( "Closed output stream from %s.", this.destination ) ).asString() ); } @Override public void flush() throws IOException { this.origin.flush(); final Level level = this.logger.getLevel(); if (level.equals(Level.INFO)) { this.logger.log( level, new UncheckedText( new FormattedText( "Written %d byte(s) to %s in %dms.", this.bytes.get(), this.destination, this.time.get() ) ).asString() ); } this.logger.log( level, new UncheckedText( new FormattedText( "Flushed output stream from %s.", this.destination ) ).asString() ); } } cactoos-0.49/src/main/java/org/cactoos/io/OutputNoNulls.java000066400000000000000000000036571400054650300240540ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.io; import java.io.IOException; import java.io.OutputStream; import org.cactoos.Output; /** * Output check for no nulls. * * @since 0.10 */ public final class OutputNoNulls implements Output { /** * The output. */ private final Output origin; /** * Ctor. * @param output The output */ public OutputNoNulls(final Output output) { this.origin = output; } @Override public OutputStream stream() throws Exception { if (this.origin == null) { throw new IOException("NULL instead of a valid output"); } final OutputStream stream = this.origin.stream(); if (stream == null) { throw new IOException("NULL instead of a valid stream"); } return stream; } } cactoos-0.49/src/main/java/org/cactoos/io/OutputStreamTo.java000066400000000000000000000110211400054650300242000ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.io; import java.io.File; import java.io.IOException; import java.io.OutputStream; import java.io.Writer; import java.nio.charset.Charset; import java.nio.charset.CharsetDecoder; import java.nio.charset.StandardCharsets; import java.nio.file.Path; import org.cactoos.Output; import org.cactoos.Scalar; import org.cactoos.scalar.Sticky; import org.cactoos.scalar.Unchecked; /** * An {@link OutputStream} that encapsulates other destination for the data. * *

There is no thread-safety guarantee. * * @since 0.13 */ public final class OutputStreamTo extends OutputStream { /** * The target. */ private final Unchecked target; /** * Ctor. * @param path The path */ public OutputStreamTo(final Path path) { this(new OutputTo(path)); } /** * Ctor. * @param file The file */ public OutputStreamTo(final File file) { this(new OutputTo(file)); } /** * Ctor. * @param wtr The writer */ public OutputStreamTo(final Writer wtr) { this(wtr, StandardCharsets.UTF_8); } /** * Ctor. * @param wtr Writer * @param charset Charset * @since 0.13.1 */ public OutputStreamTo(final Writer wtr, final Charset charset) { this(new OutputTo(wtr, charset)); } /** * Ctor. * @param wtr Writer * @param charset Charset * @since 0.13.1 */ public OutputStreamTo(final Writer wtr, final CharSequence charset) { this(new OutputTo(wtr, charset)); } /** * Ctor. * @param wtr Reader * @param charset Charset * @param size Buffer size * @since 0.13.1 */ public OutputStreamTo(final Writer wtr, final Charset charset, final int size) { this(new OutputTo(wtr, charset, size)); } /** * Ctor. * @param wtr Reader * @param charset Charset * @param size Buffer size * @since 0.13.1 */ public OutputStreamTo(final Writer wtr, final CharSequence charset, final int size) { this(new OutputTo(wtr, charset, size)); } /** * Ctor. * @param wtr Reader * @param ddr Charset decoder * @param size Buffer size * @since 0.13.1 */ public OutputStreamTo(final Writer wtr, final CharsetDecoder ddr, final int size) { this(new OutputTo(wtr, ddr, size)); } /** * Ctor. * @param output The input */ public OutputStreamTo(final Output output) { this((Scalar) output::stream); } /** * Ctor. * @param tgt Target */ private OutputStreamTo(final Scalar tgt) { super(); this.target = new Unchecked<>( new Sticky<>(tgt) ); } @Override public void write(final int data) throws IOException { this.target.value().write(data); } @Override public void write(final byte[] buffer) throws IOException { this.target.value().write(buffer); } @Override public void write(final byte[] buffer, final int offset, final int length) throws IOException { this.target.value().write(buffer, offset, length); } @Override public void close() throws IOException { this.target.value().close(); } @Override public void flush() throws IOException { this.target.value().flush(); } } cactoos-0.49/src/main/java/org/cactoos/io/OutputTo.java000066400000000000000000000112571400054650300230370ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.io; import java.io.File; import java.io.FileOutputStream; import java.io.OutputStream; import java.io.Writer; import java.nio.charset.Charset; import java.nio.charset.CharsetDecoder; import java.nio.file.Path; import org.cactoos.Output; /** * An {@link Output} that encapsulates other destination for the data. * *

There is no thread-safety guarantee. * * @since 0.12 */ public final class OutputTo implements Output { /** * The output. */ private final Output origin; /** * Ctor. * @param file The file */ public OutputTo(final File file) { this(file, true); } /** * Ctor. * @param file The file * @param mkdirs Should we do mkdirs beforehand? * @since 0.15 */ public OutputTo(final File file, final boolean mkdirs) { this( () -> { if (mkdirs) { file.getAbsoluteFile().getParentFile().mkdirs(); } return new FileOutputStream(file); } ); } /** * Ctor. * @param path The path */ public OutputTo(final Path path) { this(path, true); } /** * Ctor. * @param path The path * @param mkdirs Should we do mkdirs beforehand? * @since 0.15 */ public OutputTo(final Path path, final boolean mkdirs) { this( () -> { final File file = path.toFile(); if (mkdirs) { file.getParentFile().mkdirs(); } return new FileOutputStream(file); } ); } /** * Ctor. * @param writer The writer */ public OutputTo(final Writer writer) { this(new WriterAsOutputStream(writer)); } /** * Ctor. * @param wtr Writer * @param charset Charset */ OutputTo(final Writer wtr, final Charset charset) { this(new WriterAsOutputStream(wtr, charset)); } /** * Ctor. * @param wtr Writer * @param charset Charset */ OutputTo(final Writer wtr, final CharSequence charset) { this(new WriterAsOutputStream(wtr, charset)); } /** * Ctor. * @param wtr Reader * @param charset Charset * @param size Buffer size */ OutputTo(final Writer wtr, final Charset charset, final int size) { this(new WriterAsOutputStream(wtr, charset, size)); } /** * Ctor. * @param wtr Reader * @param size Buffer size * @since 0.13.3 */ OutputTo(final Writer wtr, final int size) { this(new WriterAsOutputStream(wtr, size)); } /** * Ctor. * @param wtr Reader * @param charset Charset * @param size Buffer size */ OutputTo(final Writer wtr, final CharSequence charset, final int size) { this(new WriterAsOutputStream(wtr, charset, size)); } /** * Ctor. * @param wtr Reader * @param ddr Charset decoder * @param size Buffer size */ OutputTo(final Writer wtr, final CharsetDecoder ddr, final int size) { this(new WriterAsOutputStream(wtr, ddr, size)); } /** * Ctor. * @param stream The stream */ public OutputTo(final OutputStream stream) { this(() -> stream); } /** * Ctor. * @param output The output */ private OutputTo(final Output output) { this.origin = output; } @Override public OutputStream stream() throws Exception { return this.origin.stream(); } } cactoos-0.49/src/main/java/org/cactoos/io/ReaderOf.java000066400000000000000000000162531400054650300227240ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.io; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.io.UnsupportedEncodingException; import java.net.URI; import java.net.URL; import java.nio.charset.Charset; import java.nio.charset.CharsetDecoder; import java.nio.charset.StandardCharsets; import java.nio.file.Path; import org.cactoos.Bytes; import org.cactoos.Input; import org.cactoos.Scalar; import org.cactoos.Text; import org.cactoos.scalar.Sticky; import org.cactoos.scalar.Unchecked; /** * A {@link Reader} that encapsulates other sources of data. * *

There is no thread-safety guarantee. * * @since 0.13 */ public final class ReaderOf extends Reader { /** * The source. */ private final Unchecked source; /** * Ctor. * @param chars Chars */ public ReaderOf(final char... chars) { this(new InputOf(chars)); } /** * Ctor. * @param chars Chars * @param charset Charset */ public ReaderOf(final char[] chars, final Charset charset) { this(new InputOf(chars, charset)); } /** * Ctor. * @param chars Chars * @param charset Charset */ public ReaderOf(final char[] chars, final CharSequence charset) { this(new InputOf(chars, charset)); } /** * Ctor. * @param bytes Bytes */ public ReaderOf(final byte[] bytes) { this(new InputOf(bytes)); } /** * Ctor. * @param bytes Bytes * @param charset Charset */ public ReaderOf(final byte[] bytes, final Charset charset) { this(new InputOf(bytes), charset); } /** * Ctor. * @param bytes Bytes * @param charset Charset */ public ReaderOf(final byte[] bytes, final CharSequence charset) { this(new InputOf(bytes), charset); } /** * Ctor. * @param path The path */ public ReaderOf(final Path path) { this(new InputOf(path)); } /** * Ctor. * @param file The file */ public ReaderOf(final File file) { this(new InputOf(file)); } /** * Ctor. * @param url The URL */ public ReaderOf(final URL url) { this(new InputOf(url)); } /** * Ctor. * @param uri The URI */ public ReaderOf(final URI uri) { this(new InputOf(uri)); } /** * Ctor. * @param bytes The text */ public ReaderOf(final Bytes bytes) { this(new InputOf(bytes)); } /** * Ctor. * @param text The text */ public ReaderOf(final Text text) { this(new InputOf(text)); } /** * Ctor. * @param text The text * @param charset Charset */ public ReaderOf(final Text text, final Charset charset) { this(new InputOf(text, charset)); } /** * Ctor. * @param text The text * @param charset Charset */ public ReaderOf(final Text text, final CharSequence charset) { this(new InputOf(text, charset)); } /** * Ctor. * @param text The text */ public ReaderOf(final CharSequence text) { this(new InputOf(text)); } /** * Ctor. * @param text The text * @param charset Charset */ public ReaderOf(final CharSequence text, final Charset charset) { this(new InputOf(text, charset)); } /** * Ctor. * @param text The text * @param charset Charset */ public ReaderOf(final CharSequence text, final CharSequence charset) { this(new InputOf(text, charset)); } /** * Ctor. * @param input The input */ public ReaderOf(final Input input) { this(input, StandardCharsets.UTF_8); } /** * Ctor. * @param input The input * @param charset The charset */ public ReaderOf(final Input input, final Charset charset) { this(() -> new InputStreamReader(input.stream(), charset)); } /** * Ctor. * @param input The input * @param charset The charset */ public ReaderOf(final Input input, final CharSequence charset) { this(() -> new InputStreamReader(input.stream(), charset.toString())); } /** * Ctor. * @param input The input * @param decoder The decoder * @since 0.13.1 */ public ReaderOf(final Input input, final CharsetDecoder decoder) { this(() -> new InputStreamReader(input.stream(), decoder)); } /** * Ctor. * @param stream The stream */ public ReaderOf(final InputStream stream) { this(stream, StandardCharsets.UTF_8); } /** * Ctor. * @param stream The stream * @param charset The charset */ public ReaderOf(final InputStream stream, final Charset charset) { this(new InputStreamReader(stream, charset)); } /** * Ctor. * @param stream The stream * @param charset The charset * @throws UnsupportedEncodingException If fails */ public ReaderOf(final InputStream stream, final CharSequence charset) throws UnsupportedEncodingException { this(new InputStreamReader(stream, charset.toString())); } /** * Ctor. * @param stream The stream * @param decoder The charset decoder * @since 0.13.1 */ public ReaderOf(final InputStream stream, final CharsetDecoder decoder) { this(new InputStreamReader(stream, decoder)); } /** * Ctor. * @param rdr The reader */ private ReaderOf(final Reader rdr) { this(() -> rdr); } /** * Ctor. * @param src Source */ private ReaderOf(final Scalar src) { super(); this.source = new Unchecked<>( new Sticky<>(src) ); } @Override public int read(final char[] cbuf, final int off, final int len) throws IOException { return this.source.value().read(cbuf, off, len); } @Override public void close() throws IOException { this.source.value().close(); } } cactoos-0.49/src/main/java/org/cactoos/io/ResourceOf.java000066400000000000000000000153131400054650300233050ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.io; import java.io.IOException; import java.io.InputStream; import org.cactoos.Func; import org.cactoos.Input; import org.cactoos.Text; import org.cactoos.bytes.BytesOf; import org.cactoos.func.IoCheckedFunc; import org.cactoos.text.FormattedText; import org.cactoos.text.TextOf; /** * Classpath resource. * *

Pay attention that the name of resource must always be * global, not starting with a leading slash. Thus, * if you want to load a text file from {@code /com/example/Test.txt}, * you must provide this name: {@code "com/example/Test.txt"}.

* * @see ClassLoader#getResource(String) * @since 0.1 */ public final class ResourceOf implements Input { /** * Resource name. */ private final Text path; /** * Fallback. */ private final Func fallback; /** * Resource class loader. */ private final ClassLoader loader; /** * New resource input with current context {@link ClassLoader}. * @param res Resource name */ public ResourceOf(final CharSequence res) { this(res, Thread.currentThread().getContextClassLoader()); } /** * New resource input with {@link ClassLoader} from the specified {@link Class}. * @param res Resource name * @param cls Resource class loader * @since 0.49 */ public ResourceOf(final CharSequence res, final Class cls) { this(res, cls.getClassLoader()); } /** * New resource input with specified {@link ClassLoader}. * @param res Resource name * @param ldr Resource class loader */ public ResourceOf(final CharSequence res, final ClassLoader ldr) { this(new TextOf(res), ldr); } /** * New resource input with {@link ClassLoader} from the specified {@link Class}. * @param res Resource name * @param fbk Fallback * @param cls Resource class loader * @since 0.49 */ public ResourceOf(final CharSequence res, final Func fbk, final Class cls) { this(res, fbk, cls.getClassLoader()); } /** * New resource input with specified {@link ClassLoader}. * @param res Resource name * @param fbk Fallback * @param ldr Resource class loader */ public ResourceOf(final CharSequence res, final Func fbk, final ClassLoader ldr) { this(new TextOf(res), input -> fbk.apply(input.asString()), ldr); } /** * New resource input with current context {@link ClassLoader}. * @param res Resource name * @param fbk Fallback */ public ResourceOf(final CharSequence res, final CharSequence fbk) { this(res, input -> new InputOf(new BytesOf(fbk))); } /** * New resource input with current context {@link ClassLoader}. * @param res Resource name * @param fbk Fallback */ public ResourceOf(final CharSequence res, final Func fbk) { this(res, fbk, Thread.currentThread().getContextClassLoader()); } /** * New resource input with current context {@link ClassLoader}. * @param res Resource name * @param fbk Fallback */ public ResourceOf(final CharSequence res, final Input fbk) { this(res, input -> fbk); } /** * New resource input with current context {@link ClassLoader}. * @param res Resource name */ public ResourceOf(final Text res) { this(res, Thread.currentThread().getContextClassLoader()); } /** * New resource input with specified {@link ClassLoader}. * @param res Resource name * @param ldr Resource class loader */ public ResourceOf(final Text res, final ClassLoader ldr) { this( res, input -> { throw new IOException( new FormattedText( "The resource \"%s\" was not found in %s", input.asString(), ldr ).asString() ); }, ldr ); } /** * New resource input with current context {@link ClassLoader}. * @param res Resource name * @param fbk Fallback */ public ResourceOf(final Text res, final Text fbk) { this(res, input -> new InputOf(new BytesOf(fbk.asString()))); } /** * New resource input with current context {@link ClassLoader}. * @param res Resource name * @param fbk Fallback */ public ResourceOf(final Text res, final Input fbk) { this(res, input -> fbk); } /** * New resource input with current context {@link ClassLoader}. * @param res Resource name * @param fbk Fallback */ public ResourceOf(final Text res, final Func fbk) { this(res, fbk, Thread.currentThread().getContextClassLoader()); } /** * New resource input with specified {@link ClassLoader}. * @param res Resource name * @param fbk Fallback * @param ldr Resource class loader */ public ResourceOf(final Text res, final Func fbk, final ClassLoader ldr) { this.path = res; this.loader = ldr; this.fallback = fbk; } @Override public InputStream stream() throws Exception { InputStream input = this.loader.getResourceAsStream( this.path.asString() ); if (input == null) { input = new IoCheckedFunc<>(this.fallback) .apply(this.path) .stream(); } return input; } } cactoos-0.49/src/main/java/org/cactoos/io/Stderr.java000066400000000000000000000027101400054650300224710ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.io; import java.io.OutputStream; import org.cactoos.Output; /** * Output that writes to {@code stderr}. * *

There is no thread-safety guarantee. * * @since 0.6 */ public final class Stderr implements Output { @Override public OutputStream stream() { return System.err; } } cactoos-0.49/src/main/java/org/cactoos/io/Stdin.java000066400000000000000000000027011400054650300223070ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.io; import java.io.InputStream; import org.cactoos.Input; /** * Input that reads from {@code stdin}. * *

There is no thread-safety guarantee. * * @since 0.6 */ public final class Stdin implements Input { @Override public InputStream stream() { return System.in; } } cactoos-0.49/src/main/java/org/cactoos/io/Stdout.java000066400000000000000000000027101400054650300225100ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.io; import java.io.OutputStream; import org.cactoos.Output; /** * Output that writes to {@code stdout}. * *

There is no thread-safety guarantee. * * @since 0.6 */ public final class Stdout implements Output { @Override public OutputStream stream() { return System.out; } } cactoos-0.49/src/main/java/org/cactoos/io/Sticky.java000066400000000000000000000045231400054650300225000ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.io; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.InputStream; import org.cactoos.Input; import org.cactoos.Scalar; import org.cactoos.scalar.IoChecked; import org.cactoos.scalar.LengthOf; /** * Input that reads only once. * *

Pay attention that this class is not thread-safe. It is highly * recommended to always decorate it with {@link SyncInput}.

* *

There is no thread-safety guarantee. * * @since 0.6 */ public final class Sticky implements Input { /** * The cache. */ private final Scalar cache; /** * Ctor. * @param input The input */ public Sticky(final Input input) { this.cache = new org.cactoos.scalar.Sticky<>( () -> { final ByteArrayOutputStream baos = new ByteArrayOutputStream(); new LengthOf( new TeeInput(input, new OutputTo(baos)) ).value(); return baos.toByteArray(); } ); } @Override public InputStream stream() throws Exception { return new ByteArrayInputStream( new IoChecked<>(this.cache).value() ); } } cactoos-0.49/src/main/java/org/cactoos/io/SyncInput.java000066400000000000000000000037611400054650300231710ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.io; import java.io.InputStream; import org.cactoos.Input; /** * Thread-safe {@link Input}. * *

Objects of this class are thread safe.

* * @since 0.18 */ public final class SyncInput implements Input { /** * The input. */ private final Input origin; /** * Sync lock. */ private final Object lock; /** * Ctor. * @param input The input */ public SyncInput(final Input input) { this(input, input); } /** * Ctor. * @param input The input * @param lck The lock object */ public SyncInput(final Input input, final Object lck) { this.origin = input; this.lock = lck; } @Override public InputStream stream() throws Exception { synchronized (this.lock) { return this.origin.stream(); } } } cactoos-0.49/src/main/java/org/cactoos/io/SyncOutput.java000066400000000000000000000040061400054650300233630ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.io; import java.io.OutputStream; import org.cactoos.Output; /** * Thread-safe {@link Output}. * *

Objects of this class are thread safe.

* * @since 0.18 */ public final class SyncOutput implements Output { /** * The output. */ private final Output origin; /** * Sync lock. */ private final Object lock; /** * Ctor. * @param output The output */ public SyncOutput(final Output output) { this(output, output); } /** * Ctor. * @param output The output * @param lck The lock object */ public SyncOutput(final Output output, final Object lck) { this.origin = output; this.lock = lck; } @Override public OutputStream stream() throws Exception { synchronized (this.lock) { return this.origin.stream(); } } } cactoos-0.49/src/main/java/org/cactoos/io/TailOf.java000066400000000000000000000111571400054650300224110ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.io; import java.io.ByteArrayInputStream; import java.io.InputStream; import org.cactoos.Input; import org.cactoos.scalar.MinOf; import org.cactoos.text.FormattedText; /** * Input showing only last N bytes of the stream. * *

There is no thread-safety guarantee. * * @since 0.30 */ public final class TailOf implements Input { /** * Input to decorate. */ private final Input input; /** * Number of last bytes to show from the input. */ private final int count; /** * Maximum number of bytes to read at once. */ private final int max; /** * Constructor. * @param inpt Input to decorate * @param bytes Number of last bytes to show from input */ public TailOf(final Input inpt, final int bytes) { // @checkstyle MagicNumber (1 line) this(inpt, bytes, 16384); } /** * Constructor. * @param inpt Input to decorate * @param bytes Number of last bytes to show from input * @param maximum Maximum number of bytes to read at once */ public TailOf(final Input inpt, final int bytes, final int maximum) { this.input = inpt; this.count = bytes; this.max = maximum; } @Override public InputStream stream() throws Exception { if (this.max < this.count) { throw new IllegalArgumentException( new FormattedText( "Can't tail %d bytes if buffer is set to %d", this.count, this.max ).asString() ); } final byte[] buffer = new byte[this.max]; final byte[] response = new byte[this.count]; int num = 0; final InputStream strm = this.input.stream(); for (int read = strm.read(buffer); read > 0; read = strm.read(buffer)) { if (read < this.max && read < this.count) { num = this.copyPartial(buffer, response, num, read); } else { num = this.copy(buffer, response, read); } } return new ByteArrayInputStream(response, 0, num); } /** * Copy full buffer to response. * @param buffer The buffer array * @param response The response array * @param read Number of bytes read in buffer * @return Number of bytes in the response buffer */ private int copy(final byte[] buffer, final byte[] response, final int read) { System.arraycopy( buffer, read - this.count, response, 0, this.count ); return new MinOf(this.count, read).intValue(); } /** * Copy buffer to response for read count smaller then buffer size. * @param buffer The buffer array * @param response The response array * @param num Number of bytes in response array from previous read * @param read Number of bytes read in the buffer * @return New count of bytes in the response array * @checkstyle ParameterNumberCheck (3 lines) */ private int copyPartial(final byte[] buffer, final byte[] response, final int num, final int read) { final int result; if (num > 0) { System.arraycopy( response, read, response, 0, this.count - read ); System.arraycopy(buffer, 0, response, this.count - read, read); result = this.count; } else { System.arraycopy(buffer, 0, response, 0, read); result = read; } return result; } } cactoos-0.49/src/main/java/org/cactoos/io/TeeInput.java000066400000000000000000000532711400054650300227730ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.io; import java.io.File; import java.io.InputStream; import java.io.Reader; import java.io.Writer; import java.net.URI; import java.net.URL; import java.nio.charset.Charset; import java.nio.file.Path; import org.cactoos.Bytes; import org.cactoos.Input; import org.cactoos.Output; import org.cactoos.Text; /** * Input to Output copying pipe. * *

There is no thread-safety guarantee. * * @since 0.1 */ public final class TeeInput implements Input { /** * The source. */ private final Input source; /** * The destination. */ private final Output target; /** * Ctor. * @param url The source * @param path The output file * @since 0.13.3 */ public TeeInput(final URL url, final Path path) { this(new InputOf(url), new OutputTo(path)); } /** * Ctor. * @param url The source * @param file The output file * @since 0.13.3 */ public TeeInput(final URL url, final File file) { this(new InputOf(url), new OutputTo(file)); } /** * Ctor. * @param url The source * @param output The output file * @since 0.13.3 */ public TeeInput(final URL url, final Output output) { this(new InputOf(url), output); } /** * Ctor. * @param uri The source * @param path The output file * @since 0.13.3 */ public TeeInput(final URI uri, final Path path) { this(new InputOf(uri), new OutputTo(path)); } /** * Ctor. * @param uri The source * @param file The output file * @since 0.13.3 */ public TeeInput(final URI uri, final File file) { this(new InputOf(uri), new OutputTo(file)); } /** * Ctor. * @param uri The source * @param output The output file * @since 0.13.3 */ public TeeInput(final URI uri, final Output output) { this(new InputOf(uri), output); } /** * Ctor. * @param input The source * @param path The output file * @since 0.5 */ public TeeInput(final Path input, final Path path) { this(new InputOf(input), new OutputTo(path)); } /** * Ctor. * @param input The source * @param file The output file * @since 0.5 */ public TeeInput(final Path input, final File file) { this(new InputOf(input), new OutputTo(file)); } /** * Ctor. * @param input The source * @param output The output * @since 0.13.3 */ public TeeInput(final Path input, final Output output) { this(new InputOf(input), output); } /** * Ctor. * @param input The source * @param file The output file * @since 0.5 */ public TeeInput(final File input, final File file) { this(new InputOf(input), new OutputTo(file)); } /** * Ctor. * @param input The source * @param path The output file * @since 0.5 */ public TeeInput(final File input, final Path path) { this(new InputOf(input), new OutputTo(path)); } /** * Ctor. * @param input The source * @param output The output * @since 0.13.3 */ public TeeInput(final File input, final Output output) { this(new InputOf(input), output); } /** * Ctor. * @param input The source * @param file The output file * @since 0.5 */ public TeeInput(final CharSequence input, final File file) { this(new InputOf(input), new OutputTo(file)); } /** * Ctor. * @param input The source * @param file The output file * @param charset The charset * @since 0.13.3 */ public TeeInput(final CharSequence input, final File file, final Charset charset) { this(new InputOf(input, charset), new OutputTo(file)); } /** * Ctor. * @param input The source * @param file The output file * @param charset The charset * @since 0.13.3 */ public TeeInput(final CharSequence input, final File file, final CharSequence charset) { this(new InputOf(input, charset), new OutputTo(file)); } /** * Ctor. * @param input The source * @param file The output file * @since 0.5 */ public TeeInput(final CharSequence input, final Path file) { this(new InputOf(input), new OutputTo(file)); } /** * Ctor. * @param input The source * @param file The output file * @param charset The charset * @since 0.13.3 */ public TeeInput(final CharSequence input, final Path file, final Charset charset) { this(new InputOf(input, charset), new OutputTo(file)); } /** * Ctor. * @param input The source * @param file The output file * @param charset The charset * @since 0.13.3 */ public TeeInput(final CharSequence input, final Path file, final CharSequence charset) { this(new InputOf(input, charset), new OutputTo(file)); } /** * Ctor. * @param input The source * @param output The target * @since 0.5 */ public TeeInput(final CharSequence input, final Output output) { this(new InputOf(input), output); } /** * Ctor. * @param input The source * @param output The target * @param charset The charset * @since 0.13.3 */ public TeeInput(final CharSequence input, final Output output, final Charset charset) { this(new InputOf(input, charset), output); } /** * Ctor. * @param input The source * @param output The target * @param charset The charset * @since 0.13.3 */ public TeeInput(final CharSequence input, final Output output, final CharSequence charset) { this(new InputOf(input, charset), output); } /** * Ctor. * @param input The source * @param file The output file * @since 0.13.3 */ public TeeInput(final Reader input, final File file) { this(new InputOf(input), new OutputTo(file)); } /** * Ctor. * @param input The source * @param file The output file * @param size Reading buffer size * @since 0.13.3 */ public TeeInput(final Reader input, final File file, final int size) { this(new InputOf(input, size), new OutputTo(file)); } /** * Ctor. * @param input The source * @param file The output file * @param charset The charset * @since 0.13.3 */ public TeeInput(final Reader input, final File file, final Charset charset) { this(new InputOf(input, charset), new OutputTo(file)); } /** * Ctor. * @param input The source * @param file The output file * @param charset The charset * @param size Reading buffer size * @since 0.13.3 * @checkstyle ParameterNumberCheck (5 lines) */ public TeeInput(final Reader input, final File file, final Charset charset, final int size) { this(new InputOf(input, charset, size), new OutputTo(file)); } /** * Ctor. * @param input The source * @param file The output file * @param charset The charset * @since 0.13.3 */ public TeeInput(final Reader input, final File file, final CharSequence charset) { this(new InputOf(input, charset), new OutputTo(file)); } /** * Ctor. * @param input The source * @param file The output file * @param charset The charset * @param size Reading buffer size * @since 0.13.3 * @checkstyle ParameterNumberCheck (5 lines) */ public TeeInput(final Reader input, final File file, final CharSequence charset, final int size) { this(new InputOf(input, charset, size), new OutputTo(file)); } /** * Ctor. * @param input The source * @param file The output file * @since 0.13.3 */ public TeeInput(final Reader input, final Path file) { this(new InputOf(input), new OutputTo(file)); } /** * Ctor. * @param input The source * @param file The output file * @param size Reading buffer size * @since 0.13.3 */ public TeeInput(final Reader input, final Path file, final int size) { this(new InputOf(input, size), new OutputTo(file)); } /** * Ctor. * @param input The source * @param file The output file * @param charset The charset * @since 0.13.3 */ public TeeInput(final Reader input, final Path file, final Charset charset) { this(new InputOf(input, charset), new OutputTo(file)); } /** * Ctor. * @param input The source * @param file The output file * @param charset The charset * @param size Reading buffer size * @since 0.13.3 * @checkstyle ParameterNumberCheck (5 lines) */ public TeeInput(final Reader input, final Path file, final Charset charset, final int size) { this(new InputOf(input, charset, size), new OutputTo(file)); } /** * Ctor. * @param input The source * @param file The output file * @param charset The charset * @since 0.13.3 */ public TeeInput(final Reader input, final Path file, final CharSequence charset) { this(new InputOf(input, charset), new OutputTo(file)); } /** * Ctor. * @param input The source * @param file The output file * @param charset The charset * @param size Reading buffer size * @since 0.13.3 * @checkstyle ParameterNumberCheck (5 lines) */ public TeeInput(final Reader input, final Path file, final CharSequence charset, final int size) { this(new InputOf(input, charset, size), new OutputTo(file)); } /** * Ctor. * @param input The source * @param output The target * @since 0.13.3 */ public TeeInput(final Reader input, final Output output) { this(new InputOf(input), output); } /** * Ctor. * @param input The source * @param output The target * @param size Reading buffer size * @since 0.13.3 */ public TeeInput(final Reader input, final Output output, final int size) { this(new InputOf(input, size), output); } /** * Ctor. * @param input The source * @param output The target * @param charset The charset * @since 0.13.3 */ public TeeInput(final Reader input, final Output output, final Charset charset) { this(new InputOf(input, charset), output); } /** * Ctor. * @param input The source * @param output The target * @param charset The charset * @param size Reading buffer size * @since 0.13.3 * @checkstyle ParameterNumberCheck (5 lines) */ public TeeInput(final Reader input, final Output output, final Charset charset, final int size) { this(new InputOf(input, charset, size), output); } /** * Ctor. * @param input The source * @param output The target * @param charset The charset * @since 0.13.3 */ public TeeInput(final Reader input, final Output output, final CharSequence charset) { this(new InputOf(input, charset), output); } /** * Ctor. * @param input The source * @param output The target * @param charset The charset * @param size Reading buffer size * @since 0.13.3 * @checkstyle ParameterNumberCheck (5 lines) */ public TeeInput(final Reader input, final Output output, final CharSequence charset, final int size) { this(new InputOf(input, charset, size), output); } /** * Ctor. * @param input The source * @param path The output path * @since 0.5 */ public TeeInput(final byte[] input, final Path path) { this(new InputOf(input), new OutputTo(path)); } /** * Ctor. * @param input The source * @param file The output file * @since 0.5 */ public TeeInput(final byte[] input, final File file) { this(new InputOf(input), new OutputTo(file)); } /** * Ctor. * @param input The source * @param output The output file * @since 0.5 */ public TeeInput(final byte[] input, final Output output) { this(new InputOf(input), output); } /** * Ctor. * @param input The source * @param path The output path * @since 0.5 */ public TeeInput(final char[] input, final Path path) { this(new InputOf(input), new OutputTo(path)); } /** * Ctor. * @param input The source * @param path The output path * @param charset Charset * @since 0.13.3 */ public TeeInput(final char[] input, final Path path, final Charset charset) { this(new InputOf(input, charset), new OutputTo(path)); } /** * Ctor. * @param input The source * @param path The output path * @param charset Charset * @since 0.13.3 */ public TeeInput(final char[] input, final Path path, final CharSequence charset) { this(new InputOf(input, charset), new OutputTo(path)); } /** * Ctor. * @param input The source * @param file The output file * @since 0.5 */ public TeeInput(final char[] input, final File file) { this(new InputOf(input), new OutputTo(file)); } /** * Ctor. * @param input The source * @param file The output file * @param charset Charset * @since 0.13.3 */ public TeeInput(final char[] input, final File file, final Charset charset) { this(new InputOf(input, charset), new OutputTo(file)); } /** * Ctor. * @param input The source * @param file The output file * @param charset Charset * @since 0.13.3 */ public TeeInput(final char[] input, final File file, final CharSequence charset) { this(new InputOf(input, charset), new OutputTo(file)); } /** * Ctor. * @param input The source * @param output The output file * @since 0.5 */ public TeeInput(final char[] input, final Output output) { this(new InputOf(input), output); } /** * Ctor. * @param input The source * @param output The output file * @param charset Charset * @since 0.13.3 */ public TeeInput(final char[] input, final Output output, final Charset charset) { this(new InputOf(input, charset), output); } /** * Ctor. * @param input The source * @param output The output file * @param charset Charset * @since 0.13.3 */ public TeeInput(final char[] input, final Output output, final CharSequence charset) { this(new InputOf(input, charset), output); } /** * Ctor. * @param text The source * @param path The output path * @since 0.13.3 */ public TeeInput(final Text text, final Path path) { this(new InputOf(text), new OutputTo(path)); } /** * Ctor. * @param text The source * @param path The output path * @param charset Charset * @since 0.13.3 */ public TeeInput(final Text text, final Path path, final Charset charset) { this(new InputOf(text, charset), new OutputTo(path)); } /** * Ctor. * @param text The source * @param path The output path * @param charset Charset * @since 0.13.3 */ public TeeInput(final Text text, final Path path, final CharSequence charset) { this(new InputOf(text, charset), new OutputTo(path)); } /** * Ctor. * @param text The source * @param file The output file * @since 0.13.3 */ public TeeInput(final Text text, final File file) { this(new InputOf(text), new OutputTo(file)); } /** * Ctor. * @param text The source * @param file The output file * @param charset Charset * @since 0.13.3 */ public TeeInput(final Text text, final File file, final Charset charset) { this(new InputOf(text, charset), new OutputTo(file)); } /** * Ctor. * @param text The source * @param file The output file * @param charset Charset * @since 0.13.3 */ public TeeInput(final Text text, final File file, final CharSequence charset) { this(new InputOf(text, charset), new OutputTo(file)); } /** * Ctor. * @param text The source * @param output The output * @since 0.13.3 */ public TeeInput(final Text text, final Output output) { this(new InputOf(text), output); } /** * Ctor. * @param text The source * @param output The output * @param charset Charset * @since 0.13.3 */ public TeeInput(final Text text, final Output output, final Charset charset) { this(new InputOf(text, charset), output); } /** * Ctor. * @param text The source * @param output The output * @param charset Charset * @since 0.13.3 */ public TeeInput(final Text text, final Output output, final CharSequence charset) { this(new InputOf(text, charset), output); } /** * Ctor. * @param bytes The source * @param path The output path * @since 0.13.3 */ public TeeInput(final Bytes bytes, final Path path) { this(new InputOf(bytes), new OutputTo(path)); } /** * Ctor. * @param bytes The source * @param file The output file * @since 0.13.3 */ public TeeInput(final Bytes bytes, final File file) { this(new InputOf(bytes), new OutputTo(file)); } /** * Ctor. * @param bytes The source * @param output The output * @since 0.13.3 */ public TeeInput(final Bytes bytes, final Output output) { this(new InputOf(bytes), output); } /** * Ctor. * @param input The source * @param path The output path * @since 0.13.3 */ public TeeInput(final Input input, final Path path) { this(input, new OutputTo(path)); } /** * Ctor. * @param input The source * @param file The output file * @since 0.13.3 */ public TeeInput(final Input input, final File file) { this(input, new OutputTo(file)); } /** * Ctor. * @param input The source * @param writer The output * @since 0.13.3 */ public TeeInput(final Input input, final Writer writer) { this(input, new OutputTo(writer)); } /** * Ctor. * @param input The source * @param writer The output * @param size Writing buffer size * @since 0.13.3 */ public TeeInput(final Input input, final Writer writer, final int size) { this(input, new OutputTo(writer, size)); } /** * Ctor. * @param input The source * @param writer The output * @param charset The charset * @since 0.13.3 */ public TeeInput(final Input input, final Writer writer, final Charset charset) { this(input, new OutputTo(writer, charset)); } /** * Ctor. * @param input The source * @param writer The output * @param charset The charset * @param size Writing buffer size * @since 0.13.3 * @checkstyle ParameterNumberCheck (5 lines) */ public TeeInput(final Input input, final Writer writer, final Charset charset, final int size) { this(input, new OutputTo(writer, charset, size)); } /** * Ctor. * @param input The source * @param writer The output * @param charset The charset * @since 0.13.3 */ public TeeInput(final Input input, final Writer writer, final CharSequence charset) { this(input, new OutputTo(writer, charset)); } /** * Ctor. * @param input The source * @param writer The output * @param charset The charset * @param size Writing buffer size * @since 0.13.3 * @checkstyle ParameterNumberCheck (5 lines) */ public TeeInput(final Input input, final Writer writer, final CharSequence charset, final int size) { this(input, new OutputTo(writer, charset, size)); } /** * Ctor. * @param input The source * @param output The target */ public TeeInput(final Input input, final Output output) { this.source = input; this.target = output; } @Override public InputStream stream() throws Exception { return new TeeInputStream( this.source.stream(), this.target.stream() ); } } cactoos-0.49/src/main/java/org/cactoos/io/TeeInputStream.java000066400000000000000000000061541400054650300241450ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.io; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; /** * Stream that copies input to output. * WARNING: * This class closes {@link TeeInputStream#output} * after {@link TeeInputStream#close()}. * *

There is no thread-safety guarantee. * * @since 0.1 */ public final class TeeInputStream extends InputStream { /** * Input. */ private final InputStream input; /** * Output. */ private final OutputStream output; /** * Ctor. * @param src Source of data * @param tgt Destination of data */ public TeeInputStream(final InputStream src, final OutputStream tgt) { super(); this.input = src; this.output = tgt; } @Override public int read() throws IOException { final int data = this.input.read(); if (data >= 0) { this.output.write(data); } return data; } @Override public int read(final byte[] buf) throws IOException { return this.read(buf, 0, buf.length); } @Override public int read(final byte[] buf, final int offset, final int len) throws IOException { final int max = this.input.read(buf, offset, len); if (max > 0) { this.output.write(buf, offset, max); } return max; } @Override public long skip(final long num) throws IOException { return this.input.skip(num); } @Override public int available() throws IOException { return this.input.available(); } @Override public void close() throws IOException { this.input.close(); this.output.close(); } @Override public void mark(final int limit) { this.input.mark(limit); } @Override public void reset() throws IOException { this.input.reset(); } @Override public boolean markSupported() { return this.input.markSupported(); } } cactoos-0.49/src/main/java/org/cactoos/io/TeeOutput.java000066400000000000000000000060351400054650300231700ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.io; import java.io.File; import java.io.OutputStream; import java.io.Writer; import java.nio.charset.Charset; import java.nio.file.Path; import org.cactoos.Output; /** * Output to Output copying pipe. * *

There is no thread-safety guarantee. * * @since 0.16 */ public final class TeeOutput implements Output { /** * The target. */ private final Output target; /** * The copy. */ private final Output copy; /** * Ctor. * @param tgt The target * @param cpy The copy destination * @param charset The charset */ public TeeOutput(final Output tgt, final Writer cpy, final Charset charset) { this(tgt, new OutputTo(cpy, charset)); } /** * Ctor. * @param tgt The target * @param cpy The copy destination */ public TeeOutput(final Output tgt, final Writer cpy) { this(tgt, new OutputTo(cpy)); } /** * Ctor. * @param tgt The target * @param cpy The copy destination */ public TeeOutput(final Output tgt, final Path cpy) { this(tgt, new OutputTo(cpy)); } /** * Ctor. * @param tgt The target * @param cpy The copy destination */ public TeeOutput(final Output tgt, final File cpy) { this(tgt, new OutputTo(cpy)); } /** * Ctor. * @param tgt The target * @param cpy The copy destination */ public TeeOutput(final Output tgt, final OutputStream cpy) { this(tgt, new OutputTo(cpy)); } /** * Ctor. * @param tgt The target * @param cpy The copy destination */ public TeeOutput(final Output tgt, final Output cpy) { this.target = tgt; this.copy = cpy; } @Override public OutputStream stream() throws Exception { return new TeeOutputStream( this.target.stream(), this.copy.stream() ); } } cactoos-0.49/src/main/java/org/cactoos/io/TeeOutputStream.java000066400000000000000000000053411400054650300243430ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.io; import java.io.IOException; import java.io.OutputStream; /** * Stream that copies output to output. * *

There is no thread-safety guarantee. * * @since 0.16 */ public final class TeeOutputStream extends OutputStream { /** * Output. */ private final OutputStream target; /** * Copy. */ private final OutputStream copy; /** * Ctor. * @param tgt Destination of data * @param cpy Copy */ public TeeOutputStream(final OutputStream tgt, final OutputStream cpy) { super(); this.target = tgt; this.copy = cpy; } @Override public void write(final int data) throws IOException { try { this.target.write(data); } finally { this.copy.write(data); } } @Override public void write(final byte[] buf) throws IOException { try { this.target.write(buf); } finally { this.copy.write(buf); } } @Override public void write(final byte[] buf, final int off, final int len) throws IOException { try { this.target.write(buf, off, len); } finally { this.copy.write(buf, off, len); } } @Override public void flush() throws IOException { try { this.target.flush(); } finally { this.copy.flush(); } } @Override public void close() throws IOException { try { this.target.close(); } finally { this.copy.close(); } } } cactoos-0.49/src/main/java/org/cactoos/io/TeeReader.java000066400000000000000000000043371400054650300230750ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.io; import java.io.IOException; import java.io.Reader; import java.io.Writer; /** * Input to Output copying reader. * *

There is no thread-safety guarantee. * @since 0.13 */ public final class TeeReader extends Reader { /** * The source. */ private final Reader source; /** * The destination. */ private final Writer destination; /** * Ctor. * @param reader The source * @param writer The destination */ public TeeReader(final Reader reader, final Writer writer) { super(); this.source = reader; this.destination = writer; } @Override public int read(final char[] cbuf, final int offset, final int length) throws IOException { final int done = this.source.read(cbuf, 0, length); if (done >= 0) { this.destination.write(cbuf); } return done; } @Override public void close() throws IOException { try { this.source.close(); } finally { this.destination.close(); } } } cactoos-0.49/src/main/java/org/cactoos/io/TempFile.java000066400000000000000000000104201400054650300227300ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.io; import java.io.Closeable; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import org.cactoos.Scalar; import org.cactoos.Text; import org.cactoos.scalar.IoChecked; import org.cactoos.scalar.Sticky; import org.cactoos.text.TextOf; /** * A temporary file. *

* These are ephemeral files to be used in small scopes. * Typical use looks like this: *

{@code
 *    try (final TempFile file = new TempFile()) {
 *       //write to the file
 *    }
 * }
* The physical file is deleted from the filesystem when the temp file is * closed. * * @since 1.0 */ public final class TempFile implements Scalar, Closeable { /** * Creates the temporary file, returning its path. */ private final Scalar file; /** * Ctor. *

* Specifies empty strings for suffix and prefix, and creates the file * in the filesystem's temporary directory denoted by the system property * {@code java.io.tmpdir}. * @since 1.0 */ public TempFile() { this("", ""); } /** * Ctor. *

* The temporary file will be created inside the filesystem's * temporary folder (system property: {@code java.io.tmpdir}). * @param prefix The temp filename's prefix * @param suffix The temp filename's suffix * @since 1.0 */ public TempFile(final String prefix, final String suffix) { this( () -> Paths.get(System.getProperty("java.io.tmpdir")), prefix, suffix ); } /** * Ctor. * @param dir The directory in which to create the temp file * @param prefix The temp filename's prefix * @param suffix The temp filename's suffix * @since 1.0 */ public TempFile( final Scalar dir, final String prefix, final String suffix) { this( dir, new TextOf(prefix), new TextOf(suffix) ); } /** * Ctor. * @param dir The directory in which to create the temp file * @param prefix The temp filename's prefix * @param suffix The temp filename's suffix * @since 1.0 */ public TempFile( final Scalar dir, final Text prefix, final Text suffix) { this( new Sticky<>( () -> Files.createTempFile( dir.value(), prefix.asString(), suffix.asString() ) ) ); } /** * Primary ctor. * @param fullpath Creates the file and returns the path to it * @since 1.0 */ private TempFile(final Scalar fullpath) { this.file = fullpath; } @Override public Path value() throws Exception { return this.file.value(); } /** * Deletes the file from the filesystem. * @checkstyle NoJavadocForOverriddenMethodsCheck (5 lines) * @checkstyle JavadocMethodCheck (5 lines) */ @Override public void close() throws IOException { Files.delete(new IoChecked<>(this).value()); } } cactoos-0.49/src/main/java/org/cactoos/io/TempFolder.java000066400000000000000000000106571400054650300233000ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.io; import java.io.Closeable; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Comparator; import org.cactoos.Scalar; import org.cactoos.Text; import org.cactoos.iterable.Sorted; import org.cactoos.proc.ForEach; import org.cactoos.proc.IoCheckedProc; import org.cactoos.scalar.IoChecked; import org.cactoos.scalar.Sticky; import org.cactoos.text.Joined; import org.cactoos.text.Randomized; import org.cactoos.text.TextOf; /** * A temporary folder. * This is ephemeral folder to be used in small scopes. * The physical folder is deleted from the filesystem when the temp folder is * closed. * @since 1.0 * @checkstyle ClassDataAbstractionCouplingCheck (500 lines) */ public final class TempFolder implements Scalar, Closeable { /** * Creates the temporary folder, returning its path. */ private final Scalar folder; /** * Ctor. * Creates new folder in temporary directory * with a random name. * @since 1.0 */ public TempFolder() { this( new Joined( new TextOf(""), new TextOf("tmp"), new Randomized( // @checkstyle MagicNumber (1 line) 5, '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' ) ) ); } /** * Ctor. * Creates new folder in temporary directory. * @param path Relative path to new directory. * @since 1.0 */ public TempFolder(final String path) { this(new TextOf(path)); } /** * Ctor. * Creates new folder in temporary directory. * @param path Relative path to new directory. * @since 1.0 */ public TempFolder(final Text path) { this( new Sticky<>( () -> Files.createDirectory( Paths.get( new Joined( File.separator, System.getProperty("java.io.tmpdir"), path.asString() ).asString() ) ) ) ); } /** * Primary ctor. * @param flr Creates the folder and returns the path to it * @since 1.0 */ private TempFolder(final Scalar flr) { this.folder = flr; } @Override public Path value() throws Exception { return this.folder.value(); } @Override public void close() throws IOException { new IoCheckedProc<>( new ForEach( path -> path.toFile().delete() ) ).exec( new Sorted<>( Comparator.reverseOrder(), new Directory( new IoChecked<>(this).value() ) ) ); } } cactoos-0.49/src/main/java/org/cactoos/io/UncheckedInput.java000066400000000000000000000033521400054650300241420ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.io; import java.io.InputStream; import org.cactoos.Input; import org.cactoos.scalar.Unchecked; /** * Input that doesn't throw checked {@link Exception}. * *

There is no thread-safety guarantee. * * @since 0.9 */ public final class UncheckedInput implements Input { /** * Original input. */ private final Input input; /** * Ctor. * @param ipt Input */ public UncheckedInput(final Input ipt) { this.input = ipt; } @Override public InputStream stream() { return new Unchecked<>(this.input::stream).value(); } } cactoos-0.49/src/main/java/org/cactoos/io/UncheckedOutput.java000066400000000000000000000033671400054650300243510ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.io; import java.io.OutputStream; import org.cactoos.Output; import org.cactoos.scalar.Unchecked; /** * Input that doesn't throw checked {@link Exception}. * *

There is no thread-safety guarantee. * * @since 0.9 */ public final class UncheckedOutput implements Output { /** * Original output. */ private final Output output; /** * Ctor. * @param opt Output */ public UncheckedOutput(final Output opt) { this.output = opt; } @Override public OutputStream stream() { return new Unchecked<>(this.output::stream).value(); } } cactoos-0.49/src/main/java/org/cactoos/io/WriterAsOutput.java000066400000000000000000000054361400054650300242170ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.io; import java.io.OutputStream; import java.io.Writer; import java.nio.charset.Charset; import java.nio.charset.CharsetDecoder; import java.nio.charset.StandardCharsets; import org.cactoos.Output; /** * Writer as {@link Output}. * *

This class is for internal use only. Use {@link OutputTo} instead.

* *

There is no thread-safety guarantee. * * @since 0.13 */ final class WriterAsOutput implements Output { /** * The writer. */ private final Writer writer; /** * The charset decoder. */ private final CharsetDecoder decoder; /** * The buffer size. */ private final int size; /** * Ctor. * @param wtr Writer */ WriterAsOutput(final Writer wtr) { this(wtr, StandardCharsets.UTF_8); } /** * Ctor. * @param wtr Writer * @param cset Charset */ WriterAsOutput(final Writer wtr, final Charset cset) { // @checkstyle MagicNumber (1 line) this(wtr, cset, 16 << 10); } /** * Ctor. * @param wtr Reader * @param cset Charset * @param max Buffer size */ WriterAsOutput(final Writer wtr, final Charset cset, final int max) { this(wtr, cset.newDecoder(), max); } /** * Ctor. * @param wtr Reader * @param ddr Decoder * @param max Buffer size */ WriterAsOutput(final Writer wtr, final CharsetDecoder ddr, final int max) { this.writer = wtr; this.decoder = ddr; this.size = max; } @Override public OutputStream stream() { return new WriterAsOutputStream(this.writer, this.decoder, this.size); } } cactoos-0.49/src/main/java/org/cactoos/io/WriterAsOutputStream.java000066400000000000000000000132321400054650300253640ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.io; import java.io.IOException; import java.io.OutputStream; import java.io.Writer; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.charset.Charset; import java.nio.charset.CharsetDecoder; import java.nio.charset.CoderResult; import java.nio.charset.CodingErrorAction; import java.nio.charset.StandardCharsets; /** * Writer as {@link OutputStream}. * *

This class is for internal use only. Use {@link OutputStreamTo} * instead.

* *

There is no thread-safety guarantee. * * @since 0.13 */ final class WriterAsOutputStream extends OutputStream { /** * Incoming data. */ private final ByteBuffer input; /** * Output ready to be flushed. */ private final CharBuffer output; /** * The writer. */ private final Writer writer; /** * The charset. */ private final CharsetDecoder decoder; /** * Ctor. * @param wtr Writer */ WriterAsOutputStream(final Writer wtr) { this(wtr, StandardCharsets.UTF_8); } /** * Ctor. * @param wtr Writer * @param charset Charset */ WriterAsOutputStream(final Writer wtr, final CharSequence charset) { // @checkstyle MagicNumber (1 line) this(wtr, charset, 16 << 10); } /** * Ctor. * @param wtr Writer * @param charset Charset */ WriterAsOutputStream(final Writer wtr, final Charset charset) { // @checkstyle MagicNumber (1 line) this(wtr, charset.name()); } /** * Ctor. * @param wtr Reader * @param charset Charset * @param size Buffer size */ WriterAsOutputStream(final Writer wtr, final CharSequence charset, final int size) { this(wtr, Charset.forName(charset.toString()), size); } /** * Ctor. * @param wtr Reader * @param size Buffer size * @since 0.13.3 */ WriterAsOutputStream(final Writer wtr, final int size) { this(wtr, StandardCharsets.UTF_8, size); } /** * Ctor. * @param wtr Reader * @param charset Charset * @param size Buffer size */ WriterAsOutputStream(final Writer wtr, final Charset charset, final int size) { this( wtr, charset.newDecoder() .onMalformedInput(CodingErrorAction.REPORT) .onUnmappableCharacter(CodingErrorAction.REPORT), size ); } /** * Ctor. * @param wtr Reader * @param ddr Charset decoder * @param size Buffer size */ WriterAsOutputStream(final Writer wtr, final CharsetDecoder ddr, final int size) { super(); this.writer = wtr; this.decoder = ddr; this.input = ByteBuffer.allocate(size); this.output = CharBuffer.allocate(size); } @Override public void write(final int data) throws IOException { this.write(new byte[] {(byte) data}, 0, 1); } @Override public void write(final byte[] buffer) throws IOException { this.write(buffer, 0, buffer.length); } @Override public void write(final byte[] buffer, final int offset, final int length) throws IOException { int left = length; int start = offset; while (left > 0) { final int taken = this.next(buffer, start, left); start += taken; left -= taken; } } @Override public void close() throws IOException { this.writer.close(); } /** * Write a portion from the buffer. * @param buffer The buffer * @param offset Offset in the buffer * @param length Maximum possible amount to take * @return How much was taken * @throws IOException If fails */ private int next(final byte[] buffer, final int offset, final int length) throws IOException { final int max = Math.min(length, this.input.remaining()); this.input.put(buffer, offset, max); this.input.flip(); while (true) { final CoderResult result = this.decoder.decode( this.input, this.output, false ); if (result.isError()) { result.throwException(); } this.writer.write( this.output.array(), 0, this.output.position() ); this.writer.flush(); this.output.rewind(); if (result.isUnderflow()) { break; } } this.input.compact(); return max; } } cactoos-0.49/src/main/java/org/cactoos/io/WriterTo.java000066400000000000000000000073041400054650300230110ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.io; import java.io.File; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Writer; import java.nio.charset.Charset; import java.nio.charset.CharsetEncoder; import java.nio.charset.StandardCharsets; import java.nio.file.Path; import org.cactoos.Output; import org.cactoos.Scalar; import org.cactoos.scalar.Sticky; import org.cactoos.scalar.Unchecked; /** * A {@link Writer} that encapsulates other destination for the data. * *

There is no thread-safety guarantee. * * @since 0.13 */ public final class WriterTo extends Writer { /** * The target. */ private final Unchecked target; /** * Ctor. * @param path The path */ public WriterTo(final Path path) { this(new OutputTo(path)); } /** * Ctor. * @param file The file */ public WriterTo(final File file) { this(new OutputTo(file)); } /** * Ctor. * @param stream The output */ public WriterTo(final OutputStream stream) { this(new OutputTo(stream)); } /** * Ctor. * @param output The input */ public WriterTo(final Output output) { this(output, StandardCharsets.UTF_8); } /** * Ctor. * @param output The input * @param charset The charset */ public WriterTo(final Output output, final Charset charset) { this(() -> new OutputStreamWriter(output.stream(), charset)); } /** * Ctor. * @param output The input * @param charset The charset */ public WriterTo(final Output output, final CharSequence charset) { this(() -> new OutputStreamWriter(output.stream(), charset.toString())); } /** * Ctor. * @param output The input * @param encoder Charset encoder * @since 0.13.1 */ public WriterTo(final Output output, final CharsetEncoder encoder) { this(() -> new OutputStreamWriter(output.stream(), encoder)); } /** * Ctor. * @param tgt Target */ private WriterTo(final Scalar tgt) { super(); this.target = new Unchecked<>( new Sticky<>(tgt) ); } @Override public void write(final char[] cbuf, final int off, final int len) throws IOException { this.target.value().write(cbuf, off, len); } @Override public void flush() throws IOException { this.target.value().flush(); } @Override public void close() throws IOException { this.target.value().close(); } } cactoos-0.49/src/main/java/org/cactoos/io/Zip.java000066400000000000000000000053361400054650300217770ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.io; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.nio.file.Path; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import org.cactoos.Input; import org.cactoos.bytes.BytesOf; /** * Zip files and directory. *
*
There is no thread-safety guarantee. * * @since 0.29 */ @SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops") public final class Zip implements Input { /** * Origin directory. */ private final Directory origin; /** * Ctor. * * @param origin Origin directory. */ public Zip(final Directory origin) { this.origin = origin; } @Override public InputStream stream() throws Exception { final ByteArrayOutputStream out = new ByteArrayOutputStream(); try (ZipOutputStream zip = new ZipOutputStream(out)) { for (final Path path : this.origin) { final File file = path.toFile(); final ZipEntry entry = new ZipEntry( file.getPath() ); zip.putNextEntry(entry); if (file.isFile()) { try ( FileInputStream input = new FileInputStream(file) ) { zip.write(new BytesOf(new InputOf(input)).asBytes()); } } zip.closeEntry(); } } return new ByteArrayInputStream(out.toByteArray()); } } cactoos-0.49/src/main/java/org/cactoos/io/package-info.java000066400000000000000000000023051400054650300235520ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ /** * Input/Output. * * @since 0.1 */ package org.cactoos.io; cactoos-0.49/src/main/java/org/cactoos/iterable/000077500000000000000000000000001400054650300215435ustar00rootroot00000000000000cactoos-0.49/src/main/java/org/cactoos/iterable/Cycled.java000066400000000000000000000033061400054650300236130ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.iterable; /** * Cycled Iterable. * *

There is no thread-safety guarantee. * * @param Type of item * @since 0.8 */ public final class Cycled extends IterableEnvelope { /** * Ctor. * @param itr Iterable * @since 0.23 */ @SafeVarargs public Cycled(final T... itr) { this(new IterableOf(itr)); } /** * Ctor. * @param itr Iterable */ public Cycled(final Iterable itr) { super(new IterableOf<>(() -> new org.cactoos.iterator.Cycled<>(itr))); } } cactoos-0.49/src/main/java/org/cactoos/iterable/Endless.java000066400000000000000000000030731400054650300240060ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.iterable; /** * Endless iterable. * *

If you need to repeat certain amount of time, * use {@link Repeated}.

* * @param Element type * @since 0.4 */ public final class Endless extends IterableEnvelope { /** * Ctor. * @param item The item to repeat */ public Endless(final T item) { super(new IterableOf<>(() -> new org.cactoos.iterator.Endless<>(item))); } } cactoos-0.49/src/main/java/org/cactoos/iterable/Filtered.java000066400000000000000000000053671400054650300241570ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.iterable; import org.cactoos.Func; import org.cactoos.Scalar; /** * Filtered iterable. * *

You can use it in order to create a declarative/lazy * version of a filtered collection/iterable. For example, * this code will create a list of two strings "hello" and "world":

* *
 Iterable<String> list = new Filtered<>(
 *   new ArrayOf<>(
 *     "hey", "hello", "world"
 *   ),
 *   input -> input.length() > 4
 * );
 * 
* *

There is no thread-safety guarantee. * * @param Type of item * @see Filtered * @since 0.1 */ public final class Filtered extends IterableEnvelope { /** * Ctor. * @param fnc Predicate * @param src Source iterable * @since 0.21 */ @SafeVarargs public Filtered(final Func fnc, final X... src) { this(fnc, new IterableOf<>(src)); } /** * Ctor. * @param fnc Predicate * @param src Source iterable */ public Filtered(final Func fnc, final Iterable src) { super( new IterableOf<>( () -> new org.cactoos.iterator.Filtered<>(fnc, src.iterator()) ) ); } /** * Ctor. * @param src Source iterable * @param fnc Predicate */ public Filtered(final Iterable src, final Func> fnc) { super( new IterableOf<>( () -> new org.cactoos.iterator.Filtered<>( src.iterator(), fnc ) ) ); } } cactoos-0.49/src/main/java/org/cactoos/iterable/HeadOf.java000066400000000000000000000037361400054650300235450ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.iterable; /** * Head portion of the iterable. * *

There is no thread-safety guarantee.

* * @param Element type * @since 0.8 */ public final class HeadOf extends IterableEnvelope { /** * Ctor. * @param num Number of head elements * @param src The underlying iterable */ @SafeVarargs public HeadOf(final int num, final T... src) { this(num, new IterableOf<>(src)); } /** * Ctor. * @param num Number of head elements * @param iterable Decorated iterable */ public HeadOf(final int num, final Iterable iterable) { super( new IterableOf<>( () -> new org.cactoos.iterator.HeadOf<>( num, iterable.iterator() ) ) ); } } cactoos-0.49/src/main/java/org/cactoos/iterable/IterableEnvelope.java000066400000000000000000000040311400054650300256310ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.iterable; import java.util.Iterator; /** * Iterable envelope. * *

There is no thread-safety guarantee. * * @param Type of item * @since 0.24 */ public abstract class IterableEnvelope implements Iterable { /** * The wrapped iterable. */ private final Iterable wrapped; /** * Ctor. * @param iterable The wrapped iterable */ public IterableEnvelope(final Iterable iterable) { this.wrapped = iterable; } @Override public final Iterator iterator() { return this.wrapped.iterator(); } @Override public final boolean equals(final Object other) { return this.wrapped.equals(other); } @Override public final int hashCode() { return this.wrapped.hashCode(); } @Override public final String toString() { return this.wrapped.toString(); } } cactoos-0.49/src/main/java/org/cactoos/iterable/IterableOf.java000066400000000000000000000104001400054650300244150ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.iterable; import java.util.Iterator; import org.cactoos.Fallback; import org.cactoos.Scalar; import org.cactoos.iterator.IteratorOf; import org.cactoos.scalar.And; import org.cactoos.scalar.Folded; import org.cactoos.scalar.Or; import org.cactoos.scalar.ScalarWithFallback; import org.cactoos.scalar.SumOfInt; import org.cactoos.scalar.Unchecked; import org.cactoos.text.TextOf; import org.cactoos.text.UncheckedText; /** * Array as iterable. * *

There is no thread-safety guarantee. * * @param Type of item * @since 0.12 * @checkstyle ClassDataAbstractionCouplingCheck (550 lines) */ public final class IterableOf implements Iterable { /** * The encapsulated iterator. */ private final Scalar> itr; /** * Ctor. * @param items The array */ @SafeVarargs public IterableOf(final X... items) { this(() -> new IteratorOf<>(items)); } /** * Ctor. * @param list The list * @since 0.21 */ public IterableOf(final Iterator list) { this(() -> list); } /** * Ctor. * @param sclr The encapsulated iterator of x */ public IterableOf(final Scalar> sclr) { this.itr = sclr; } @SuppressWarnings("unchecked") @Override public Iterator iterator() { return (Iterator) new Unchecked<>(this.itr).value(); } @Override @edu.umd.cs.findbugs.annotations.SuppressFBWarnings("EQ_UNUSUAL") @SuppressWarnings (value = "unchecked") public boolean equals(final Object other) { return new Unchecked<>( new Or( () -> other == this, new And( () -> other != null, () -> Iterable.class.isAssignableFrom(other.getClass()), () -> { final Iterable compared = (Iterable) other; return new ScalarWithFallback( new And( (X value) -> true, new Matched<>( this, compared ) ), new IterableOf<>( new Fallback.From<>( IllegalStateException.class, ex -> false ) ) ).value(); } ) ) ).value(); } // @checkstyle MagicNumberCheck (30 lines) @Override public int hashCode() { return new Unchecked<>( new Folded<>( 42, (hash, entry) -> new SumOfInt( () -> 37 * hash, entry::hashCode ).value(), this ) ).value(); } @Override public String toString() { return new UncheckedText(new TextOf(this)).asString(); } } cactoos-0.49/src/main/java/org/cactoos/iterable/IterableOfBooleans.java000066400000000000000000000030361400054650300261070ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.iterable; import org.cactoos.iterator.IteratorOfBooleans; /** * Iterable of boolean values. * * @since 1.0 */ public final class IterableOfBooleans extends IterableEnvelope { /** * Ctor. * @param values Boolean values */ public IterableOfBooleans(final boolean... values) { super(new IterableOf<>(() -> new IteratorOfBooleans(values))); } } cactoos-0.49/src/main/java/org/cactoos/iterable/IterableOfBytes.java000066400000000000000000000037731400054650300254430ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.iterable; import org.cactoos.Bytes; import org.cactoos.Text; import org.cactoos.bytes.BytesOf; import org.cactoos.iterator.IteratorOfBytes; /** * Iterable of bytes. * * @since 1.0 */ public final class IterableOfBytes extends IterableEnvelope { /** * Ctor. * @param txt Text */ public IterableOfBytes(final Text txt) { this(new BytesOf(txt)); } /** * Ctor. * @param str String */ public IterableOfBytes(final String str) { this(new BytesOf(str)); } /** * Ctor. * @param bytes Bytes */ public IterableOfBytes(final byte... bytes) { this(new BytesOf(bytes)); } /** * Ctor. * @param bytes Bytes to iterate */ public IterableOfBytes(final Bytes bytes) { super(new IterableOf<>(() -> new IteratorOfBytes(bytes))); } } cactoos-0.49/src/main/java/org/cactoos/iterable/IterableOfChars.java000066400000000000000000000034621400054650300254100ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.iterable; import org.cactoos.Text; import org.cactoos.iterator.IteratorOfChars; /** * Iterable of characters. * * @since 1.0 */ public final class IterableOfChars extends IterableEnvelope { /** * Ctor. * @param str String */ public IterableOfChars(final String str) { this(str.toCharArray()); } /** * Ctor. * @param txt Text */ public IterableOfChars(final Text txt) { this(txt.toString()); } /** * Ctor. * @param chars Characters */ public IterableOfChars(final char... chars) { super(new IterableOf<>(() -> new IteratorOfChars(chars))); } } cactoos-0.49/src/main/java/org/cactoos/iterable/IterableOfDoubles.java000066400000000000000000000030261400054650300257410ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.iterable; import org.cactoos.iterator.IteratorOfDoubles; /** * Iterable of double values. * * @since 1.0 */ public final class IterableOfDoubles extends IterableEnvelope { /** * Ctor. * @param values Double values */ public IterableOfDoubles(final double... values) { super(new IterableOf<>(() -> new IteratorOfDoubles(values))); } } cactoos-0.49/src/main/java/org/cactoos/iterable/IterableOfFloats.java000066400000000000000000000030161400054650300255730ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.iterable; import org.cactoos.iterator.IteratorOfFloats; /** * Iterable of float values. * * @since 1.0 */ public final class IterableOfFloats extends IterableEnvelope { /** * Ctor. * @param values Float values */ public IterableOfFloats(final float... values) { super(new IterableOf<>(() -> new IteratorOfFloats(values))); } } cactoos-0.49/src/main/java/org/cactoos/iterable/IterableOfInts.java000066400000000000000000000030121400054650300252540ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.iterable; import org.cactoos.iterator.IteratorOfInts; /** * Iterable of integer values. * * @since 1.0 */ public final class IterableOfInts extends IterableEnvelope { /** * Ctor. * @param values Integer values */ public IterableOfInts(final int... values) { super(new IterableOf<>(() -> new IteratorOfInts(values))); } } cactoos-0.49/src/main/java/org/cactoos/iterable/IterableOfLongs.java000066400000000000000000000030061400054650300254240ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.iterable; import org.cactoos.iterator.IteratorOfLongs; /** * Iterable of long values. * * @since 1.0 */ public final class IterableOfLongs extends IterableEnvelope { /** * Ctor. * @param values Long values */ public IterableOfLongs(final long... values) { super(new IterableOf<>(() -> new IteratorOfLongs(values))); } } cactoos-0.49/src/main/java/org/cactoos/iterable/IterableOfShorts.java000066400000000000000000000030771400054650300256340ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.iterable; import org.cactoos.iterator.IteratorOfShorts; /** * Iterable of short values. * * @since 1.0 */ public final class IterableOfShorts extends IterableEnvelope { /** * Ctor. * @param values Short values */ @SuppressWarnings("PMD.AvoidUsingShortType") public IterableOfShorts(final short... values) { super(new IterableOf<>(() -> new IteratorOfShorts(values))); } } cactoos-0.49/src/main/java/org/cactoos/iterable/Joined.java000066400000000000000000000043101400054650300236140ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.iterable; import java.util.Iterator; /** * A few Iterables joined together. * *

There is no thread-safety guarantee. * * @param Type of item * @since 0.1 */ public final class Joined extends IterableEnvelope { /** * Ctor. * @param items Items to concatenate */ @SafeVarargs public Joined(final Iterable... items) { this(new IterableOf<>(items)); } /** * Ctor. * @param item First item * @param items Iterable * @since 0.32 */ @SuppressWarnings("unchecked") public Joined(final T item, final Iterable items) { this(new IterableOf<>(new IterableOf<>(item), items)); } /** * Ctor. * @param items Items to concatenate */ public Joined(final Iterable> items) { super( new IterableOf<>( () -> new org.cactoos.iterator.Joined<>( new Mapped>(Iterable::iterator, items) ) ) ); } } cactoos-0.49/src/main/java/org/cactoos/iterable/Mapped.java000066400000000000000000000040141400054650300236130ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.iterable; import org.cactoos.Func; /** * Mapped iterable. * *

* There is no thread-safety guarantee. * * @param Type of target item * @since 0.1 */ public final class Mapped extends IterableEnvelope { /** * Ctor. * @param fnc Func * @param src Source iterable * @param Type of source item */ @SafeVarargs public Mapped(final Func fnc, final X... src) { this(fnc, new IterableOf<>(src)); } /** * Ctor. * @param fnc Func * @param src Source iterable * @param Type of source item */ public Mapped( final Func fnc, final Iterable src ) { super( new IterableOf<>( () -> new org.cactoos.iterator.Mapped<>(fnc, src.iterator()) ) ); } } cactoos-0.49/src/main/java/org/cactoos/iterable/Matched.java000066400000000000000000000046761400054650300237700ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.iterable; import org.cactoos.BiFunc; /** * Matched iterable. * * Iterates over 2 iterables at the same time and verify that elements with the * same position has correlation by the function. The function might be equals, * endsWith, greaterThen, nonNull, empty, negative, positive, etc. * * @param Type of item. * @since 0.39 */ public final class Matched extends IterableEnvelope { /** * Ctor. * @param fst The first part of duplex iterator. * @param snd The second part of duplex iterator. */ public Matched( final Iterable fst, final Iterable snd ) { this(Object::equals, fst, snd); } /** * Ctor. * @param fnc The function to detect the correlation between elements. * @param fst The first part of duplex iterator. * @param snd The second part of duplex iterator. * @param Type of item in snd. */ public Matched( final BiFunc fnc, final Iterable fst, final Iterable snd ) { super( new IterableOf<>( new org.cactoos.iterator.Matched<>( fnc, fst.iterator(), snd.iterator() ) ) ); } } cactoos-0.49/src/main/java/org/cactoos/iterable/NoNulls.java000066400000000000000000000033751400054650300240100ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.iterable; import java.util.Iterator; /** * A decorator for {@link Iterable} that doesn't allow any NULL. * *

There is no thread-safety guarantee. * * @param Type of item * @since 0.27 */ public final class NoNulls implements Iterable { /** * Original iterable. */ private final Iterable origin; /** * Ctor. * @param items The items */ public NoNulls(final Iterable items) { this.origin = items; } @Override public Iterator iterator() { return new org.cactoos.iterator.NoNulls<>(this.origin.iterator()); } } cactoos-0.49/src/main/java/org/cactoos/iterable/Paged.java000066400000000000000000000074151400054650300234350ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.iterable; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.concurrent.atomic.AtomicReference; import org.cactoos.Func; import org.cactoos.Scalar; import org.cactoos.func.UncheckedFunc; import org.cactoos.scalar.Sticky; import org.cactoos.scalar.Unchecked; /** * Paged iterable. * Elements will continue to be provided so long as {@code next} produces * non-empty iterators. * *

There is no thread-safety guarantee. * * @param Type of item * @since 0.47 * @todo #1183:30m Continue refactoring and add `iterator.Paged` by * extracting inner anon class from this class. The checkstyle suppression * should be removed after that. */ @SuppressWarnings("PMD.OnlyOneConstructorShouldDoInitialization") public final class Paged extends IterableEnvelope { /** * Ctor. *

* @param first First bag of elements * @param next Subsequent bags of elements * @param Custom iterator */ @SuppressWarnings("PMD.ConstructorOnlyInitializesOrCallOtherConstructors") public > Paged( final Scalar first, final Func next ) { // @checkstyle AnonInnerLengthCheck (30 lines) super( new IterableOf<>( () -> new Iterator() { private final AtomicReference> current = new AtomicReference<>( new Unchecked<>( new Sticky<>(first) ) ); private final UncheckedFunc subsequent = new UncheckedFunc<>(next); @Override public boolean hasNext() { if (!this.current.get().value().hasNext()) { final I next = this.subsequent.apply( this.current.get().value() ); this.current.set( new Unchecked<>( new Sticky<>(() -> next) ) ); } return this.current.get().value().hasNext(); } @Override public X next() { if (this.hasNext()) { return this.current.get().value().next(); } throw new NoSuchElementException(); } } ) ); } } cactoos-0.49/src/main/java/org/cactoos/iterable/Partitioned.java000066400000000000000000000040021400054650300246640ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.iterable; import java.util.List; /** * Iterable implementation for partitioning functionality. * * @param Partitions value type * @since 0.29 */ public final class Partitioned extends IterableEnvelope> { /** * Ctor. * @param size The partitions size. * @param items The source items. */ @SafeVarargs public Partitioned(final int size, final T...items) { this(size, new IterableOf<>(items)); } /** * Ctor. * @param size The partitions size. * @param iterable The source {@link Iterable}. */ public Partitioned(final int size, final Iterable iterable) { super( new IterableOf<>( () -> new org.cactoos.iterator.Partitioned<>( size, iterable.iterator() ) ) ); } } cactoos-0.49/src/main/java/org/cactoos/iterable/RangeOf.java000066400000000000000000000053051400054650300237320ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.iterable; import java.util.Iterator; import java.util.NoSuchElementException; import org.cactoos.Func; import org.cactoos.func.UncheckedFunc; /** * Iterable implementation to model range functionality. * @param Range value type * @since 1.0 */ public final class RangeOf> extends IterableEnvelope { /** * Ctor. * @param min Start of the range. * @param max End of the range. * @param incrementor The {@link Func} to process for the next value. */ @SuppressWarnings({ "PMD.CallSuperInConstructor", "PMD.ConstructorOnlyInitializesOrCallOtherConstructors" } ) public RangeOf(final T min, final T max, final Func incrementor) { super( new IterableOf<>( () -> new Iterator() { private final UncheckedFunc inc = new UncheckedFunc<>(incrementor); private T value = min; @Override public boolean hasNext() { return this.value.compareTo(max) < 1; } @Override public T next() { if (!this.hasNext()) { throw new NoSuchElementException(); } final T result = this.value; this.value = this.inc.apply(this.value); return result; } } ) ); } } cactoos-0.49/src/main/java/org/cactoos/iterable/Repeated.java000066400000000000000000000036461400054650300241500ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.iterable; import org.cactoos.Scalar; /** * Repeat an element. * *

If you need to repeat endlessly, use {@link Endless}.

* * @param Element type * @since 0.1 */ public final class Repeated extends IterableEnvelope { /** * Ctor. * @param total The total number of repetitions * @param elm The element to repeat */ public Repeated(final int total, final T elm) { this(total, () -> elm); } /** * Ctor. * @param total The total number of repetitions * @param elm The element to repeat */ public Repeated(final int total, final Scalar elm) { super( new IterableOf<>( () -> new org.cactoos.iterator.Repeated<>(total, elm) ) ); } } cactoos-0.49/src/main/java/org/cactoos/iterable/Reversed.java000066400000000000000000000036271400054650300241750ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.iterable; /** * Reverse iterable. * *

This loads the whole wrapped {@link Iterable} in memory * each time {@link #iterator()} is called in order to be able to reverse it. * *

There is no thread-safety guarantee. * * @param Type of item * @see Filtered * @since 0.9 */ public final class Reversed extends IterableEnvelope { /** * Ctor. * @param src Source iterable * @since 0.23 */ @SafeVarargs public Reversed(final X... src) { this(new IterableOf<>(src)); } /** * Ctor. * @param src Source iterable * @since 0.23 */ public Reversed(final Iterable src) { super(new IterableOf<>(() -> new org.cactoos.iterator.Reversed<>(src.iterator()))); } } cactoos-0.49/src/main/java/org/cactoos/iterable/Shuffled.java000066400000000000000000000034461400054650300241550ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.iterable; /** * Shuffled iterable. * *

There is no thread-safety guarantee.

* * @param Element type * @since 0.20 */ public final class Shuffled extends IterableEnvelope { /** * Ctor. * @param src The underlying iterable * @since 0.23 */ @SafeVarargs public Shuffled(final T... src) { this(new IterableOf<>(src)); } /** * Ctor. * @param src The underlying iterable */ public Shuffled(final Iterable src) { super( new IterableOf<>( () -> new org.cactoos.iterator.Shuffled<>(src.iterator()) ) ); } } cactoos-0.49/src/main/java/org/cactoos/iterable/Skipped.java000066400000000000000000000037101400054650300240060ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.iterable; /** * Skipped iterable. * *

There is no thread-safety guarantee.

* * @param Element type * @since 0.34 */ public final class Skipped extends IterableEnvelope { /** * Ctor. * @param skip How many to skip * @param src The underlying iterable */ @SafeVarargs public Skipped(final int skip, final T... src) { this(skip, new IterableOf<>(src)); } /** * Ctor. * @param skip Count skip elements * @param iterable Decorated iterable */ public Skipped(final int skip, final Iterable iterable) { super( new IterableOf<>( () -> new org.cactoos.iterator.Skipped<>( skip, iterable.iterator() ) ) ); } } cactoos-0.49/src/main/java/org/cactoos/iterable/Sliced.java000066400000000000000000000042451400054650300236160ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.iterable; /** * Sliced portion of the iterable. * *

There is no thread-safety guarantee.

* * @param Element type * @since 1.0.0 */ public final class Sliced extends IterableEnvelope { /** * Ctor. * @param start Starting index * @param count Maximum number of elements for resulted iterator * @param items Varargs items */ @SafeVarargs public Sliced(final int start, final int count, final T... items) { this(start, count, new IterableOf<>(items)); } /** * Ctor. * @param start Starting index * @param count Maximum number of elements for resulted iterator * @param iterable Decorated iterable */ public Sliced(final int start, final int count, final Iterable iterable) { super( new IterableOf<>( () -> new org.cactoos.iterator.Sliced<>( start, count, iterable.iterator() ) ) ); } } cactoos-0.49/src/main/java/org/cactoos/iterable/Solid.java000066400000000000000000000033411400054650300234610ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.iterable; /** * An {@link Iterable} that is both synchronized and sticky. * *

Objects of this class are thread-safe.

* * @param Type of item * @since 0.24 */ public final class Solid extends IterableEnvelope { /** * Ctor. * @param src The underlying iterable */ @SafeVarargs public Solid(final X... src) { this(new IterableOf<>(src)); } /** * Ctor. * @param iterable The iterable */ public Solid(final Iterable iterable) { super(new Synced<>(new Sticky<>(iterable))); } } cactoos-0.49/src/main/java/org/cactoos/iterable/Sorted.java000066400000000000000000000050411400054650300236460ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.iterable; import java.util.Comparator; /** * Sorted iterable. * *

There is no thread-safety guarantee.

* * @param Element type * @since 0.7 */ public final class Sorted extends IterableEnvelope { /** * Ctor. * @param src The underlying iterable */ @SafeVarargs public Sorted(final T... src) { this(new IterableOf<>(src)); } /** * Ctor. * *

If you're using this ctor you must be sure that type {@code T} * implements {@link Comparable} interface. Otherwise, there will be * a type casting exception in runtime.

* * @param src The underlying iterable */ @SuppressWarnings("unchecked") public Sorted(final Iterable src) { this((Comparator) Comparator.naturalOrder(), src); } /** * Ctor. * @param cmp The comparator * @param src The underlying iterable */ @SafeVarargs public Sorted(final Comparator cmp, final T... src) { this(cmp, new IterableOf<>(src)); } /** * Ctor. * @param cmp The comparator * @param src The underlying iterable */ public Sorted(final Comparator cmp, final Iterable src) { super( new IterableOf<>( () -> new org.cactoos.iterator.Sorted<>(cmp, src.iterator()) ) ); } } cactoos-0.49/src/main/java/org/cactoos/iterable/Sticky.java000066400000000000000000000040101400054650300236470ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.iterable; import org.cactoos.list.ListOf; import org.cactoos.scalar.Mapped; /** * Iterable that returns the same set of elements, always. * *

There is no thread-safety guarantee. * * @param Type of item * @since 0.1 */ public final class Sticky extends IterableEnvelope { /** * Ctor. * @param src The underlying iterable */ @SafeVarargs public Sticky(final X... src) { this(new IterableOf<>(src)); } /** * Ctor. * @param iterable The iterable */ public Sticky(final Iterable iterable) { super( new IterableOf( new Mapped<>( Iterable::iterator, new org.cactoos.scalar.Sticky<>( () -> new ListOf<>(iterable) ) ) ) ); } } cactoos-0.49/src/main/java/org/cactoos/iterable/Synced.java000066400000000000000000000053551400054650300236430ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.iterable; import java.util.Iterator; import org.cactoos.iterator.Mapped; /** * Synchronized iterable. * *

* This class should be used very carefully. You must understand that it will * fetch the entire content of the encapsulated {@link Iterable} on each method * call. It doesn't cache the data anyhow. If you don't need this * {@link Iterable} to re-fresh its content on every call, by doing round-trips * to the encapsulated iterable, use {@link Sticky}. *

* *

* Objects of this class are thread-safe. *

* @param Type of item * @since 0.24 */ public final class Synced implements Iterable { /** * The iterable. */ private final Iterable origin; /** * Sync lock. */ private final Object lock; /** * Ctor. * @param src The underlying iterable */ @SafeVarargs public Synced(final X... src) { this(new IterableOf<>(src)); } /** * Ctor. * @param iterable The iterable synchronize access to. */ public Synced(final Iterable iterable) { this(new Object(), iterable); } /** * Ctor. * @param lck The lock to synchronize with. * @param iterable The iterable synchronize access to. */ public Synced(final Object lck, final Iterable iterable) { this.origin = iterable; this.lock = lck; } @SuppressWarnings("unchecked") @Override public Iterator iterator() { synchronized (this.lock) { return (Iterator) this.origin.iterator(); } } } cactoos-0.49/src/main/java/org/cactoos/iterable/TailOf.java000066400000000000000000000037141400054650300235710ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.iterable; /** * Tail portion of the iterable. * *

There is no thread-safety guarantee.

* * @param Element type * @since 0.31 */ public final class TailOf extends IterableEnvelope { /** * Ctor. * @param num Number of tail elements * @param src The underlying iterable */ @SafeVarargs public TailOf(final int num, final T... src) { this(num, new IterableOf<>(src)); } /** * Ctor. * @param num Number of tail elements * @param iterable Decorated iterable */ public TailOf(final int num, final Iterable iterable) { super( new IterableOf<>( () -> new org.cactoos.iterator.TailOf<>( num, iterable.iterator() ) ) ); } } cactoos-0.49/src/main/java/org/cactoos/iterable/package-info.java000066400000000000000000000023111400054650300247270ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ /** * Iterables. * * @since 0.12 */ package org.cactoos.iterable; cactoos-0.49/src/main/java/org/cactoos/iterator/000077500000000000000000000000001400054650300216055ustar00rootroot00000000000000cactoos-0.49/src/main/java/org/cactoos/iterator/Cycled.java000066400000000000000000000045331400054650300236600ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.iterator; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.concurrent.atomic.AtomicReference; /** * Cycled Iterator. * *

There is no thread-safety guarantee. * * @param Type of item * @since 0.8 */ public final class Cycled implements Iterator { /** * Iterable. */ private final Iterable origin; /** * Iterator. */ private AtomicReference> reference; /** * Ctor. * @param iterable Iterable. */ public Cycled(final Iterable iterable) { this.origin = iterable; this.reference = new AtomicReference<>(iterable.iterator()); } @Override public boolean hasNext() { if (!this.reference.get().hasNext()) { this.reference.compareAndSet( this.reference.get(), this.origin.iterator() ); } return this.reference.get().hasNext(); } @Override public T next() { if (!this.hasNext()) { throw new NoSuchElementException( "The iterator doesn't have any more items" ); } return this.reference.get().next(); } } cactoos-0.49/src/main/java/org/cactoos/iterator/Endless.java000066400000000000000000000045451400054650300240550ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.iterator; import java.util.Iterator; import java.util.NoSuchElementException; import org.cactoos.Scalar; import org.cactoos.scalar.Unchecked; /** * Iterator that never ends. * *

If you need to repeat certain amount of time, * use {@link Repeated}.

* * @param Element type * @since 0.4 */ public final class Endless implements Iterator { /** * The element to repeat. */ private final Unchecked origin; /** * Ctor. * @param element Element to repeat */ public Endless(final T element) { this(() -> element); } /** * Ctor. * @param scalar Scalar to repeat */ public Endless(final Scalar scalar) { this(new Unchecked<>(scalar)); } /** * Ctor. * @param scalar Scalar to repeat */ public Endless(final Unchecked scalar) { this.origin = scalar; } @Override public boolean hasNext() { return this.origin.value() != null; } @Override public T next() { if (!this.hasNext()) { throw new NoSuchElementException( "The iterator doesn't have item" ); } return this.origin.value(); } } cactoos-0.49/src/main/java/org/cactoos/iterator/Filtered.java000066400000000000000000000073061400054650300242140ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.iterator; import java.util.Iterator; import java.util.LinkedList; import java.util.NoSuchElementException; import java.util.Queue; import org.cactoos.Func; import org.cactoos.Scalar; import org.cactoos.func.UncheckedFunc; import org.cactoos.scalar.Unchecked; /** * Filtered iterator. * *

You can use it in order to create a declarative/lazy * version of a filtered collection/iterable. For example, * this code will create a list of two strings "hello" and "world":

* *
 Iterator<String> list = new Filtered<>(
 *   new ArrayOf<>(
 *     "hey", "hello", "world"
 *   ).iterator(),
 *   input -> input.length() > 4
 * );
 * 
* *

There is no thread-safety guarantee. * * @param Type of item * @see Filtered * @since 0.1 */ public final class Filtered implements Iterator { /** * Iterator. */ private final Iterator iterator; /** * Predicate. */ private final Func> func; /** * The buffer storing the objects of the iterator. */ private final Queue buffer; /** * Ctor. * @param fnc Predicate * @param src Source iterable */ public Filtered( final Func fnc, final Iterator src ) { this(src, input -> () -> fnc.apply(input)); } /** * Ctor. * @param src Source iterable * @param fnc Predicate */ public Filtered( final Iterator src, final Func> fnc ) { this.iterator = src; this.func = fnc; this.buffer = new LinkedList<>(); } @Override public boolean hasNext() { final UncheckedFunc> fnc = new UncheckedFunc<>(this.func); if (this.buffer.isEmpty()) { while (this.iterator.hasNext()) { final X object = this.iterator.next(); if (new Unchecked<>(fnc.apply(object)).value()) { this.buffer.add(object); break; } } } return !this.buffer.isEmpty(); } @Override public X next() { if (!this.hasNext()) { throw new NoSuchElementException( "No more elements that fit the condition" ); } return this.buffer.poll(); } @Override public void remove() { throw new UnsupportedOperationException( "#remove() is not supported" ); } } cactoos-0.49/src/main/java/org/cactoos/iterator/HeadOf.java000066400000000000000000000031571400054650300236040ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.iterator; import java.util.Iterator; /** * Head portion of the iterator. * *

There is no thread-safety guarantee.

* * @param Element type * @since 0.8 */ public final class HeadOf extends IteratorEnvelope { /** * Ctor. * @param num Num of head elements * @param iterator Decorated iterator */ public HeadOf(final int num, final Iterator iterator) { super(new Sliced<>(0, num, iterator)); } } cactoos-0.49/src/main/java/org/cactoos/iterator/Immutable.java000066400000000000000000000036461400054650300244000ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.iterator; import java.util.Iterator; /** * Decorator that doesn't allow removal from the wrapped {@link Iterator}. * *

There is no thread-safety guarantee.

* * @param Element type * @since 0.32 */ public final class Immutable implements Iterator { /** * Decorated iterator. */ private final Iterator iterator; /** * Ctor. * @param iter Iterator to make immutable */ public Immutable(final Iterator iter) { this.iterator = iter; } @Override public boolean hasNext() { return this.iterator.hasNext(); } @Override public T next() { return this.iterator.next(); } @Override public String toString() { return this.iterator.toString(); } } cactoos-0.49/src/main/java/org/cactoos/iterator/IteratorEnvelope.java000066400000000000000000000046331400054650300257450ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.iterator; import java.util.Iterator; import java.util.function.Consumer; /** * {@link Iterator} that delegates to another {@link Iterator}. * *

There is no thread-safety guarantee.

* * @param Type of item * @since 0.43 */ public abstract class IteratorEnvelope implements Iterator { /** * Wrapped {@link Iterator}. */ private final Iterator wrapped; /** * Ctor. * @param iter The {@link Iterator} to wrap. */ public IteratorEnvelope(final Iterator iter) { this.wrapped = iter; } @Override public final boolean hasNext() { return this.wrapped.hasNext(); } @Override public final X next() { return this.wrapped.next(); } @Override public final void forEachRemaining(final Consumer action) { this.wrapped.forEachRemaining(action); } @Override public final void remove() { this.wrapped.remove(); } @Override public final String toString() { return this.wrapped.toString(); } @Override public final boolean equals(final Object obj) { return this.wrapped.equals(obj); } @Override public final int hashCode() { return this.wrapped.hashCode(); } } cactoos-0.49/src/main/java/org/cactoos/iterator/IteratorOf.java000066400000000000000000000043241400054650300245310ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.iterator; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.concurrent.atomic.AtomicInteger; /** * {@link Iterator} that returns the elements. * *

There is no thread-safety guarantee.

* * @param Type of item * @since 0.30 */ public final class IteratorOf implements Iterator { /** * The list of items to iterate. */ private final X[] list; /** * Current position. */ private final AtomicInteger position; /** * Ctor. * @param items Items to iterate */ @SafeVarargs public IteratorOf(final X... items) { this.list = items; this.position = new AtomicInteger(0); } @Override public boolean hasNext() { return this.position.intValue() < this.list.length; } @Override public X next() { if (!this.hasNext()) { throw new NoSuchElementException( "The iterator doesn't have any more items" ); } return this.list[this.position.getAndIncrement()]; } } cactoos-0.49/src/main/java/org/cactoos/iterator/IteratorOfBooleans.java000066400000000000000000000043501400054650300262130ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.iterator; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.concurrent.atomic.AtomicInteger; /** * {@link Iterator} that returns the {@code boolean}s as {@link Boolean}s. * *

There is no thread-safety guarantee.

* * @since 0.32 */ public final class IteratorOfBooleans implements Iterator { /** * The list of items to iterate. */ private final boolean[] list; /** * Current position. */ private final AtomicInteger position; /** * Ctor. * @param items Items to iterate */ public IteratorOfBooleans(final boolean... items) { this.list = items; this.position = new AtomicInteger(0); } @Override public boolean hasNext() { return this.position.intValue() < this.list.length; } @Override public Boolean next() { if (!this.hasNext()) { throw new NoSuchElementException( "The iterator doesn't have any more items" ); } return this.list[this.position.getAndIncrement()]; } } cactoos-0.49/src/main/java/org/cactoos/iterator/IteratorOfBytes.java000066400000000000000000000054061400054650300255420ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.iterator; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.concurrent.atomic.AtomicInteger; import org.cactoos.Bytes; import org.cactoos.Text; import org.cactoos.bytes.BytesOf; import org.cactoos.bytes.UncheckedBytes; /** * Iterator that returns a set of bytes. * *

There is no thread-safety guarantee. * * @since 0.34 */ public final class IteratorOfBytes implements Iterator { /** * The list of items to iterate. */ private final byte[] items; /** * Current position. */ private final AtomicInteger position; /** * Ctor. * @param txt Text to iterate */ public IteratorOfBytes(final Text txt) { this(new BytesOf(txt)); } /** * Ctor. * @param str String to iterate */ public IteratorOfBytes(final String str) { this(new BytesOf(str)); } /** * Ctor. * @param bytes Bytes to iterate */ public IteratorOfBytes(final Bytes bytes) { this(new UncheckedBytes(bytes).asBytes()); } /** * Ctor. * @param itms Items to iterate */ public IteratorOfBytes(final byte... itms) { this.items = itms; this.position = new AtomicInteger(0); } @Override public boolean hasNext() { return this.position.intValue() < this.items.length; } @Override public Byte next() { if (!this.hasNext()) { throw new NoSuchElementException( "The iterator doesn't have any more items" ); } return this.items[this.position.getAndIncrement()]; } } cactoos-0.49/src/main/java/org/cactoos/iterator/IteratorOfChars.java000066400000000000000000000050411400054650300255070ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.iterator; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.concurrent.atomic.AtomicInteger; import org.cactoos.Text; /** * {@link Iterator} that returns the {@code char}s as {@link Character}s. * *

There is no thread-safety guarantee.

* * @since 0.32 */ public final class IteratorOfChars implements Iterator { /** * The list of items to iterate. */ private final char[] list; /** * Current position. */ private final AtomicInteger position; /** * Ctor. * @param str String to iterate */ public IteratorOfChars(final String str) { this(str.toCharArray()); } /** * Ctor. * @param txt Text to iterate */ public IteratorOfChars(final Text txt) { this(txt.toString()); } /** * Ctor. * @param items Items to iterate */ public IteratorOfChars(final char... items) { this.list = items; this.position = new AtomicInteger(0); } @Override public boolean hasNext() { return this.position.intValue() < this.list.length; } @Override public Character next() { if (!this.hasNext()) { throw new NoSuchElementException( "The iterator doesn't have any more items" ); } return this.list[this.position.getAndIncrement()]; } } cactoos-0.49/src/main/java/org/cactoos/iterator/IteratorOfDoubles.java000066400000000000000000000043061400054650300260470ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.iterator; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.concurrent.atomic.AtomicInteger; /** * Iterator that returns a set of double values. * *

There is no thread-safety guarantee. * * @since 0.34 */ public final class IteratorOfDoubles implements Iterator { /** * The list of items to iterate. */ private final double[] items; /** * Current position. */ private final AtomicInteger position; /** * Ctor. * @param itms Items to iterate */ public IteratorOfDoubles(final double... itms) { this.items = itms; this.position = new AtomicInteger(0); } @Override public boolean hasNext() { return this.position.intValue() < this.items.length; } @Override public Double next() { if (!this.hasNext()) { throw new NoSuchElementException( "The iterator doesn't have any more items" ); } return this.items[this.position.getAndIncrement()]; } } cactoos-0.49/src/main/java/org/cactoos/iterator/IteratorOfFloats.java000066400000000000000000000043311400054650300257000ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.iterator; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.concurrent.atomic.AtomicInteger; /** * {@link Iterator} that returns the {@code float}s as {@link Float}s. * *

There is no thread-safety guarantee.

* * @since 0.32 */ public final class IteratorOfFloats implements Iterator { /** * The list of items to iterate. */ private final float[] items; /** * Current position. */ private final AtomicInteger position; /** * Ctor. * @param itms Items to iterate */ public IteratorOfFloats(final float... itms) { this.items = itms; this.position = new AtomicInteger(0); } @Override public boolean hasNext() { return this.position.intValue() < this.items.length; } @Override public Float next() { if (!this.hasNext()) { throw new NoSuchElementException( "The iterator doesn't have any more items" ); } return this.items[this.position.getAndIncrement()]; } } cactoos-0.49/src/main/java/org/cactoos/iterator/IteratorOfInts.java000066400000000000000000000043251400054650300253700ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.iterator; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.concurrent.atomic.AtomicInteger; /** * {@link Iterator} that returns the {@code int}s as {@link Integer}s. * *

There is no thread-safety guarantee.

* * @since 0.32 */ public final class IteratorOfInts implements Iterator { /** * The list of items to iterate. */ private final int[] items; /** * Current position. */ private final AtomicInteger position; /** * Ctor. * @param itms Items to iterate */ public IteratorOfInts(final int... itms) { this.items = itms; this.position = new AtomicInteger(0); } @Override public boolean hasNext() { return this.position.intValue() < this.items.length; } @Override public Integer next() { if (!this.hasNext()) { throw new NoSuchElementException( "The iterator doesn't have any more items" ); } return this.items[this.position.getAndIncrement()]; } } cactoos-0.49/src/main/java/org/cactoos/iterator/IteratorOfLongs.java000066400000000000000000000043221400054650300255320ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.iterator; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.concurrent.atomic.AtomicInteger; /** * {@link Iterator} that returns the {@code long}s as {@link Long}s. * *

There is no thread-safety guarantee.

* * @since 0.34 */ public final class IteratorOfLongs implements Iterator { /** * The list of items to iterate. */ private final long[] items; /** * Current position. */ private final AtomicInteger position; /** * Ctor. * @param itms Items to iterate */ public IteratorOfLongs(final long... itms) { this.items = itms; this.position = new AtomicInteger(0); } @Override public boolean hasNext() { return this.position.intValue() < this.items.length; } @Override public Long next() { if (!this.hasNext()) { throw new NoSuchElementException( "The iterator doesn't have any more items" ); } return this.items[this.position.getAndIncrement()]; } } cactoos-0.49/src/main/java/org/cactoos/iterator/IteratorOfShorts.java000066400000000000000000000044071400054650300257360ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.iterator; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.concurrent.atomic.AtomicInteger; /** * {@link Iterator} that returns the {@code short}s as {@link Short}s. * *

There is no thread-safety guarantee.

* * @since 0.34 */ @SuppressWarnings("PMD.AvoidUsingShortType") public final class IteratorOfShorts implements Iterator { /** * The list of items to iterate. */ private final short[] items; /** * Current position. */ private final AtomicInteger position; /** * Ctor. * @param itms Items to iterate */ public IteratorOfShorts(final short... itms) { this.items = itms; this.position = new AtomicInteger(0); } @Override public boolean hasNext() { return this.position.intValue() < this.items.length; } @Override public Short next() { if (!this.hasNext()) { throw new NoSuchElementException( "The iterator doesn't have any more items" ); } return this.items[this.position.getAndIncrement()]; } } cactoos-0.49/src/main/java/org/cactoos/iterator/Joined.java000066400000000000000000000056201400054650300236630ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.iterator; import java.util.Collections; import java.util.Iterator; import org.cactoos.iterable.IterableOf; /** * A few Iterators joined together. * *

There is no thread-safety guarantee. * * @param Type of item * @since 0.1 */ public final class Joined implements Iterator { /** * Iterators. */ private final Iterator> iters; /** * Current traversal iterator. */ private Iterator current; /** * Ctor. * @param items Items to concatenate */ @SafeVarargs public Joined(final Iterator... items) { this(new IterableOf<>(items)); } /** * Ctor. * @param item First item * @param items Iterable * @since 0.49 */ @SuppressWarnings("unchecked") public Joined(final T item, final Iterator items) { this(new IterableOf<>(new IteratorOf<>(item), items)); } /** * Ctor. * @param items Iterable * @param item End item * @since 0.49 */ @SuppressWarnings("unchecked") public Joined(final Iterator items, final T item) { this(new IterableOf<>(items, new IteratorOf<>(item))); } /** * Ctor. * @param items Items to concatenate */ public Joined(final Iterable> items) { this.iters = items.iterator(); this.current = Collections.emptyIterator(); } @Override public boolean hasNext() { while (!this.current.hasNext() && this.iters.hasNext()) { this.current = this.iters.next(); } return this.current.hasNext(); } @Override public T next() { this.hasNext(); return this.current.next(); } } cactoos-0.49/src/main/java/org/cactoos/iterator/Mapped.java000066400000000000000000000050121400054650300236540ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.iterator; import java.util.Iterator; import java.util.NoSuchElementException; import org.cactoos.Func; import org.cactoos.scalar.Unchecked; /** * Mapped iterator. * *

* There is no thread-safety guarantee. * * @param Type of target item * @since 0.1 */ public final class Mapped extends IteratorEnvelope { /** * Ctor. * @param func Func * @param iterator Source iterator * @param Type of item * @checkstyle AnonInnerLengthCheck (60 lines) */ public Mapped( final Func func, final Iterator iterator ) { super( new Iterator() { @Override public boolean hasNext() { return iterator.hasNext(); } @Override public Y next() { if (this.hasNext()) { return new Unchecked<>( new org.cactoos.scalar.Mapped<>( func, iterator::next ) ).value(); } throw new NoSuchElementException(); } @Override public void remove() { iterator.remove(); } } ); } } cactoos-0.49/src/main/java/org/cactoos/iterator/Matched.java000066400000000000000000000062201400054650300240150ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.iterator; import java.util.Iterator; import org.cactoos.BiFunc; import org.cactoos.func.UncheckedBiFunc; import org.cactoos.text.FormattedText; /** * Matched iterator. * * Iterates over 2 iterators at the same time and verify that elements with the * same position has correlation by the function. The function might be equals, * endsWith, greaterThen, nonNull, empty, negative, positive, etc. * * @param Type of item in first iterator. * @param Type of item in second iterator. * @since 0.47 */ public final class Matched implements Iterator { /** * The correlation function. */ private final UncheckedBiFunc func; /** * First iterator. */ private final Iterator first; /** * Second iterator. */ private final Iterator second; /** * Ctor. * @param fnc The function to detect the correlation between elements. * @param fst The first part of duplex iterator. * @param snd The second part of duplex iterator. */ public Matched( final BiFunc fnc, final Iterator fst, final Iterator snd ) { this.func = new UncheckedBiFunc<>(fnc); this.first = fst; this.second = snd; } @Override public boolean hasNext() { return this.first.hasNext() || this.second.hasNext(); } @Override public X next() { if (!this.first.hasNext() || !this.second.hasNext()) { throw new IllegalStateException("Size mismatch of iterators"); } final X fvl = this.first.next(); final Y svl = this.second.next(); if (!this.func.apply(fvl, svl)) { throw new IllegalStateException( new FormattedText( "There is no correlation between `%s` and `%s`.", fvl, svl ).toString() ); } return fvl; } } cactoos-0.49/src/main/java/org/cactoos/iterator/NoNulls.java000066400000000000000000000047301400054650300240460ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.iterator; import java.util.Iterator; import java.util.concurrent.atomic.AtomicLong; import org.cactoos.text.FormattedText; import org.cactoos.text.UncheckedText; /** * A decorator of an {@link Iterator} that returns no NULL. * *

There is no thread-safety guarantee. * * @param Type of item * @since 0.27 */ public final class NoNulls implements Iterator { /** * Iterator. */ private final Iterator iterator; /** * Position. */ private final AtomicLong pos; /** * Ctor. * @param src Source iterable */ public NoNulls(final Iterator src) { this.iterator = src; this.pos = new AtomicLong(); } @Override public boolean hasNext() { return this.iterator.hasNext(); } @Override public X next() { final X next = this.iterator.next(); if (next == null) { throw new IllegalStateException( new UncheckedText( new FormattedText( "Item #%d of %s is NULL", this.pos.get(), this.iterator ) ).asString() ); } this.pos.incrementAndGet(); return next; } @Override public void remove() { this.iterator.remove(); } } cactoos-0.49/src/main/java/org/cactoos/iterator/Partitioned.java000066400000000000000000000045751400054650300247450ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.iterator; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; import org.cactoos.list.Immutable; import org.cactoos.list.ListOf; /** * Iterator implementation for {@link Iterator} partitioning. * * @param Partitions value type * @since 0.29 */ public final class Partitioned implements Iterator> { /** * Iterator to decorate. */ private final Iterator decorated; /** * Size of the partitions. */ private final int size; /** * Ctor. * * @param sze Size of the partitions. * @param src Source iterator. */ public Partitioned(final int sze, final Iterator src) { this.size = sze; this.decorated = src; } @Override public boolean hasNext() { return this.decorated.hasNext(); } @Override public List next() { if (!this.hasNext()) { throw new NoSuchElementException("No partition left."); } if (this.size < 1) { throw new IllegalArgumentException("Partition size < 1"); } return new Immutable<>( new ListOf<>(new Sliced<>(0, this.size, this.decorated)) ); } } cactoos-0.49/src/main/java/org/cactoos/iterator/Repeated.java000066400000000000000000000051771400054650300242130ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.iterator; import java.util.Iterator; import java.util.NoSuchElementException; import org.cactoos.Scalar; import org.cactoos.scalar.Unchecked; /** * Repeat an element. * *

If you need to repeat endlessly, use {@link Endless}.

* * @param Element type * @since 0.4 */ public final class Repeated implements Iterator { /** * The element to repeat. */ private final Unchecked elm; /** * How many more repeats will happen. */ private int repeat; /** * Ctor. * @param max How many times to repeat * @param element Element to repeat */ public Repeated(final int max, final T element) { this(max, () -> element); } /** * Ctor. * @param max How many times to repeat * @param scalar Scalar to repeat */ public Repeated(final int max, final Scalar scalar) { this(max, new Unchecked(scalar)); } /** * Ctor. * @param max How many times to repeat * @param scalar Scalar to repeat */ private Repeated(final int max, final Unchecked scalar) { this.elm = scalar; this.repeat = max; } @Override public boolean hasNext() { return this.repeat > 0; } @Override public T next() { if (!this.hasNext()) { throw new NoSuchElementException( "The iterator can't repeat anymore." ); } --this.repeat; return this.elm.value(); } } cactoos-0.49/src/main/java/org/cactoos/iterator/Reversed.java000066400000000000000000000046771400054650300242450ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.iterator; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import org.cactoos.list.ListOf; /** * Reverse iterator. * *

This loads the whole wrapped Iterator in memory in order * to be able to reverse it. * *

There is no thread-safety guarantee. * * @param Type of item * @since 1.0 */ public final class Reversed implements Iterator { /** * Origin iterator to be reversed. */ private final ListIterator origin; /** * Ctor. * @param src Source iterator * @since 1.0 */ @SafeVarargs public Reversed(final X... src) { this(new IteratorOf<>(src)); } /** * Ctor. * @param src Source iterator * @since 1.0 */ public Reversed(final Iterator src) { this(new ListOf<>(src)); } /** * Ctor. * @param src Source list */ private Reversed(final List src) { this(src.listIterator(src.size())); } /** * Ctor. * @param src Source list iterator */ private Reversed(final ListIterator src) { this.origin = src; } @Override public boolean hasNext() { return this.origin.hasPrevious(); } @Override public X next() { return this.origin.previous(); } } cactoos-0.49/src/main/java/org/cactoos/iterator/Shuffled.java000066400000000000000000000044741400054650300242210ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.iterator; import java.util.Collections; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import org.cactoos.scalar.Sticky; import org.cactoos.scalar.Unchecked; /** * Shuffled iterator. * *

There is no thread-safety guarantee.

* * @param Element type * @since 0.20 */ public final class Shuffled implements Iterator { /** * Shuffled scalar. */ private final Unchecked> scalar; /** * Ctor. * @param iterator The original iterator */ public Shuffled(final Iterator iterator) { this.scalar = new Unchecked<>( new Sticky<>( () -> { final List items = new LinkedList<>(); while (iterator.hasNext()) { items.add(iterator.next()); } Collections.shuffle(items); return items.iterator(); } ) ); } @Override public boolean hasNext() { return this.scalar.value().hasNext(); } @Override public T next() { return this.scalar.value().next(); } } cactoos-0.49/src/main/java/org/cactoos/iterator/Skipped.java000066400000000000000000000035201400054650300240470ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.iterator; import java.util.Iterator; /** * Skipped iterator. * *

There is no thread-safety guarantee.

* * @param Element type * @since 0.34 */ public final class Skipped implements Iterator { /** * Sliced iterator. */ private final Iterator sliced; /** * Ctor. * @param skp Count skip elements * @param iterator Decorated iterator */ public Skipped(final int skp, final Iterator iterator) { this.sliced = new Sliced<>(skp, iterator); } @Override public boolean hasNext() { return this.sliced.hasNext(); } @Override public T next() { return this.sliced.next(); } } cactoos-0.49/src/main/java/org/cactoos/iterator/Sliced.java000066400000000000000000000074471400054650300236670ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.iterator; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.function.IntPredicate; /** * Creates an iterator returning an interval(slice) of the original iterator * by means of providing starting index, number of elements to retrieve from * the starting index and a decorated original iterator. * Can be used to retrieve the head, tail or a portion in the middle of the * original iterator. * *

There is no thread-safety guarantee.

* @param The type of the iterator. * @since 1.0.0 */ public final class Sliced implements Iterator { /** * Decorated iterator. */ private final Iterator iterator; /** * First index of the resulted iterator. */ private final int start; /** * Current index on the original iterator. */ private int current; /** * Predicate which tests whether the end has been reached. */ private IntPredicate end; /** * Constructor. * @param start Starting index * @param count Maximum number of elements for resulted iterator * @param iterator Decorated iterator */ public Sliced(final int start, final int count, final Iterator iterator) { this(start, index -> index > start + count - 1, iterator); } /** * Constructor. * Constructs an iterator of start position and up to the end * @param start Starting index * @param iterator Decorated iterator */ public Sliced(final int start, final Iterator iterator) { this(start, any -> !iterator.hasNext(), iterator); } /** * Constructor. * @param start Starting index * @param end Predicate that test whether iterating should stop * @param iterator Decorated iterator */ private Sliced(final int start, final IntPredicate end, final Iterator iterator) { this.start = start; this.end = end; this.iterator = iterator; this.current = 0; } @Override public boolean hasNext() { this.skip(); return !this.end.test(this.current) && this.iterator.hasNext(); } @Override public T next() { if (!this.hasNext()) { throw new NoSuchElementException( "The iterator doesn't have items any more" ); } ++this.current; return this.iterator.next(); } /** * Skips head elements up to start index. */ private void skip() { while (this.current < this.start && this.iterator.hasNext()) { this.iterator.next(); ++this.current; } } } cactoos-0.49/src/main/java/org/cactoos/iterator/Sorted.java000066400000000000000000000054671400054650300237240ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.iterator; import java.util.Comparator; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import org.cactoos.scalar.Sticky; import org.cactoos.scalar.Unchecked; /** * Sorted iterator. * *

There is no thread-safety guarantee.

* * @param Element type * @since 0.7 */ public final class Sorted implements Iterator { /** * Sorted one. */ private final Unchecked> scalar; /** * Ctor. * *

If you're using this ctor you must be sure that type {@code T} * implements {@link Comparable} interface. Otherwise, there will be * a type casting exception in runtime.

* * @param items The underlying iterator */ @SuppressWarnings("unchecked") public Sorted(final Iterator items) { this((Comparator) Comparator.naturalOrder(), items); } /** * Ctor. * @param comparator The comparator * @param iterator The underlying iterator */ public Sorted(final Comparator comparator, final Iterator iterator) { this.scalar = new Unchecked<>( new Sticky<>( () -> { final List items = new LinkedList<>(); while (iterator.hasNext()) { items.add(iterator.next()); } items.sort(comparator); return items.iterator(); } ) ); } @Override public boolean hasNext() { return this.scalar.value().hasNext(); } @Override public T next() { return this.scalar.value().next(); } } cactoos-0.49/src/main/java/org/cactoos/iterator/Synced.java000066400000000000000000000056151400054650300237040ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.iterator; import java.util.Iterator; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; /** * Synchronized {@link Iterator} implementation using a {@link ReadWriteLock} * either provided to the constructor or an internally created * {@link ReentrantReadWriteLock}. * *

The {@link ReadWriteLock} is used to synchronize read calls to * {@link Synced#hasNext()} against write calls to * {@link Synced#next()} and write calls to any other read or write * calls.

* *

Objects of this class are thread-safe.

* * @param The type of the iterator. * @since 1.0 */ public final class Synced implements Iterator { /** * The original iterator. */ private final Iterator iterator; /** * The lock to use. */ private final ReadWriteLock lock; /** * Ctor. * @param iterator The iterator to synchronize access to. */ public Synced(final Iterator iterator) { this(new ReentrantReadWriteLock(), iterator); } /** * Ctor. * @param lock The lock to use for synchronization. * @param iterator The iterator to synchronize access to. */ public Synced(final ReadWriteLock lock, final Iterator iterator) { this.iterator = iterator; this.lock = lock; } @Override public boolean hasNext() { this.lock.readLock().lock(); try { return this.iterator.hasNext(); } finally { this.lock.readLock().unlock(); } } @Override public T next() { this.lock.writeLock().lock(); try { return this.iterator.next(); } finally { this.lock.writeLock().unlock(); } } } cactoos-0.49/src/main/java/org/cactoos/iterator/TailOf.java000066400000000000000000000037731400054650300236400ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.iterator; import java.util.Iterator; import org.cactoos.iterable.HeadOf; import org.cactoos.iterable.IterableOf; import org.cactoos.iterable.Reversed; /** * Tail portion of the iterator. * *

* There is no thread-safety guarantee. *

* @param Element type * @since 0.31 */ public final class TailOf extends IteratorEnvelope { /** * Ctor. * @param num Number of tail elements * @param iterator Decorated iterator */ @SuppressWarnings({ "unchecked", "cast" }) public TailOf(final int num, final Iterator iterator) { super( (Iterator) new Reversed<>( new HeadOf<>( num, new Reversed<>( new IterableOf<>(iterator) ) ) ).iterator() ); } } cactoos-0.49/src/main/java/org/cactoos/iterator/package-info.java000066400000000000000000000023111400054650300247710ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ /** * Iterators. * * @since 0.12 */ package org.cactoos.iterator; cactoos-0.49/src/main/java/org/cactoos/list/000077500000000000000000000000001400054650300207275ustar00rootroot00000000000000cactoos-0.49/src/main/java/org/cactoos/list/Immutable.java000066400000000000000000000127751400054650300235250ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.list; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.ListIterator; /** * Decorator that doesn't allow mutations of the wrapped {@link List}. * *

There is no thread-safety guarantee.

* * @param Element type * @since 1.16 * @checkstyle ClassDataAbstractionCouplingCheck (500 lines) */ @SuppressWarnings( { "PMD.TooManyMethods", "PMD.AbstractNaming", "PMD.AvoidDuplicateLiterals" } ) public final class Immutable implements List { /** * Encapsulated list. */ private final List list; /** * Ctor. * @param src Source collection */ public Immutable(final List src) { this.list = src; } @Override public int size() { return this.list.size(); } @Override public boolean isEmpty() { return this.list.isEmpty(); } @Override public boolean contains(final Object item) { return this.list.contains(item); } @Override public Iterator iterator() { return new org.cactoos.iterator.Immutable<>(this.list.iterator()); } @Override public Object[] toArray() { return this.list.toArray(); } @Override @SuppressWarnings("PMD.UseVarargs") public X[] toArray(final X[] array) { return this.list.toArray(array); } @Override public boolean add(final T item) { throw new UnsupportedOperationException( "#add(T): the list is read-only" ); } @Override public boolean remove(final Object item) { throw new UnsupportedOperationException( "#remove(Object): the list is read-only" ); } @Override public boolean containsAll(final Collection items) { return this.list.containsAll(items); } @Override public boolean addAll(final Collection items) { throw new UnsupportedOperationException( "#addAll(Collection): the list is read-only" ); } @Override public boolean addAll(final int index, final Collection items) { throw new UnsupportedOperationException( "#addAll(int, Collection): the list is read-only" ); } @Override public boolean removeAll(final Collection items) { throw new UnsupportedOperationException( "#removeAll(): the list is read-only" ); } @Override public boolean retainAll(final Collection items) { throw new UnsupportedOperationException( "#retainAll(): the list is read-only" ); } @Override public void clear() { throw new UnsupportedOperationException( "#clear(): the list is read-only" ); } @Override public T get(final int index) { return this.list.get(index); } @Override public T set(final int index, final T item) { throw new UnsupportedOperationException( "#set(): the list is read-only" ); } @Override public void add(final int index, final T item) { throw new UnsupportedOperationException( "#add(int, T): the list is read-only" ); } @Override public T remove(final int index) { throw new UnsupportedOperationException( "#remove(int): the list is read-only" ); } @Override public int indexOf(final Object item) { return this.list.indexOf(item); } @Override public int lastIndexOf(final Object item) { return this.list.lastIndexOf(item); } @Override public ListIterator listIterator() { return new ImmutableListIterator<>( this.list.listIterator() ); } @Override public ListIterator listIterator(final int index) { return new ImmutableListIterator<>( this.list.listIterator(index) ); } @Override public List subList(final int start, final int end) { return new Immutable<>( this.list.subList(start, end) ); } @Override public boolean equals(final Object other) { return this.list.equals(other); } @Override public int hashCode() { return this.list.hashCode(); } @Override public String toString() { return this.list.toString(); } } cactoos-0.49/src/main/java/org/cactoos/list/ImmutableListIterator.java000066400000000000000000000053731400054650300260670ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.list; import java.util.ListIterator; /** * Immutable {@link ListIterator} that doesn't allow mutations. * *

There is no thread-safety guarantee. * * @param Items type * @since 1.0 */ public final class ImmutableListIterator implements ListIterator { /** * Original list iterator. */ private final ListIterator origin; /** * Ctor. * @param iter Original list iterator. */ public ImmutableListIterator(final ListIterator iter) { this.origin = iter; } @Override public boolean hasNext() { return this.origin.hasNext(); } @Override public T next() { return this.origin.next(); } @Override public boolean hasPrevious() { return this.origin.hasPrevious(); } @Override public T previous() { return this.origin.previous(); } @Override public int nextIndex() { return this.origin.nextIndex(); } @Override public int previousIndex() { return this.origin.previousIndex(); } @Override public void remove() { throw new UnsupportedOperationException( "List Iterator is read-only and doesn't allow removing items" ); } @Override public void set(final T item) { throw new UnsupportedOperationException( "List Iterator is read-only and doesn't allow rewriting items" ); } @Override public void add(final T item) { throw new UnsupportedOperationException( "List Iterator is read-only and doesn't allow adding items" ); } } cactoos-0.49/src/main/java/org/cactoos/list/Joined.java000066400000000000000000000041611400054650300230040ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.list; import java.util.List; import java.util.stream.Collectors; import org.cactoos.iterable.IterableOf; /** * Joined list. * *

There is no thread-safety guarantee. * * @param Type of source item * @since 0.20 */ public final class Joined extends ListEnvelope { /** * Ctor. * @param src Source lists */ @SafeVarargs public Joined(final List... src) { this(new IterableOf<>(src)); } /** * Ctor. * @param item First item * @param items List * @since 0.32 */ @SuppressWarnings("unchecked") public Joined(final X item, final List items) { this(new ListOf<>(item), items); } /** * Ctor. * @param src Source lists */ public Joined(final Iterable> src) { super( new ListOf<>(src).stream() .flatMap(List::stream) .collect(Collectors.toList()) ); } } cactoos-0.49/src/main/java/org/cactoos/list/ListEnvelope.java000066400000000000000000000061141400054650300242050ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.list; import java.util.Collection; import java.util.List; import java.util.ListIterator; import org.cactoos.collection.CollectionEnvelope; /** * {@link List} envelope. * *

There is no thread-safety guarantee.

* * @param Element type * @since 0.23 * @checkstyle AbstractClassNameCheck (500 lines) */ @SuppressWarnings( { "PMD.TooManyMethods", "PMD.AbstractNaming" } ) public abstract class ListEnvelope extends CollectionEnvelope implements List { /** * Encapsulated list. */ private final List list; /** * Ctor. * @param list Encapsulated list */ public ListEnvelope(final List list) { super(list); this.list = list; } @Override public final boolean addAll(final int index, final Collection items) { return this.list.addAll(index, items); } @Override public final T get(final int index) { return this.list.get(index); } @Override public final T set(final int index, final T element) { return this.list.set(index, element); } @Override public final void add(final int index, final T element) { this.list.add(index, element); } @Override public final T remove(final int index) { return this.list.remove(index); } @Override public final int indexOf(final Object item) { return this.list.indexOf(item); } @Override public final int lastIndexOf(final Object item) { return this.list.lastIndexOf(item); } @Override public final ListIterator listIterator() { return this.list.listIterator(); } @Override public final ListIterator listIterator(final int index) { return this.list.listIterator(index); } @Override public final List subList(final int start, final int end) { return this.list.subList(start, end); } } cactoos-0.49/src/main/java/org/cactoos/list/ListIteratorEnvelope.java000066400000000000000000000047401400054650300257220ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.list; import java.util.ListIterator; /** * {@link ListIterator} envelope. * *

There is no thread-safety guarantee. * * @param Items type * @since 0.47 */ public abstract class ListIteratorEnvelope implements ListIterator { /** * Original list iterator. */ private final ListIterator origin; /** * Ctor. * @param iter Original list iterator. */ public ListIteratorEnvelope(final ListIterator iter) { this.origin = iter; } @Override public final boolean hasNext() { return this.origin.hasNext(); } @Override public final T next() { return this.origin.next(); } @Override public final boolean hasPrevious() { return this.origin.hasPrevious(); } @Override public final T previous() { return this.origin.previous(); } @Override public final int nextIndex() { return this.origin.nextIndex(); } @Override public final int previousIndex() { return this.origin.previousIndex(); } @Override public final void remove() { this.origin.remove(); } @Override public final void set(final T item) { this.origin.set(item); } @Override public final void add(final T item) { this.origin.add(item); } } cactoos-0.49/src/main/java/org/cactoos/list/ListIteratorNoNulls.java000066400000000000000000000060661400054650300255420ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.list; import java.util.ListIterator; /** * A decorator of {@link ListIterator} that tolerates no NULLs. * *

There is no thread-safety guarantee.

* * @param Element type * @since 0.39 */ public final class ListIteratorNoNulls implements ListIterator { /** * ListIterator. */ private final ListIterator listiterator; /** * Ctor. * * @param src List iterator. */ public ListIteratorNoNulls(final ListIterator src) { this.listiterator = src; } @Override public boolean hasNext() { return this.listiterator.hasNext(); } @Override public T next() { final T next = this.listiterator.next(); if (next == null) { throw new IllegalStateException("Next item is NULL"); } return next; } @Override public boolean hasPrevious() { return this.listiterator.hasPrevious(); } @Override public T previous() { final T prev = this.listiterator.previous(); if (prev == null) { throw new IllegalStateException("Previous item is NULL"); } return prev; } @Override public int nextIndex() { return this.listiterator.nextIndex(); } @Override public int previousIndex() { return this.listiterator.previousIndex(); } @Override public void remove() { this.listiterator.remove(); } @Override public void set(final T item) { if (item == null) { throw new IllegalArgumentException( "Item can't be NULL in #set(T)" ); } this.listiterator.set(item); } @Override public void add(final T item) { if (item == null) { throw new IllegalArgumentException( "Item can't be NULL in #add(T)" ); } this.listiterator.add(item); } } cactoos-0.49/src/main/java/org/cactoos/list/ListOf.java000066400000000000000000000040011400054650300227650ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.list; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import org.cactoos.iterable.IterableOf; /** * Implementation of {@link List}. * *

There is no thread-safety guarantee. * * @param List type * @since 0.1 */ public final class ListOf extends ListEnvelope { /** * Ctor. * * @param array An array of some elements */ @SafeVarargs public ListOf(final T... array) { this(new IterableOf<>(array)); } /** * Ctor. * @param src An {@link Iterator} * @since 0.21 */ public ListOf(final Iterator src) { this(new IterableOf(src)); } /** * Ctor. * @param src An {@link Iterable} */ public ListOf(final Iterable src) { super(new LinkedList<>()); src.forEach(super::add); } } cactoos-0.49/src/main/java/org/cactoos/list/NoNulls.java000066400000000000000000000154021400054650300231660ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.list; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import org.cactoos.text.FormattedText; import org.cactoos.text.UncheckedText; /** * A decorator of {@link List} that tolerates no NULLs. * *

There is no thread-safety guarantee.

* * @param Element type * @since 0.27 */ @SuppressWarnings("PMD.TooManyMethods") public final class NoNulls implements List { /** * Encapsulated list. */ private final List list; /** * Ctor. * @param src Source */ NoNulls(final List src) { this.list = src; } @Override public int size() { return this.list.size(); } @Override public boolean isEmpty() { return this.list.isEmpty(); } @Override public boolean contains(final Object item) { return new org.cactoos.collection.NoNulls<>(this.list).contains(item); } @Override public Iterator iterator() { return new org.cactoos.collection.NoNulls<>(this.list).iterator(); } @Override public Object[] toArray() { return new org.cactoos.collection.NoNulls<>(this.list).toArray(); } @Override @SuppressWarnings("PMD.UseVarargs") public X[] toArray(final X[] array) { return new org.cactoos.collection.NoNulls<>(this.list).toArray(array); } @Override public boolean add(final T item) { return new org.cactoos.collection.NoNulls<>(this.list).add(item); } @Override public boolean remove(final Object item) { return new org.cactoos.collection.NoNulls<>(this.list).remove(item); } @Override public boolean containsAll(final Collection items) { return new org.cactoos.collection.NoNulls<>( this.list ).containsAll(items); } @Override public boolean addAll(final Collection items) { return new org.cactoos.collection.NoNulls<>( this.list ).addAll(items); } @Override public boolean addAll(final int index, final Collection items) { return this.list.addAll( index, new org.cactoos.collection.NoNulls<>(items) ); } @Override public boolean removeAll(final Collection items) { return new org.cactoos.collection.NoNulls<>(this.list).removeAll(items); } @Override public boolean retainAll(final Collection items) { return new org.cactoos.collection.NoNulls<>(this.list).retainAll(items); } @Override public void clear() { this.list.clear(); } @Override public T get(final int index) { final T item = this.list.get(index); if (item == null) { throw new IllegalStateException( new UncheckedText( new FormattedText( "Item #%d of %s is NULL", index, this.list ) ).asString() ); } return item; } @Override public T set(final int index, final T item) { if (item == null) { throw new IllegalArgumentException( new UncheckedText( new FormattedText( "Item can't be NULL in #set(%d,T)", index ) ).asString() ); } final T result = this.list.set(index, item); if (result == null) { throw new IllegalStateException( new UncheckedText( new FormattedText( "Result of #set(%d,T) is NULL", index ) ).asString() ); } return result; } @Override public void add(final int index, final T item) { if (item == null) { throw new IllegalArgumentException( new UncheckedText( new FormattedText( "Item can't be NULL in #add(%d,T)", index ) ).asString() ); } this.list.add(index, item); } @Override public T remove(final int index) { final T result = this.list.remove(index); if (result == null) { throw new IllegalStateException( new UncheckedText( new FormattedText( "Result of #remove(%d) is NULL", index ) ).asString() ); } return result; } @Override public int indexOf(final Object item) { if (item == null) { throw new IllegalArgumentException( "Item can't be NULL in #indexOf(T)" ); } return this.list.indexOf(item); } @Override public int lastIndexOf(final Object item) { if (item == null) { throw new IllegalArgumentException( "Item can't be NULL in #lastIndexOf(T)" ); } return this.list.lastIndexOf(item); } @Override public ListIterator listIterator() { return new ListIteratorNoNulls<>(this.list.listIterator()); } @Override public ListIterator listIterator(final int index) { return new ListIteratorNoNulls<>(this.list.listIterator(index)); } @Override public List subList(final int start, final int end) { return new NoNulls<>(this.list.subList(start, end)); } } cactoos-0.49/src/main/java/org/cactoos/list/Synced.java000066400000000000000000000030601400054650300230160ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.list; import java.util.Collections; import java.util.List; /** * Synchronized list. * *

Objects of this class are thread-safe.

* * @param Type of item * @since 0.24 */ public final class Synced extends ListEnvelope { /** * Ctor. * @param list The underlying list */ public Synced(final List list) { super(Collections.synchronizedList(list)); } } cactoos-0.49/src/main/java/org/cactoos/list/package-info.java000066400000000000000000000023101400054650300241120ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ /** * Lists, tests. * * @since 0.14 */ package org.cactoos.list; cactoos-0.49/src/main/java/org/cactoos/map/000077500000000000000000000000001400054650300205315ustar00rootroot00000000000000cactoos-0.49/src/main/java/org/cactoos/map/Grouped.java000066400000000000000000000045161400054650300230070ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.map; import java.util.List; import java.util.Map; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.StreamSupport; /** * Iterable as {@link Map}. * *

* This class groups objects from iterable by applying functions for keys and * values *

* *

* There is no thread-safety guarantee. * * @param Type of key * @param Type of value * @param Type of entry objects of functions * @since 0.30 */ public final class Grouped extends MapEnvelope> { /** * Ctor. * * @param list Iterable which is used to retrieve data from * @param keys Function to get a key * @param values Function to get a value */ public Grouped( final Iterable list, final Function keys, final Function values ) { super( StreamSupport.stream( list.spliterator(), false ).collect( Collectors.groupingBy( keys, Collectors.mapping(values, Collectors.toList()) ) ) ); } } cactoos-0.49/src/main/java/org/cactoos/map/MapEntry.java000066400000000000000000000056771400054650300231520ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.map; import java.util.Map; import org.cactoos.text.FormattedText; import org.cactoos.text.UncheckedText; /** * MapEntry as {@link java.util.AbstractMap.Entry}. * *

There is no thread-safety guarantee. * * @param Key type * @param Value type * @since 0.9 */ public final class MapEntry implements Map.Entry { /** * The key. */ private final K key; /** * The value. */ private final V value; /** * Ctor. * @param src The key of the entry's map. * @param trgt The value associated to the key of the entry's map. */ public MapEntry(final K src, final V trgt) { this.key = src; this.value = trgt; } @Override public String toString() { return new UncheckedText( new FormattedText( "%s=%s", this.key, this.value ) ).asString(); } @Override public K getKey() { return this.key; } @Override public V getValue() { return this.value; } @Override public V setValue(final V val) { throw new UnsupportedOperationException( "#setValue() is not supported" ); } @Override public boolean equals(final Object obj) { return obj instanceof Map.Entry && Map.Entry.class.cast(obj).getKey().equals(this.key) && Map.Entry.class.cast(obj).getValue().equals(this.value); } @Override public int hashCode() { int hash; if (this.key == null) { hash = 0; } else { hash = this.key.hashCode(); } if (this.value == null) { hash ^= 1; } else { hash ^= this.value.hashCode(); } return hash; } } cactoos-0.49/src/main/java/org/cactoos/map/MapEnvelope.java000066400000000000000000000070141400054650300236110ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.map; import java.util.Collection; import java.util.Map; import java.util.Set; import org.cactoos.text.TextOf; /** * Map envelope. * *

There is no thread-safety guarantee. * * @param Type of key * @param Type of value * @since 0.24 * @checkstyle AbstractClassNameCheck (500 lines) * @checkstyle ClassDataAbstractionCouplingCheck (500 lines) */ @SuppressWarnings( { "PMD.TooManyMethods", "PMD.AbstractNaming" } ) public abstract class MapEnvelope implements Map { /** * The map. */ private final Map map; /** * Ctor. * @param original The original map. */ public MapEnvelope(final Map original) { this.map = original; } @Override public final int size() { return this.map.size(); } @Override public final boolean isEmpty() { return this.map.isEmpty(); } @Override public final boolean containsKey(final Object key) { return this.map.containsKey(key); } @Override public final boolean containsValue(final Object value) { return this.map.containsValue(value); } @Override public final Y get(final Object key) { return this.map.get(key); } @Override public final Y put(final X key, final Y value) { return this.map.put(key, value); } @Override public final Y remove(final Object key) { return this.map.remove(key); } @Override public final void putAll(final Map extra) { this.map.putAll(extra); } @Override public final void clear() { this.map.clear(); } @Override public final Set keySet() { return this.map.keySet(); } @Override public final Collection values() { return this.map.values(); } @Override public final Set> entrySet() { return this.map.entrySet(); } @Override public final String toString() { return new StringBuilder() .append('{') .append(new TextOf(this.entrySet()).toString()) .append('}') .toString(); } @Override public final boolean equals(final Object other) { return this.map.equals(other); } @Override public final int hashCode() { return this.map.hashCode(); } } cactoos-0.49/src/main/java/org/cactoos/map/MapOf.java000066400000000000000000000114101400054650300223730ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.map; import java.util.HashMap; import java.util.Map; import org.cactoos.Func; import org.cactoos.iterable.IterableOf; import org.cactoos.iterable.Joined; import org.cactoos.iterable.Mapped; /** * Iterable as {@link Map}. * *

* This class should be used very carefully. You must understand that it will * fetch the entire content of the encapsulated {@link Map} on each method call. * It doesn't cache the data anyhow. * *

* There is no thread-safety guarantee. * * @param Type of key * @param Type of value * @since 0.4 */ public final class MapOf extends MapEnvelope { /** * Ctor. * @param list List of entries */ @SafeVarargs public MapOf(final Map.Entry... list) { this(new IterableOf<>(list)); } /** * Ctor. * @param src The map to extend * @param list List of entries * @since 0.12 */ @SafeVarargs public MapOf( final Map src, final Map.Entry... list ) { this(src, new IterableOf<>(list)); } /** * Ctor. * @param key Func to create key * @param value Func to create value * @param list List of items * @param Type of items in the list * @since 0.11 */ public MapOf( final Func key, final Func value, final Iterable list ) { this(item -> new MapEntry<>(key.apply(item), value.apply(item)), list); } /** * Ctor. * @param key Func to create key * @param value Func to create value * @param src The map to extend * @param list List of items * @param Type of items in the list * @since 0.12 * @checkstyle ParameterNumberCheck (5 lines) */ public MapOf( final Func key, final Func value, final Map src, final Iterable list ) { this( item -> new MapEntry<>(key.apply(item), value.apply(item)), src, list ); } /** * Ctor. * @param entry Func to create entry * @param list List of items * @param Type of items in the list * @since 0.11 */ public MapOf( final Func> entry, final Iterable list ) { this(new Mapped<>(entry, list)); } /** * Ctor. * @param entry Func to create entry * @param src The map to extend * @param list List of items * @param Type of items in the list * @since 0.11 */ public MapOf( final Func> entry, final Map src, final Iterable list ) { this(src, new Mapped<>(entry, list)); } /** * Ctor. * @param src Map to extend * @param list List of the entries * @since 0.12 */ public MapOf( final Map src, final Iterable> list ) { this(new Joined>(src.entrySet(), list)); } /** * Ctor. * @param entries List of the entries */ public MapOf(final Iterable> entries) { super(new HashMap<>()); for (final Entry entry : entries) { this.put(entry.getKey(), entry.getValue()); } } } cactoos-0.49/src/main/java/org/cactoos/map/Merged.java000066400000000000000000000035601400054650300226030ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.map; import java.util.Map; import java.util.stream.Collectors; import org.cactoos.list.ListOf; /** * This class can be used to merge a few {@link Map}. * Repeatable keys will be overridden by next ones. * * @param Key type * @param Value type * @since 1.0 */ public final class Merged extends MapEnvelope { /** * Ctor. * @param maps Maps to merge. */ @SafeVarargs public Merged(final Map... maps) { super( new MapOf<>( new ListOf<>(maps) .stream() .flatMap(map -> map.entrySet().stream()) .collect(Collectors.toList()) ) ); } } cactoos-0.49/src/main/java/org/cactoos/map/NoNulls.java000066400000000000000000000123741400054650300227750ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.map; import java.util.Collection; import java.util.Map; import java.util.Set; import org.cactoos.text.FormattedText; import org.cactoos.text.UncheckedText; /** * A decorator of {@link Map} that tolerates no NULLs. * *

There is no thread-safety guarantee. * * @param Type of key * @param Type of value * @since 0.27 */ @SuppressWarnings("PMD.TooManyMethods") public class NoNulls implements Map { /** * The map. */ private final Map map; /** * Ctor. * @param origin The scalar */ public NoNulls(final Map origin) { this.map = origin; } @Override public final int size() { return this.map.size(); } @Override public final boolean isEmpty() { return this.map.isEmpty(); } @Override public final boolean containsKey(final Object key) { if (key == null) { throw new IllegalStateException( "Key at #containsKey(K) is NULL" ); } return this.map.containsKey(key); } @Override public final boolean containsValue(final Object value) { if (value == null) { throw new IllegalStateException( "Value at #containsValue(K) is NULL" ); } return this.map.containsValue(value); } @Override public final V get(final Object key) { if (key == null) { throw new IllegalStateException( "Key at #get(K) is NULL" ); } final V value = this.map.get(key); if (value == null) { throw new IllegalStateException( new UncheckedText( new FormattedText( "Value returned by #get(%s) is NULL", key ) ).asString() ); } return value; } @Override public final V put(final K key, final V value) { if (key == null) { throw new IllegalStateException( new UncheckedText( new FormattedText( "Key at #put(K,%s) is NULL", value ) ).asString() ); } if (value == null) { throw new IllegalStateException( new UncheckedText( new FormattedText( "Value at #put(%s,V) is NULL", key ) ).asString() ); } final V result = this.map.put(key, value); if (result == null) { throw new IllegalStateException( new UncheckedText( new FormattedText( "Value returned by #put(%s,%s) is NULL", key, value ) ).asString() ); } return result; } @Override public final V remove(final Object key) { if (key == null) { throw new IllegalStateException( "Key at #remove(K) is NULL" ); } final V result = this.map.remove(key); if (result == null) { throw new IllegalStateException( new UncheckedText( new FormattedText( "Value returned by #remove(%s) is NULL", key ) ).asString() ); } return result; } @Override @SuppressWarnings("unchecked") public final void putAll(final Map items) { this.map.putAll(new NoNulls<>((Map) items)); } @Override public final void clear() { this.map.clear(); } @Override public final Set keySet() { return this.map.keySet(); } @Override public final Collection values() { return new org.cactoos.collection.NoNulls<>(this.map.values()); } @Override public final Set> entrySet() { return this.map.entrySet(); } } cactoos-0.49/src/main/java/org/cactoos/map/Synced.java000066400000000000000000000115021400054650300226200ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.map; import java.util.Collections; import java.util.Map; import org.cactoos.Func; import org.cactoos.iterable.IterableOf; import org.cactoos.iterable.Mapped; /** * Map decorator that goes through the map only once. * *

* The map is read-only. *

* *

* Objects of this class are thread-safe. *

* * @param Type of key * @param Type of value * @since 0.24 */ public final class Synced extends MapEnvelope { /** * Ctor. * @param list List of entries */ @SafeVarargs public Synced(final Map.Entry... list) { this(new IterableOf<>(list)); } /** * Ctor. * @param map The map to extend * @param list List of entries */ @SafeVarargs public Synced(final Map map, final Map.Entry... list) { this(map, new IterableOf<>(list)); } /** * Ctor. * @param key Func to create key * @param value Func to create value * @param map The map to extend * @param list List of items * @param Type of items in the list * @checkstyle ParameterNumberCheck (5 lines) */ public Synced( final Func key, final Func value, final Map map, final Iterable list ) { this( item -> new MapEntry<>(key.apply(item), value.apply(item)), map, list ); } /** * Ctor. * @param list List of items * @param key Func to create key * @param value Func to create value * @param Type of items in the list */ public Synced( final Iterable list, final Func key, final Func value ) { this(item -> new MapEntry<>(key.apply(item), value.apply(item)), list); } /** * Ctor. * @param entry Func to create entry * @param list List of items * @param Type of items in the list */ @SafeVarargs public Synced( final Func> entry, final Z... list ) { this(new Mapped<>(entry, list)); } /** * Ctor. * @param entry Func to create entry * @param list List of items * @param Type of items in the list */ public Synced( final Func> entry, final Iterable list ) { this(new Mapped<>(entry, list)); } /** * Ctor. * @param entry Func to create entry * @param map The map to extend * @param list List of items * @param Type of items in the list */ public Synced( final Func> entry, final Map map, final Iterable list ) { this(map, new Mapped<>(entry, list)); } /** * Ctor. * @param list Entries for the entries */ public Synced(final Iterable> list) { this(new MapOf<>(list)); } /** * Ctor. * @param map Pre-existing map we want to extend * @param list Entries for the entries */ public Synced( final Map map, final Iterable> list ) { this(new MapOf<>(map, list)); } /** * Ctor. * @param map The map */ @SuppressWarnings("unchecked") public Synced(final Map map) { super((Map) Collections.synchronizedMap(map)); } } cactoos-0.49/src/main/java/org/cactoos/map/package-info.java000066400000000000000000000022771400054650300237300ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ /** * Maps. * * @since 0.14 */ package org.cactoos.map; cactoos-0.49/src/main/java/org/cactoos/package-info.java000066400000000000000000000036701400054650300231510ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ /** * Cactoos. * *

This is a collection of Java primitives designed in a rather * extreme object-objected manner. More details about our design * decisions you can find in this * README. * Feel free to contribute, if you find issues or have a need for * some other primitives.

* * @since 0.1 * @see Project site www.cactoos.org * @see GitHub repository * @todo #1445:30min For consistency sake with Func, let's * - introduce envelopes for Proc, BiProc, BiFunc, Runnable and Callable * - have FuncOf, ProcOf, etc extend their envelope to simplify their code * - apply on other classes that could benefit from it */ package org.cactoos; cactoos-0.49/src/main/java/org/cactoos/proc/000077500000000000000000000000001400054650300207175ustar00rootroot00000000000000cactoos-0.49/src/main/java/org/cactoos/proc/BiProcNoNulls.java000066400000000000000000000042521400054650300242560ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.proc; import org.cactoos.BiProc; /** * BiProc check for no nulls. * @param Type of input * @param Type of input * @since 0.20 */ public final class BiProcNoNulls implements BiProc { /** * The proc. */ private final BiProc origin; /** * Ctor. * @param proc The function */ public BiProcNoNulls(final BiProc proc) { this.origin = proc; } @Override public void exec(final X first, final Y second) throws Exception { if (this.origin == null) { throw new IllegalArgumentException( "NULL instead of a valid function" ); } if (first == null) { throw new IllegalArgumentException( "NULL instead of a valid first argument" ); } if (second == null) { throw new IllegalArgumentException( "NULL instead of a valid second argument" ); } this.origin.exec(first, second); } } cactoos-0.49/src/main/java/org/cactoos/proc/CheckedBiProc.java000066400000000000000000000043501400054650300242110ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.proc; import org.cactoos.BiProc; import org.cactoos.Func; import org.cactoos.scalar.Checked; /** * BiProc that throws exception of specified type. * * @param Type of input * @param Type of input * @param Exception's type * @since 0.32 */ public final class CheckedBiProc implements BiProc { /** * Original BiProc. */ private final BiProc origin; /** * Function that wraps exception of {@link #origin} to the required type. */ private final Func func; /** * Ctor. * @param original Original BiProc * @param fnc Function that wraps exceptions. */ public CheckedBiProc(final BiProc original, final Func fnc) { this.origin = original; this.func = fnc; } @Override public void exec(final X first, final Y second) throws E { new Checked<>( () -> { this.origin.exec(first, second); return true; }, this.func ).value(); } } cactoos-0.49/src/main/java/org/cactoos/proc/CheckedProc.java000066400000000000000000000042121400054650300237330ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.proc; import org.cactoos.Func; import org.cactoos.Proc; import org.cactoos.scalar.Checked; /** * Proc that throws exception of specified type. * * @param Type of input * @param Exception's type * @since 0.32 */ public final class CheckedProc implements Proc { /** * Original proc. */ private final Proc origin; /** * Function that wraps exception of {@link #origin} to the required type. */ private final Func func; /** * Ctor. * @param original Original proc * @param fnc Function that wraps exceptions. */ public CheckedProc(final Proc original, final Func fnc) { this.origin = original; this.func = fnc; } @Override public void exec(final X input) throws E { new Checked<>( () -> { this.origin.exec(input); return true; }, this.func ).value(); } } cactoos-0.49/src/main/java/org/cactoos/proc/ForEach.java000066400000000000000000000044531400054650300230770ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.proc; import org.cactoos.Proc; import org.cactoos.func.FuncOf; import org.cactoos.scalar.And; /** * Executes a {@link org.cactoos.Proc} for each element of an * {@link java.lang.Iterable} * *

* This class can be effectively used to iterate through a collection, just like * {@link java.util.stream.Stream#forEach(java.util.function.Consumer)} works: *

* * {@code * new ForEach( * new ProcOf<>(input -> System.out.printf("\'%s\' ", input)), * ).execute( * new IterableOf<>("Mary", "John", "William", "Napkin") * ); // will print 'Mary' 'John' 'William' 'Napkin' to standard output * } *

* There is no thread-safety guarantee. * * @param The type to iterate over * @since 1.0 */ public final class ForEach implements Proc> { /** * The proc. */ private final Proc proc; /** * Ctor. * * @param proc The proc to execute */ public ForEach(final Proc proc) { this.proc = proc; } @Override public void exec(final Iterable input) throws Exception { new And( new FuncOf<>(this.proc, true), input ).value(); } } cactoos-0.49/src/main/java/org/cactoos/proc/ForEachInThreads.java000066400000000000000000000047031400054650300246770ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.proc; import org.cactoos.Proc; import org.cactoos.func.FuncOf; import org.cactoos.scalar.AndInThreads; /** * Executes a {@link org.cactoos.Proc} in a new Thread for each element of an * {@link java.lang.Iterable} * *

* This class can be effectively used to iterate through a collection, just like * {@link java.util.stream.Stream#forEach(java.util.function.Consumer)} works, * but with no guarantee on the output sorting: *

* * {@code * new ForEachInThreads( * new ProcOf<>(input -> System.out.printf("\'%s\' ", input)), * ).execute( * new IterableOf<>("Mary", "John", "William", "Napkin") * ); // Will print 'Mary' 'John' 'William' 'Napkin' to standard output. * // Order of printing can be random. * } *

* There is no thread-safety guarantee. * * @param The type to iterate over * @since 1.0 */ public final class ForEachInThreads implements Proc> { /** * The proc. */ private final Proc proc; /** * Ctor. * * @param proc The proc to execute */ public ForEachInThreads(final Proc proc) { this.proc = proc; } @Override public void exec(final Iterable input) throws Exception { new AndInThreads( new FuncOf<>(this.proc, true), input ).value(); } } cactoos-0.49/src/main/java/org/cactoos/proc/ForEachWithIndex.java000066400000000000000000000047161400054650300247250ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.proc; import org.cactoos.BiProc; import org.cactoos.Proc; import org.cactoos.scalar.AndWithIndex; /** * Executes a {@link org.cactoos.BiProc} for each element of an * {@link java.lang.Iterable} * *

* This class can be effectively used to iterate through a collection similar to how * {@link java.util.stream.Stream#forEach(java.util.function.Consumer)} works except * this class also passes the index of the current element to the proc: *

* * {@code * new ForEachWithIndex( * new BiProcOf<>((input, index) -> System.out.printf("%d: \'%s\' ", index + 1, input)), * ).execute( * new IterableOf<>("Mary", "John", "William", "Napkin") * ); // will print 1: 'Mary' 2: 'John' 3: 'William' 4: 'Napkin' to standard output * } *

* There is no thread-safety guarantee. * * @param The type to iterate over * @since 1.0 */ public final class ForEachWithIndex implements Proc> { /** * The proc. */ private final BiProc proc; /** * Ctor. * * @param proc The proc to execute */ public ForEachWithIndex(final BiProc proc) { this.proc = proc; } @Override public void exec(final Iterable input) throws Exception { new AndWithIndex( this.proc, input ).value(); } } cactoos-0.49/src/main/java/org/cactoos/proc/IoCheckedBiProc.java000066400000000000000000000036561400054650300245110ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.proc; import java.io.IOException; import org.cactoos.BiProc; /** * BiProc that doesn't throw checked {@link Exception}, but throws * {@link IOException} instead. * *

There is no thread-safety guarantee. * * @param Type of input * @param Type of input * @since 0.22 */ public final class IoCheckedBiProc implements BiProc { /** * Original proc. */ private final BiProc proc; /** * Ctor. * @param prc Encapsulated func */ public IoCheckedBiProc(final BiProc prc) { this.proc = prc; } @Override public void exec(final X first, final Y second) throws IOException { new CheckedBiProc<>( this.proc, IOException::new ).exec(first, second); } } cactoos-0.49/src/main/java/org/cactoos/proc/IoCheckedProc.java000066400000000000000000000035451400054650300242330ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.proc; import java.io.IOException; import org.cactoos.Proc; /** * Proc that doesn't throw checked {@link Exception}, but * throws {@link java.io.IOException} instead. * *

There is no thread-safety guarantee. * * @param Type of input * @since 0.4 */ public final class IoCheckedProc implements Proc { /** * Original proc. */ private final Proc proc; /** * Ctor. * @param prc Encapsulated func */ public IoCheckedProc(final Proc prc) { this.proc = prc; } @Override public void exec(final X input) throws IOException { new CheckedProc<>( this.proc, IOException::new ).exec(input); } } cactoos-0.49/src/main/java/org/cactoos/proc/ProcNoNulls.java000066400000000000000000000036731400054650300240110ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.proc; import org.cactoos.Proc; /** * Proc check for no nulls. * * @param Type of input * @since 0.11 */ public final class ProcNoNulls implements Proc { /** * The procedure. */ private final Proc origin; /** * Ctor. * @param proc The procedure */ public ProcNoNulls(final Proc proc) { this.origin = proc; } @Override public void exec(final X input) throws Exception { if (this.origin == null) { throw new IllegalArgumentException( "NULL instead of a valid procedure" ); } if (input == null) { throw new IllegalArgumentException( "NULL instead of a valid input" ); } this.origin.exec(input); } } cactoos-0.49/src/main/java/org/cactoos/proc/ProcOf.java000066400000000000000000000035561400054650300227630ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.proc; import org.cactoos.Func; import org.cactoos.Proc; /** * Func as Proc. * *

There is no thread-safety guarantee. * * @param Type of input * @since 0.12 */ public final class ProcOf implements Proc { /** * The proc. */ private final Proc proc; /** * Ctor. * @param fnc The proc */ public ProcOf(final Func fnc) { this( input -> { fnc.apply(input); } ); } /** * Ctor. * @param prc The proc */ public ProcOf(final Proc prc) { this.proc = prc; } @Override public void exec(final X input) throws Exception { this.proc.exec(input); } } cactoos-0.49/src/main/java/org/cactoos/proc/RepeatedProc.java000066400000000000000000000040041400054650300241350ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.proc; import org.cactoos.Func; import org.cactoos.Proc; import org.cactoos.func.FuncOf; import org.cactoos.func.Repeated; /** * Proc that runs repeatedly for a number of times. * * @param Type of input * @since 0.49.2 */ public final class RepeatedProc implements Proc { /** * The repeated func. */ private final Func func; /** * Ctor. * *

If {@code count} is equal or less than zero {@link #exec(Object)} * will return an exception.

* * @param prc Proc to repeat. * @param count How many times. */ public RepeatedProc(final Proc prc, final int count) { this.func = new Repeated<>( new FuncOf<>(prc, true), count ); } @Override public void exec(final X input) throws Exception { this.func.apply(input); } } cactoos-0.49/src/main/java/org/cactoos/proc/RunnableOf.java000066400000000000000000000044271400054650300236240ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.proc; import org.cactoos.Proc; import org.cactoos.Scalar; import org.cactoos.scalar.Unchecked; /** * Func as Runnable. * *

There is no thread-safety guarantee. * * @since 0.12 */ public final class RunnableOf implements Runnable { /** * Runnable. */ private final Runnable runnable; /** * Ctor. * @param proc Encapsulated proc * @param ipt Input * @param Type of input * @since 0.32 */ public RunnableOf(final Proc proc, final X ipt) { this( () -> { new UncheckedProc<>(proc).exec(ipt); } ); } /** * Ctor. * @param scalar Encapsulated scalar * @since 0.11 */ public RunnableOf(final Scalar scalar) { this( () -> { new Unchecked<>(scalar).value(); } ); } /** * Ctor. * @param runnable Encapsulated runnable * @since 0.49 */ public RunnableOf(final Runnable runnable) { this.runnable = runnable; } @Override public void run() { this.runnable.run(); } } cactoos-0.49/src/main/java/org/cactoos/proc/UncheckedBiProc.java000066400000000000000000000036311400054650300245550ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.proc; import org.cactoos.BiProc; import org.cactoos.func.BiFuncOf; import org.cactoos.func.UncheckedBiFunc; /** * BiProc that doesn't throw checked {@link Exception}. * *

There is no thread-safety guarantee. * * @param Type of input * @param Type of input * @since 0.22 */ public final class UncheckedBiProc implements BiProc { /** * Original proc. */ private final BiProc proc; /** * Ctor. * @param prc Encapsulated proc */ public UncheckedBiProc(final BiProc prc) { this.proc = prc; } @Override public void exec(final X first, final Y second) { new UncheckedBiFunc<>( new BiFuncOf<>(this.proc, null) ).apply(first, second); } } cactoos-0.49/src/main/java/org/cactoos/proc/UncheckedProc.java000066400000000000000000000036071400054650300243050ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.proc; import java.io.IOException; import java.io.UncheckedIOException; import org.cactoos.Proc; /** * Proc that doesn't throw checked {@link Exception}. * *

There is no thread-safety guarantee. * * @param Type of input * @since 0.2 */ public final class UncheckedProc implements Proc { /** * Original proc. */ private final Proc proc; /** * Ctor. * @param prc Encapsulated func */ public UncheckedProc(final Proc prc) { this.proc = prc; } @Override public void exec(final X input) { try { new IoCheckedProc<>(this.proc).exec(input); } catch (final IOException ex) { throw new UncheckedIOException(ex); } } } cactoos-0.49/src/main/java/org/cactoos/proc/package-info.java000066400000000000000000000023061400054650300241070ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ /** * Procedures. * * @since 0.47 */ package org.cactoos.proc; cactoos-0.49/src/main/java/org/cactoos/scalar/000077500000000000000000000000001400054650300212215ustar00rootroot00000000000000cactoos-0.49/src/main/java/org/cactoos/scalar/And.java000066400000000000000000000105071400054650300225710ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.scalar; import org.cactoos.Func; import org.cactoos.Scalar; import org.cactoos.iterable.IterableOf; import org.cactoos.iterable.Mapped; /** * Logical conjunction. * This class performs short-circuit evaluation in which arguments are * executed only if the preceding argument does not suffice to determine * the value of the expression. * *

This class could be also used for matching multiple boolean * expressions:

* * {@code * new And( * new True(), * new True(), * new True() * ).value(); // the result is true * * new And( * new True(), * new False(), * new True() * ).value(); // the result is false * } * *

This class implements {@link Scalar}, which throws a checked * {@link Exception}. This may not be convenient in many cases. To make * it more convenient and get rid of the checked exception you can * use the {@link Unchecked} decorator. Or you may use * {@link IoChecked} to wrap it in an IOException.

* *

There is no thread-safety guarantee. * * @see Unchecked * @see IoChecked * @since 0.8 */ public final class And implements Scalar { /** * The iterator. */ private final Iterable> origin; /** * Ctor. * @param func Func to map * @param src The iterable * @param Type of items in the iterable */ @SafeVarargs public And(final Func func, final X... src) { this(func, new IterableOf<>(src)); } /** * Ctor. * @param func Func to map * @param src The iterable * @param Type of items in the iterable * @since 0.24 */ public And(final Func func, final Iterable src) { this( new Mapped<>( item -> new ScalarOf<>(() -> func.apply(item)), src ) ); } /** * Ctor. * @param subject The subject * @param conditions Funcs to map * @param Type of items in the iterable * @since 0.34 */ @SafeVarargs public And(final X subject, final Func... conditions) { this(subject, new IterableOf<>(conditions)); } /** * Ctor. * @param subject The subject * @param conditions Funcs to map * @param Type of items in the iterable * @since 0.49 */ public And(final X subject, final Iterable> conditions) { this( new Mapped<>( item -> new ScalarOf<>(() -> item.apply(subject)), conditions ) ); } /** * Ctor. * @param scalar The Scalar. */ @SafeVarargs public And(final Scalar... scalar) { this(new IterableOf<>(scalar)); } /** * Ctor. * @param iterable The iterable. */ public And(final Iterable> iterable) { this.origin = iterable; } @Override public Boolean value() throws Exception { boolean result = true; for (final Scalar item : this.origin) { if (!item.value()) { result = false; break; } } return result; } } cactoos-0.49/src/main/java/org/cactoos/scalar/AndInThreads.java000066400000000000000000000154771400054650300244060ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.scalar; import java.util.Collection; import java.util.LinkedList; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import org.cactoos.Func; import org.cactoos.Proc; import org.cactoos.Scalar; import org.cactoos.func.FuncOf; import org.cactoos.iterable.IterableOf; import org.cactoos.iterable.Mapped; import org.cactoos.text.FormattedText; /** * Logical conjunction, in multiple threads. * *

The usage is same as for {@link And}

* *

This class implements {@link Scalar}, which throws a checked * {@link Exception}. This may not be convenient in many cases. To make * it more convenient and get rid of the checked exception you can * use the {@link Unchecked} decorator. Or you may use * {@link IoChecked} to wrap it in an IOException.

* *

There is no thread-safety guarantee. * * @see Unchecked * @see IoChecked * @since 0.25 */ public final class AndInThreads implements Scalar { /** * The service. */ private final ExecutorService service; /** * The iterator. */ private final Iterable> iterable; /** * Shut down the service when it's done. */ private final boolean shut; /** * Ctor. * @param func Func to map * @param src The iterable * @param Type of items in the iterable */ @SafeVarargs public AndInThreads(final Func func, final X... src) { this(func, new IterableOf<>(src)); } /** * Ctor. * @param func Func to map * @param src The iterable * @param Type of items in the iterable */ public AndInThreads(final Func func, final Iterable src) { this( new Mapped<>( item -> new ScalarOf<>(() -> func.apply(item)), src ) ); } /** * Ctor. * @param src The iterable */ @SafeVarargs public AndInThreads(final Scalar... src) { this(new IterableOf<>(src)); } /** * Ctor. * @param src The iterable */ public AndInThreads(final Iterable> src) { this(Executors.newCachedThreadPool(), src, true); } /** * Ctor. * @param svc Executable service to run thread in * @param proc Proc to map * @param src The iterable * @param Type of items in the iterable */ @SafeVarargs public AndInThreads(final ExecutorService svc, final Proc proc, final X... src) { this(svc, new FuncOf<>(proc, true), src); } /** * Ctor. * @param svc Executable service to run thread in * @param func Func to map * @param src The iterable * @param Type of items in the iterable */ @SafeVarargs public AndInThreads(final ExecutorService svc, final Func func, final X... src) { this(svc, func, new IterableOf<>(src)); } /** * Ctor. * @param svc Executable service to run thread in * @param proc Proc to use * @param src The iterable * @param Type of items in the iterable */ public AndInThreads(final ExecutorService svc, final Proc proc, final Iterable src) { this(svc, new FuncOf<>(proc, true), src); } /** * Ctor. * @param svc Executable service to run thread in * @param func Func to map * @param src The iterable * @param Type of items in the iterable */ public AndInThreads(final ExecutorService svc, final Func func, final Iterable src) { this( svc, new Mapped<>( item -> new ScalarOf<>(() -> func.apply(item)), src ) ); } /** * Ctor. * @param svc Executable service to run thread in * @param src The iterable */ @SafeVarargs public AndInThreads(final ExecutorService svc, final Scalar... src) { this(svc, new IterableOf<>(src)); } /** * Ctor. * @param svc Executable service to run thread in * @param src The iterable */ public AndInThreads(final ExecutorService svc, final Iterable> src) { this(svc, src, false); } /** * Ctor. * @param svc Executable service to run thread in * @param src The iterable * @param sht Shut it down */ private AndInThreads(final ExecutorService svc, final Iterable> src, final boolean sht) { this.service = svc; this.iterable = src; this.shut = sht; } @Override public Boolean value() throws Exception { final Collection> futures = new LinkedList<>(); for (final Scalar item : this.iterable) { futures.add(this.service.submit(item::value)); } final boolean result = new And( Future::get, futures ).value(); if (this.shut) { this.service.shutdown(); try { if (!this.service.awaitTermination(1L, TimeUnit.MINUTES)) { throw new IllegalStateException( new FormattedText( "Can't terminate the service, result=%b", result ).asString() ); } } catch (final InterruptedException ex) { Thread.currentThread().interrupt(); throw new IllegalStateException(ex); } } return result; } } cactoos-0.49/src/main/java/org/cactoos/scalar/AndWithIndex.java000066400000000000000000000111021400054650300244050ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.scalar; import org.cactoos.BiFunc; import org.cactoos.BiProc; import org.cactoos.Func; import org.cactoos.Proc; import org.cactoos.Scalar; import org.cactoos.func.BiFuncOf; import org.cactoos.func.FuncOf; import org.cactoos.iterable.IterableOf; import org.cactoos.iterable.Mapped; /** * Logical conjunction, with index. * *

This class can be effectively used to iterate through * a collection, just like * {@link java.util.stream.Stream#forEach(java.util.function.Consumer)} * works, but with an index provided for each item:

* *
{@code
 * new UncheckedScalar<>(
 *     new AndWithIndex(
 *         new IterableOf<>("Mary", "John", "William", "Napkin"),
 *         new BiFuncOf<>((text, index) ->
 *             System.out.printf("| idx #%d: name: %s ", index, text), true)
 *     )
 * ).value();
 * // will print "| idx #0: name: Mary | idx #1: name: John |
 * // idx #2: name: William | idx #3: name: Napkin " to console
 * }
* *

This class implements {@link Scalar}, which throws a checked * {@link Exception}. This may not be convenient in many cases. To make * it more convenient and get rid of the checked exception you can * use the {@link Unchecked} decorator. Or you may use * {@link IoChecked} to wrap it in an IOException.

* *

There is no thread-safety guarantee. * * @since 0.20 */ public final class AndWithIndex implements Scalar { /** * The iterator. */ private final Iterable> iterable; /** * Ctor. * @param proc Proc to map * @param src The iterable * @param Type of items in the iterable */ @SafeVarargs public AndWithIndex(final Proc proc, final X... src) { this(new BiFuncOf<>(proc, true), src); } /** * Ctor. * @param func Func to map * @param src The iterable * @param Type of items in the iterable */ @SafeVarargs public AndWithIndex(final BiFunc func, final X... src) { this(func, new IterableOf<>(src)); } /** * Ctor. * @param proc Proc to use * @param src The iterable * @param Type of items in the iterable * @since 0.24 */ public AndWithIndex(final BiProc proc, final Iterable src) { this(new BiFuncOf<>(proc, true), src); } /** * Ctor. * @param func Func to map * @param src The iterable * @param Type of items in the iterable * @since 0.24 */ public AndWithIndex(final BiFunc func, final Iterable src) { this( new Mapped<>( item -> new FuncOf<>(input -> func.apply(item, input)), src ) ); } /** * Ctor. * @param src The iterable */ @SafeVarargs public AndWithIndex(final Func... src) { this(new IterableOf<>(src)); } /** * Ctor. * @param src The iterable */ public AndWithIndex(final Iterable> src) { this.iterable = src; } @Override public Boolean value() throws Exception { boolean result = true; int pos = 0; for (final Func item : this.iterable) { if (!item.apply(pos)) { result = false; break; } ++pos; } return result; } } cactoos-0.49/src/main/java/org/cactoos/scalar/AvgOf.java000066400000000000000000000102351400054650300230670ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.scalar; import java.math.BigDecimal; import java.math.MathContext; import java.util.List; import org.cactoos.Scalar; import org.cactoos.iterable.IterableOf; import org.cactoos.iterable.Mapped; import org.cactoos.list.ListOf; /** * Average of numbers. * *

Here is how you can use it to find the mathematical average of numbers: *

* *
 * int avg = new AvgOf(1, 2, 3, 4).intValue();
 * long avg = new AvgOf(1L, 2L, 3L).longValue();
 * int avg = new AvgOf(numbers.toArray(new Integer[numbers.size()])).intValue();
 * 
* *

This class implements {@link Scalar}, which throws a checked * {@link Exception}. This may not be convenient in many cases. To make * it more convenient and get rid of the checked exception you can * use the {@link Unchecked} decorator. Or you may use * {@link IoChecked} to wrap it in an IOException.

* *

There is no thread-safety guarantee. * * @since 0.24 */ public final class AvgOf extends NumberEnvelope { /** * Serialization marker. */ private static final long serialVersionUID = 3624862553221697558L; /** * Ctor. * @param src Numbers */ public AvgOf(final Integer... src) { this( new Mapped<>( number -> () -> number, new IterableOf<>(src) ) ); } /** * Ctor. * @param src Numbers */ public AvgOf(final Long... src) { this( new Mapped<>( number -> () -> number, new IterableOf<>(src) ) ); } /** * Ctor. * @param src Numbers */ public AvgOf(final Double... src) { this( new Mapped<>( number -> () -> number, new IterableOf<>(src) ) ); } /** * Ctor. * @param src Numbers */ public AvgOf(final Float... src) { this( new Mapped<>( number -> () -> number, new IterableOf<>(src) ) ); } /** * Ctor. * @param src Numbers */ @SafeVarargs public AvgOf(final Scalar... src) { this(new IterableOf<>(src)); } /** * Ctor. * @param src The iterable * @checkstyle ExecutableStatementCountCheck (150 lines) */ public AvgOf(final Iterable> src) { super( new Ternary<>( new ScalarOf<>(() -> new ListOf<>(new Mapped(Scalar::value, src))), (List list) -> !list.isEmpty(), list -> new Folded( BigDecimal.ZERO, (sum, value) -> sum.add(value, MathContext.DECIMAL128), new Mapped<>(s -> new BigDecimal(s.doubleValue()), list) ).value().divide( BigDecimal.valueOf(list.size()), MathContext.DECIMAL128 ).doubleValue(), list -> 0.0 ) ); } } cactoos-0.49/src/main/java/org/cactoos/scalar/Binary.java000066400000000000000000000050421400054650300233110ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.scalar; import org.cactoos.Scalar; /** * Binary operation. * *

There is no thread-safety guarantee. * *

This class implements {@link Scalar}, which throws a checked * {@link Exception}. This may not be convenient in many cases. To make * it more convenient and get rid of the checked exception you can * use the {@link Unchecked} decorator. Or you may use * {@link IoChecked} to wrap it in an IOException.

* *
{@code
 * final AtomicInteger counter = new AtomicInteger();
 * new Binary(
 *     () -> true,
 *     () -> counter.incrementAndGet
 * ).value() // will be equal true
 * }
* * @since 1.0 */ public final class Binary implements Scalar { /** * Scalar for condition. */ private final Scalar condition; /** * Proc executed when condition is true. */ private final Runnable consequent; /** * Ctor. * * @param condition Boolean function * @param consequent Proc executed when condition is true */ public Binary( final Scalar condition, final Runnable consequent ) { this.condition = condition; this.consequent = consequent; } @Override public Boolean value() throws Exception { final Boolean result = this.condition.value(); if (result) { this.consequent.run(); } return result; } } cactoos-0.49/src/main/java/org/cactoos/scalar/BoolOf.java000066400000000000000000000042671400054650300232550ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.scalar; import org.cactoos.Scalar; import org.cactoos.Text; import org.cactoos.text.TextOf; /** * Text as {@link Boolean}. * *

There is no thread-safety guarantee. * *

This class implements {@link Scalar}, which throws a checked * {@link Exception}. This may not be convenient in many cases. To make * it more convenient and get rid of the checked exception you can * use the {@link Unchecked} decorator. Or you may use * {@link IoChecked} to wrap it in an IOException.

* * @since 0.2 */ public final class BoolOf implements Scalar { /** * Source text. */ private final Text origin; /** * Ctor. * * @param txt True or false string */ public BoolOf(final String txt) { this(new TextOf(txt)); } /** * Ctor. * * @param text True or false text */ public BoolOf(final Text text) { this.origin = text; } @Override public Boolean value() throws Exception { return Boolean.valueOf(this.origin.asString()); } } cactoos-0.49/src/main/java/org/cactoos/scalar/CallableOf.java000066400000000000000000000037331400054650300240560ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.scalar; import java.util.concurrent.Callable; import org.cactoos.Scalar; /** * Func as {@link Callable}. * *

You may want to use this decorator where * {@link Callable} is required, but you just have a function:

* *
 Callable<String> callable = new CallableOf<>(
 *   i -> "Hello, world!"
 * );
 * 
* *

There is no thread-safety guarantee. * * @param Type of output * @since 0.12 */ public final class CallableOf implements Callable { /** * Original callable. */ private final Scalar scalar; /** * Ctor. * @param slr Encapsulated scalar * @since 0.41 */ public CallableOf(final Scalar slr) { this.scalar = slr; } @Override public T call() throws Exception { return this.scalar.value(); } } cactoos-0.49/src/main/java/org/cactoos/scalar/Checked.java000066400000000000000000000073721400054650300234230ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.scalar; import org.cactoos.Func; import org.cactoos.Scalar; import org.cactoos.func.UncheckedFunc; import org.cactoos.text.FormattedText; import org.cactoos.text.UncheckedText; /** * Scalar that wraps an original checked exception thrown by the origin using * the given wrapping function. * *

There is no thread-safety guarantee. * * @param Type of result * @param Type of exception * @since 0.30 */ public final class Checked implements Scalar { /** * Function that wraps exception. */ private final Func func; /** * Original scalar. */ private final Scalar origin; /** * Ctor. * @param scalar Encapsulated scalar * @param fnc Func that wraps exception */ public Checked(final Scalar scalar, final Func fnc) { this.func = fnc; this.origin = scalar; } @Override @SuppressWarnings ( { "PMD.AvoidCatchingGenericException", "PMD.AvoidRethrowingException", "PMD.PreserveStackTrace" } ) public T value() throws E { try { return this.origin.value(); // @checkstyle IllegalCatchCheck (1 line) } catch (final RuntimeException ex) { throw ex; } catch (final InterruptedException ex) { Thread.currentThread().interrupt(); throw this.wrappedException(ex); // @checkstyle IllegalCatchCheck (1 line) } catch (final Exception ex) { throw this.wrappedException(ex); } } /** * Wraps exception. * Skips unnecessary wrapping of exceptions of the same type. * Allows wrapping of exceptions of the same type if the error message * has been changed. * * @param exp Exception * @return E Wrapped exception */ @SuppressWarnings("unchecked") private E wrappedException(final Exception exp) { E wrapped = new UncheckedFunc<>(this.func).apply(exp); final int level = new InheritanceLevel( exp.getClass(), wrapped.getClass() ).value(); final String message = wrapped.getMessage() .replaceFirst( new UncheckedText( new FormattedText( "%s: ", exp.getClass().getName() ) ).asString(), "" ); if (level >= 0 && message.equals(exp.getMessage())) { wrapped = (E) exp; } return wrapped; } } cactoos-0.49/src/main/java/org/cactoos/scalar/Constant.java000066400000000000000000000043451400054650300236630ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.scalar; import org.cactoos.Scalar; /** * Constant value. * *

This {@link Scalar} represents a constant value which never changes.

* *

Contrary to {@link Sticky} this constant is always * pre-computed.

* *

This class implements {@link Scalar}, which throws a checked * {@link Exception}. Despite that this class does NOT throw a checked * exception as it only returns a pre-computed value.

* *

Example:

*
{@code
 *     final Scalar constant = new Constant<>("Value");
 *     System.out.print("Constant is always the same: ");
 *     System.out.println(constant.value() == constant.value());
 * }
* *

This class is thread-safe.

* * @param Type of result * @see Sticky * @since 0.30 */ public final class Constant implements Scalar { /** * Pre-computed value. */ private final T val; /** * Ctor. * @param value The pre-computed constant. */ public Constant(final T value) { this.val = value; } @Override public T value() { return this.val; } } cactoos-0.49/src/main/java/org/cactoos/scalar/DivisionOf.java000066400000000000000000000042271400054650300241420ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.scalar; import java.math.BigDecimal; import java.math.MathContext; import org.cactoos.Scalar; /** * Division result of two numbers. * *

This class implements {@link Scalar}, which throws a checked * {@link Exception}. This may not be convenient in many cases. To make * it more convenient and get rid of the checked exception you can * use the {@link Unchecked} decorator. Or you may use * {@link IoChecked} to wrap it in an IOException.

* *

There is no thread-safety guarantee. * * @since 0.49.2 */ public final class DivisionOf extends NumberEnvelope { private static final long serialVersionUID = -5276601257067346442L; /** * Ctor. * @param dividend The dividend * @param divisor The divisor */ public DivisionOf(final Number dividend, final Number divisor) { super(() -> BigDecimal.valueOf(dividend.doubleValue()).divide( BigDecimal.valueOf(divisor.doubleValue()), MathContext.DECIMAL128 ).doubleValue() ); } } cactoos-0.49/src/main/java/org/cactoos/scalar/Equality.java000066400000000000000000000047641400054650300236740ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.scalar; import org.cactoos.Bytes; import org.cactoos.Scalar; /** * Equality. * * Returns: * the value {@code 0} if {@code x == y}; * the value {@code -1} if {@code x < y}; * the value {@code 1} if {@code x > y} * *

There is no thread-safety guarantee. * * @param Type of input * @since 0.31 */ public final class Equality implements Scalar { /** * Left. */ private final T left; /** * Right. */ private final T right; /** * Ctor. * @param lft Left * @param rght Right */ public Equality(final T lft, final T rght) { this.left = lft; this.right = rght; } @Override public Integer value() throws Exception { final byte[] lft = this.left.asBytes(); final byte[] rght = this.right.asBytes(); return new Ternary<>( () -> lft.length == rght.length, () -> { int result = 0; for (int idx = rght.length - 1; idx >= 0; --idx) { result = lft[idx] - rght[idx]; if (result != 0) { break; } } return Integer.signum(result); }, () -> Integer.signum(lft.length - rght.length) ).value(); } } cactoos-0.49/src/main/java/org/cactoos/scalar/Equals.java000066400000000000000000000043721400054650300233240ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.scalar; import org.cactoos.Scalar; /** * Equals. * *

There is no thread-safety guarantee. * *

This class implements {@link Scalar}, which throws a checked * {@link Exception}. This may not be convenient in many cases. To make * it more convenient and get rid of the checked exception you can * use the {@link Unchecked} decorator. Or you may use * {@link IoChecked} to wrap it in an IOException.

* * @param Type of object to compare * @since 0.9 */ public final class Equals> implements Scalar { /** * The first scalar. */ private final Scalar first; /** * The second scalar. */ private final Scalar second; /** * Ctor. * @param source The first scalar to compare. * @param compared The second scalar to compare. */ public Equals(final Scalar source, final Scalar compared) { this.first = source; this.second = compared; } @Override public Boolean value() throws Exception { return this.first.value().compareTo(this.second.value()) == 0; } } cactoos-0.49/src/main/java/org/cactoos/scalar/EqualsNullable.java000066400000000000000000000060211400054650300247740ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.scalar; import org.cactoos.Scalar; /** * Checks 2 objects for equality. * Null values are accepted. *

There is no thread-safety guarantee. * @since 1.0 */ public final class EqualsNullable implements Scalar { /** * The first object for comparison. */ private final Scalar first; /** * The second object for comparison. */ private final Scalar second; /** * Accepts 2 objects to compare. * @param first Object to compare * @param second Object to compare with */ public EqualsNullable(final Object first, final Object second) { this(() -> first, () -> second); } /** * Accepts scalar to get value from and object to compare with. * @param first Scalar to get value to compare * @param second Object to compare with */ public EqualsNullable(final Scalar first, final Object second) { this(first, () -> second); } /** * Accepts object to compare with and scalar to get value from. * @param first Object to compare * @param second Scalar to get value to compare */ public EqualsNullable(final Object first, final Scalar second) { this(() -> first, second); } /** * Accepts 2 scalars to get get values from. * @param first Scalar to get value to compare * @param second Scalar to get value to compare with */ public EqualsNullable(final Scalar first, final Scalar second) { this.first = first; this.second = second; } @Override @SuppressWarnings("PMD.CompareObjectsWithEquals") public Boolean value() throws Exception { final Object source = this.first.value(); final Object compared = this.second.value(); return source == compared || source != null && source.equals(compared); } } cactoos-0.49/src/main/java/org/cactoos/scalar/False.java000066400000000000000000000026121400054650300231170ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.scalar; import org.cactoos.Scalar; /** * Logical false. * *

This class is thread-safe. * * @since 0.7 */ public final class False implements Scalar { @Override public Boolean value() { return false; } } cactoos-0.49/src/main/java/org/cactoos/scalar/FirstOf.java000066400000000000000000000060171400054650300234440ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.scalar; import org.cactoos.Func; import org.cactoos.Scalar; import org.cactoos.func.FuncOf; import org.cactoos.iterable.Filtered; /** * Find first element in a list that satisfies specified condition. * *

There is no thread-safety guarantee. * * @param Type of result * @since 0.32 */ public final class FirstOf implements Scalar { /** * Condition for getting the element. */ private final Func condition; /** * Source iterable. */ private final Iterable source; /** * Fallback used if no value matches. */ private final Scalar fallback; /** * Constructor with default condition (always `true`) and plain fallback. * @param src Source iterable * @param fbck Fallback used if no value matches */ public FirstOf(final Iterable src, final T fbck) { this( new FuncOf<>(new True()), src, () -> fbck ); } /** * Constructor with default condition (always `true`). * @param src Source iterable * @param fbck Fallback used if no value matches */ public FirstOf(final Iterable src, final Scalar fbck) { this( new FuncOf<>(new True()), src, fbck ); } /** * Constructor. * @param cond Condition for getting the element * @param src Source iterable * @param fbck Fallback used if no value matches */ public FirstOf(final Func cond, final Iterable src, final Scalar fbck) { this.condition = cond; this.source = src; this.fallback = fbck; } @Override public T value() throws Exception { return new ItemAt<>( 0, new FuncOf<>(this.fallback), new Filtered<>(this.condition, this.source) ).value(); } } cactoos-0.49/src/main/java/org/cactoos/scalar/Flattened.java000066400000000000000000000030641400054650300237750ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.scalar; import org.cactoos.Scalar; /** * {@link Scalar} from {@link Scalar} of {@link Scalar}. * *

There is no thread-safety guarantee. * * @param Element type * @since 0.48 */ public final class Flattened extends ScalarEnvelope { /** * Ctor. * @param sclr The func */ public Flattened(final Scalar> sclr) { super(() -> sclr.value().value()); } } cactoos-0.49/src/main/java/org/cactoos/scalar/Folded.java000066400000000000000000000046711400054650300232710ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.scalar; import org.cactoos.BiFunc; import org.cactoos.Scalar; import org.cactoos.iterable.IterableOf; /** * Iterable, which elements are "folded" through the func. * * @param Type of input and output * @param Type of element * @since 0.30 */ public final class Folded implements Scalar { /** * Original iterable. */ private final Iterable iterable; /** * Input. */ private final X input; /** * Func. */ private final BiFunc func; /** * Ctor. * @param ipt Input * @param fnc Func original * @param list List of items */ public Folded(final X ipt, final BiFunc fnc, final Iterable list) { this.iterable = list; this.input = ipt; this.func = fnc; } /** * Ctor. * @param ipt Input * @param fnc Func original * @param list Array of items */ @SafeVarargs public Folded(final X ipt, final BiFunc fnc, final T... list) { this(ipt, fnc, new IterableOf<>(list)); } @Override public X value() throws Exception { X memo = this.input; for (final T item : this.iterable) { memo = this.func.apply(memo, item); } return memo; } } cactoos-0.49/src/main/java/org/cactoos/scalar/HashCode.java000066400000000000000000000073721400054650300235530ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.scalar; import java.util.Objects; import org.cactoos.Scalar; import org.cactoos.iterable.IterableOf; /** * Object HashCode. * * Replace this code: * {@code * public int hashCode() { * int hash = 5; * hash = 67 * hash + Objects.hashCode(this.attr1); * hash = 67 * hash + Objects.hashCode(this.attr2); * hash = 67 * hash + Objects.hashCode(this.attr3); * // ... more attributes * return hash; * } * } * * With this: * {@code * public int hashCode() { * return new HashCode( * 5, 67, * this.attr1, this.attr2, this.attr3, ... * ).value(); * } * } * *

There is no thread-safety guarantee. * * @since 1.0 */ public final class HashCode implements Scalar { /** * Hash code. */ private final Unchecked origin; /** * Ctor. * *

The {@code initial} and {@code multiplier} values are arbitrarily * set to 17 and 31 respectively. * @param attributes The object's attributes * @checkstyle MagicNumber (3 lines) */ public HashCode(final Object... attributes) { this(new IterableOf<>(attributes)); } /** * Ctor. * *

The {@code initial} and {@code multiplier} values are arbitrarily * set to 17 and 31 respectively. * @param attributes The object's attributes * @checkstyle MagicNumber (3 lines) */ public HashCode(final Iterable attributes) { this(17, 31, attributes); } /** * Ctor. * @param initial Initial value (non-zero recommended) * @param multiplier Step multiplier (odd prime recommended) * @param attributes The object's attributes */ public HashCode( final int initial, final int multiplier, final Object... attributes ) { this(initial, multiplier, new IterableOf<>(attributes)); } /** * Ctor. * @param initial Initial value (non-zero recommended) * @param multiplier Step multiplier (odd prime recommended) * @param attributes The object's attributes */ public HashCode( final int initial, final int multiplier, final Iterable attributes ) { this( new Folded<>( initial, (hash, attr) -> hash * multiplier + Objects.hashCode(attr), attributes ) ); } /** * Ctor. * @param hash Hashcode */ private HashCode(final Scalar hash) { this.origin = new Unchecked<>(hash); } @Override public Integer value() { return this.origin.value(); } } cactoos-0.49/src/main/java/org/cactoos/scalar/HighestOf.java000066400000000000000000000063601400054650300237510ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.scalar; import org.cactoos.Scalar; import org.cactoos.iterable.IterableOf; import org.cactoos.iterable.Mapped; /** * Find the highest item. * *

Here is how you can use it to * find highest of {@link Comparable} items:

* *
 * final String highest = new HighestOf<String>(
 *         () -> "Banana", () -> "Apple", () -> "Orange"
 *     ).value();
 * // -> highest == "Orange"
 *
 * final Character highestChar = new HighestOf<>('B', 'U', 'G').value();
 * // -> highestChar == 'U'
 * 
* *

This class implements {@link Scalar}, which throws a checked * {@link Exception}. This may not be convenient in many cases. To make * it more convenient and get rid of the checked exception you can * use the {@link Unchecked} decorator. Or you may use * {@link IoChecked} to wrap it in an IOException.

* *

There is no thread-safety guarantee. * * @param Scalar type * @see Unchecked * @see IoChecked * @since 0.29 */ public final class HighestOf> implements Scalar { /** * Result. */ private final Scalar result; /** * Ctor. * @param items The comparable items */ @SafeVarargs public HighestOf(final T... items) { this( new Mapped<>( item -> () -> item, items ) ); } /** * Ctor. * @param scalars The scalars */ @SafeVarargs public HighestOf(final Scalar... scalars) { this(new IterableOf<>(scalars)); } /** * Ctor. * @param iterable The items */ public HighestOf(final Iterable> iterable) { this.result = new Reduced<>( (first, second) -> { final T value; if (first.compareTo(second) > 0) { value = first; } else { value = second; } return value; }, iterable ); } @Override public T value() throws Exception { return this.result.value(); } } cactoos-0.49/src/main/java/org/cactoos/scalar/InheritanceLevel.java000066400000000000000000000056771400054650300253240ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.scalar; import org.cactoos.Scalar; /** * The number of superclasses between base and derived class. * *

This class is thread safe. * *

Result interpretation: *

    *
  • {@link Integer#MIN_VALUE} -> classes are not related. * (ex. matching FileNotFoundException with RuntimeException); *
  • 0 -> classes are identical. (ex. matching IOException with * IOException); *
  • 1 -> single level inheritance. (ex. matching * FileNotFoundException with IOException); *
  • 2 -> two inheritance levels. (ex. matching * FileNotFoundException with Exception). *
* * @since 0.30 */ public final class InheritanceLevel implements Scalar { /** * Base class. */ private final Class base; /** * Derived class. */ private final Class derived; /** * Ctor. * @param cderived Derived class * @param cbase Base class */ public InheritanceLevel(final Class cderived, final Class cbase) { this.derived = cderived; this.base = cbase; } @Override public Integer value() { final int level; if (this.base.equals(this.derived)) { level = 0; } else { level = this.calculateLevel(); } return level; } /** * Calculates inheritance level. * @return Integer Level */ private int calculateLevel() { int level = Integer.MIN_VALUE; Class sclass = this.derived.getSuperclass(); int idx = 0; while (!sclass.equals(Object.class)) { idx += 1; if (sclass.equals(this.base)) { level = idx; break; } sclass = sclass.getSuperclass(); } return level; } } cactoos-0.49/src/main/java/org/cactoos/scalar/IoChecked.java000066400000000000000000000041341400054650300237040ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.scalar; import java.io.IOException; import org.cactoos.Scalar; /** * Scalar that doesn't throw {@link Exception}, but throws * {@link IOException} instead. * *

There is no thread-safety guarantee. * *

This class implements {@link Scalar}, which throws a checked * {@link IOException}. This may not be convenient in many cases. To make * it more convenient and get rid of the checked exception you can * use the {@link Unchecked} decorator.

* * @param Type of result * @since 0.4 */ public final class IoChecked implements Scalar { /** * Original scalar. */ private final Scalar origin; /** * Ctor. * @param scalar Encapsulated scalar */ public IoChecked(final Scalar scalar) { this.origin = scalar; } @Override public T value() throws IOException { return new Checked<>( this.origin, IOException::new ).value(); } } cactoos-0.49/src/main/java/org/cactoos/scalar/ItemAt.java000066400000000000000000000074201400054650300232520ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.scalar; import java.io.IOException; import java.util.Iterator; import org.cactoos.Func; import org.cactoos.Scalar; import org.cactoos.func.FuncOf; import org.cactoos.text.FormattedText; /** * Element from position in {@link Iterable} * or fallback value if iterable doesn't have this position. * *

There is no thread-safety guarantee. * * @param Scalar type * @since 0.7 */ public final class ItemAt implements Scalar { /** * {@link Sticky} that holds the value of the {@link Scalar} * at the position specified in the constructor. */ private final Scalar saved; /** * Ctor. * * @param position Position * @param iterable Iterable */ public ItemAt(final int position, final Iterable iterable) { this( position, itr -> { throw new IOException( new FormattedText( "The iterable doesn't have the position #%d", position ).asString() ); }, iterable ); } /** * Ctor. * * @param position Position * @param fallback Fallback value * @param iterable Iterable */ public ItemAt( final int position, final T fallback, final Iterable iterable ) { this(position, new FuncOf<>(new Constant<>(fallback)), iterable); } /** * Ctor. * * @param position Position * @param fallback Fallback value * @param iterable Iterable */ public ItemAt( final int position, final Func, T> fallback, final Iterable iterable ) { this.saved = new Sticky( () -> { final T ret; if (position < 0) { throw new IOException( new FormattedText( "The position must be non-negative: %d", position ).asString() ); } final Iterator src = iterable.iterator(); int cur; for (cur = 0; cur < position && src.hasNext(); ++cur) { src.next(); } if (cur == position && src.hasNext()) { ret = src.next(); } else { ret = fallback.apply(() -> src); } return ret; } ); } @Override public T value() throws Exception { return this.saved.value(); } } cactoos-0.49/src/main/java/org/cactoos/scalar/LengthOf.java000066400000000000000000000067411400054650300236020ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.scalar; import java.io.InputStream; import java.util.Iterator; import org.cactoos.Input; import org.cactoos.Scalar; import org.cactoos.Text; import org.cactoos.io.InputOf; /** * Length. * *

* There is no thread-safety guarantee. * * @since 0.1 */ public final class LengthOf extends NumberEnvelope { /** * Serialization marker. */ private static final long serialVersionUID = -7351954368806143451L; /** * Ctor. * @param items The array * @param The type of items */ public LengthOf(final Iterable items) { this(() -> { final Iterator iterator = items.iterator(); int size = 0; while (iterator.hasNext()) { iterator.next(); ++size; } return (double) size; }); } /** * Ctor. * Character-length of Text. * * @param text The input */ public LengthOf(final Text text) { this(() -> (double) text.asString().length()); } /** * Ctor. * @param input The input */ public LengthOf(final Input input) { // @checkstyle MagicNumber (1 line) this(input, 16 << 10); } /** * Ctor. * @param input The input * @param max Buffer size */ @SuppressWarnings( { "PMD.CallSuperInConstructor", "PMD.ConstructorOnlyInitializesOrCallOtherConstructors" } ) public LengthOf(final Input input, final int max) { this(() -> { if (max == 0) { throw new IllegalArgumentException( "Cannot use a buffer limited to zero size" ); } try (InputStream stream = input.stream()) { final byte[] buf = new byte[max]; long length = 0L; while (true) { final int len = stream.read(buf); if (len > 0) { length += (long) len; } if (len < 0) { break; } } return (double) length; } }); } /** * Ctor. * @param dnm Double number. */ private LengthOf(final Scalar dnm) { super(dnm); } } cactoos-0.49/src/main/java/org/cactoos/scalar/LowestOf.java000066400000000000000000000063431400054650300236340ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.scalar; import org.cactoos.Scalar; import org.cactoos.iterable.IterableOf; import org.cactoos.iterable.Mapped; /** * Find the lowest item. * *

Here is how you can use it to * find lowest of {@link Comparable} items:

* *
 * final String lowest = new LowestOf<String>(
 *         () -> "Banana", () -> "Apple", () -> "Orange"
 *     ).value();
 * // -> lowest == "Apple"
 *
 * final Character lowestChar = new LowestOf<>('B', 'U', 'G').value();
 * // -> lowestChar == 'B'
 * 
* *

This class implements {@link Scalar}, which throws a checked * {@link Exception}. This may not be convenient in many cases. To make * it more convenient and get rid of the checked exception you can * use the {@link Unchecked} decorator. Or you may use * {@link IoChecked} to wrap it in an IOException.

* *

There is no thread-safety guarantee. * * @param Scalar type * @see Unchecked * @see IoChecked * @since 0.29 */ public final class LowestOf> implements Scalar { /** * Result. */ private final Scalar result; /** * Ctor. * @param items The comparable items */ @SafeVarargs public LowestOf(final T... items) { this( new Mapped<>( item -> () -> item, items ) ); } /** * Ctor. * @param scalars The scalars */ @SafeVarargs public LowestOf(final Scalar... scalars) { this(new IterableOf<>(scalars)); } /** * Ctor. * @param iterable The items */ public LowestOf(final Iterable> iterable) { this.result = new Reduced<>( (first, second) -> { final T value; if (first.compareTo(second) < 0) { value = first; } else { value = second; } return value; }, iterable ); } @Override public T value() throws Exception { return this.result.value(); } } cactoos-0.49/src/main/java/org/cactoos/scalar/Mapped.java000066400000000000000000000040411400054650300232710ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.scalar; import java.io.IOException; import org.cactoos.Func; import org.cactoos.Scalar; /** * {@link Scalar} that apply a {@link Func} to the result of another * {@link Scalar}. * *

* There is no thread-safety guarantee. * *

* This class implements {@link Scalar}, which throws a checked * {@link IOException}. This may not be convenient in many cases. To make it * more convenient and get rid of the checked exception you can use the * {@link Unchecked} decorator. *

* * @param Type of result * @since 1.0.0 */ public final class Mapped extends ScalarEnvelope { /** * Ctor. * @param func Map function. * @param scalar Scalar. * @param Type of input. */ public Mapped( final Func func, final Scalar scalar ) { super(() -> func.apply(scalar.value())); } } cactoos-0.49/src/main/java/org/cactoos/scalar/MaxOf.java000066400000000000000000000067051400054650300231060ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.scalar; import org.cactoos.Scalar; import org.cactoos.iterable.IterableOf; import org.cactoos.iterable.Mapped; /** * Find the greater among items. * *

* Here is how you can use it to find the max of a set of numbers: *

* *
 * int max = new MaxOf(1, 2, 3, 4).intValue();
 * long max = new MaxOf(1L, 2L, 3L).longValue();
 * int max = new MaxOf(numbers.toArray(new Integer[numbers.size()])).intValue();
 * 
* *

* This class implements {@link Scalar}, which throws a checked * {@link Exception}. This may not be convenient in many cases. To make it more * convenient and get rid of the checked exception you can use the * {@link Unchecked} decorator. Or you may use {@link IoChecked} to wrap it in * an IOException. *

* *

* There is no thread-safety guarantee. * @see Unchecked * @see IoChecked * @since 0.24 */ public final class MaxOf extends NumberEnvelope { /** * Serialization marker. */ private static final long serialVersionUID = -6057839494957475355L; /** * Ctor. * @param src Numbers */ public MaxOf(final Integer... src) { this(new IterableOf<>(src)); } /** * Ctor. * @param src Numbers */ public MaxOf(final Long... src) { this(new IterableOf<>(src)); } /** * Ctor. * @param src Numbers */ public MaxOf(final Double... src) { this(new IterableOf<>(src)); } /** * Ctor. * @param src Numbers */ public MaxOf(final Float... src) { this(new IterableOf<>(src)); } /** * Ctor. * @param src The iterable */ public MaxOf(final Iterable src) { super( new Folded<>( Long.MIN_VALUE, Math::max, new Mapped<>(Number::longValue, src) ), new Folded<>( Integer.MIN_VALUE, Math::max, new Mapped<>(Number::intValue, src) ), new Folded<>( -Float.MAX_VALUE, Math::max, new Mapped<>(Number::floatValue, src) ), new Folded<>( -Double.MAX_VALUE, Math::max, new Mapped<>(Number::doubleValue, src) ) ); } } cactoos-0.49/src/main/java/org/cactoos/scalar/MinOf.java000066400000000000000000000066411400054650300231030ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.scalar; import org.cactoos.Scalar; import org.cactoos.iterable.IterableOf; import org.cactoos.iterable.Mapped; /** * Find the smaller among items. * *

* Here is how you can use it to find the min of a set of numbers: *

* *
 * int min = new MinOf(1, 2, 3, 4).intValue();
 * long min = new MinOf(1L, 2L, 3L).longValue();
 * int min = new MinOf(numbers.toArray(new Integer[numbers.size()])).intValue();
 * 
* *

* There is no thread-safety guarantee. * *

* This class implements {@link Scalar}, which throws a checked * {@link Exception}. This may not be convenient in many cases. To make it more * convenient and get rid of the checked exception you can use the * {@link Unchecked} decorator. Or you may use {@link IoChecked} to wrap it in * an IOException. *

* * @since 0.24 */ public final class MinOf extends NumberEnvelope { /** * Serialization marker. */ private static final long serialVersionUID = 7081070952159683108L; /** * Ctor. * @param src Numbers */ public MinOf(final Integer... src) { this(new IterableOf<>(src)); } /** * Ctor. * @param src Numbers */ public MinOf(final Long... src) { this(new IterableOf<>(src)); } /** * Ctor. * @param src Numbers */ public MinOf(final Double... src) { this(new IterableOf<>(src)); } /** * Ctor. * @param src Numbers */ public MinOf(final Float... src) { this(new IterableOf<>(src)); } /** * Ctor. * @param src The iterable */ public MinOf(final Iterable src) { super( new Folded<>( Long.MAX_VALUE, Math::min, new Mapped<>(Number::longValue, src) ), new Folded<>( Integer.MAX_VALUE, Math::min, new Mapped<>(Number::intValue, src) ), new Folded<>( Float.MAX_VALUE, Math::min, new Mapped<>(Number::floatValue, src) ), new Folded<>( Double.MAX_VALUE, Math::min, new Mapped<>(Number::doubleValue, src) ) ); } } cactoos-0.49/src/main/java/org/cactoos/scalar/MultiplicationOf.java000066400000000000000000000062351400054650300253540ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.scalar; import java.math.BigDecimal; import java.math.MathContext; import org.cactoos.Scalar; import org.cactoos.iterable.IterableOf; import org.cactoos.iterable.Joined; import org.cactoos.iterable.Mapped; /** * Multiplication result of numbers. * *

Here is how you can use it to multiply numbers:

* *
 * int multiplication = new MultiplicationOf(1, 2, 3, 4).intValue();
 * long multiplication = new MultiplicationOf(1L, 2L, 3L).longValue();
 * double multiplication = new MultiplicationOf(2.3, 3.4, 4.0).doubleValue();
 * 
* *

This class implements {@link Scalar}, which throws a checked * {@link Exception}. This may not be convenient in many cases. To make * it more convenient and get rid of the checked exception you can * use the {@link Unchecked} decorator. Or you may use * {@link IoChecked} to wrap it in an IOException.

* *

There is no thread-safety guarantee. * * @since 0.49.2 */ public final class MultiplicationOf extends NumberEnvelope { /** * Serialization marker. */ private static final long serialVersionUID = -5039588861554829762L; /** * Ctor. * @param arg Required argument * @param src The numbers */ public MultiplicationOf(final Number arg, final Number... src) { this(new Joined<>(arg, new IterableOf<>(src))); } /** * Ctor. * @param src The iterable */ public MultiplicationOf(final Iterable src) { super(() -> { if (!src.iterator().hasNext()) { throw new IllegalArgumentException( "Zero arguments - can not multiply" ); } return new Folded<>( BigDecimal.ONE, (mtn, value) -> mtn.multiply(value, MathContext.DECIMAL128), new Mapped( number -> BigDecimal.valueOf(number.doubleValue()), src ) ).value().doubleValue(); }); } } cactoos-0.49/src/main/java/org/cactoos/scalar/NoNulls.java000066400000000000000000000037071400054650300234650ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.scalar; import org.cactoos.Scalar; /** * Scalar check for no nulls. * * @param Type of result * @since 0.11 */ public final class NoNulls implements Scalar { /** * The scalar. */ private final Scalar origin; /** * Ctor. * @param sclr The scalar */ public NoNulls(final Scalar sclr) { this.origin = sclr; } @Override public T value() throws Exception { if (this.origin == null) { throw new IllegalArgumentException( "NULL instead of a valid scalar" ); } final T value = this.origin.value(); if (value == null) { throw new IllegalStateException( "NULL instead of a valid value" ); } return value; } } cactoos-0.49/src/main/java/org/cactoos/scalar/Not.java000066400000000000000000000037321400054650300226310ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.scalar; import org.cactoos.Scalar; /** * Logical negative. * *

There is no thread-safety guarantee. * *

This class implements {@link Scalar}, which throws a checked * {@link Exception}. This may not be convenient in many cases. To make * it more convenient and get rid of the checked exception you can * use the {@link Unchecked} decorator. Or you may use * {@link IoChecked} to wrap it in an IOException.

* * @since 0.7 */ public final class Not implements Scalar { /** * The origin scalar. */ private final Scalar origin; /** * Ctor. * @param scalar The scalar */ public Not(final Scalar scalar) { this.origin = scalar; } @Override public Boolean value() throws Exception { return !this.origin.value(); } } cactoos-0.49/src/main/java/org/cactoos/scalar/NumberEnvelope.java000066400000000000000000000062341400054650300250170ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.scalar; import org.cactoos.Scalar; /** * Envelope for the {@link Number}. * *

There is no thread-safety guarantee. * * @since 0.26 * @checkstyle AbstractClassNameCheck (500 lines) */ @SuppressWarnings("PMD.AbstractNaming") public abstract class NumberEnvelope extends Number implements Scalar { /** * Serialization marker. */ private static final long serialVersionUID = -1924406337256921883L; /** * The LONG number. */ private final Scalar lnum; /** * The INT number. */ private final Scalar inum; /** * The FLOAT number. */ private final Scalar fnum; /** * The DOUBLE number. */ private final Scalar dnum; /** * Ctor. * @param dnm Double scalar */ public NumberEnvelope(final Scalar dnm) { this( () -> dnm.value().longValue(), () -> dnm.value().intValue(), () -> dnm.value().floatValue(), dnm ); } /** * Ctor. * @param lnm Long scalar * @param inm Integer scalar * @param fnm Float scalar * @param dnm Long scalar * @checkstyle ParameterNumberCheck (5 lines) */ public NumberEnvelope(final Scalar lnm, final Scalar inm, final Scalar fnm, final Scalar dnm) { super(); this.lnum = lnm; this.inum = inm; this.fnum = fnm; this.dnum = dnm; } @Override public final int intValue() { return new Unchecked<>(this.inum).value(); } @Override public final long longValue() { return new Unchecked<>(this.lnum).value(); } @Override public final float floatValue() { return new Unchecked<>(this.fnum).value(); } @Override public final double doubleValue() { return new Unchecked<>(this.dnum).value(); } @Override public final Double value() throws Exception { return this.dnum.value(); } } cactoos-0.49/src/main/java/org/cactoos/scalar/NumberOf.java000066400000000000000000000063311400054650300236040ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.scalar; import org.cactoos.Scalar; import org.cactoos.Text; import org.cactoos.text.TextOf; /** * Text as {@link Number}. * *

 * long value = new NumberOf("186789235425346").longValue();
 * int value = new NumberOf("1867892354").intValue();
 * double value = new NumberOf("185.65156465123").doubleValue();
 * 
* *

There is no thread-safety guarantee. * *

This class implements {@link Scalar}, which throws a checked * {@link Exception}. This may not be convenient in many cases. To make * it more convenient and get rid of the checked exception you can * use the {@link Unchecked} decorator. Or you may use * {@link IoChecked} to wrap it in an IOException.

* @since 0.2 */ public final class NumberOf extends Number implements Scalar { /** * Serialization marker. */ private static final long serialVersionUID = -1924406337256921883L; /** * Number envelope. */ private NumberEnvelope envelope; /** * Ctor. * @param txt Number-string */ public NumberOf(final String txt) { this(new TextOf(txt)); } /** * Ctor. * @param text Number-text */ public NumberOf(final Text text) { this.envelope = new Sealed( new Sticky<>( () -> Long.parseLong(text.asString()) ), new Sticky<>( () -> Integer.parseInt(text.asString()) ), new Sticky<>( () -> Float.parseFloat(text.asString()) ), new Sticky<>( () -> Double.parseDouble(text.asString()) ) ); } @Override public Number value() { return this.envelope; } @Override public int intValue() { return this.envelope.intValue(); } @Override public long longValue() { return this.envelope.longValue(); } @Override public float floatValue() { return this.envelope.floatValue(); } @Override public double doubleValue() { return this.envelope.doubleValue(); } } cactoos-0.49/src/main/java/org/cactoos/scalar/Or.java000066400000000000000000000120001400054650300224350ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.scalar; import org.cactoos.Func; import org.cactoos.Proc; import org.cactoos.Scalar; import org.cactoos.func.FuncOf; import org.cactoos.iterable.IterableOf; import org.cactoos.iterable.Mapped; /** * Logical disjunction. * This class performs short-circuit evaluation in which arguments are * executed only if the preceding argument does not suffice to determine * the value of the expression. * *

This class can be effectively used to iterate through * a collection, just like * {@link java.util.stream.Stream#forEach(java.util.function.Consumer)} * works:

* * {@code * new Or( * new ProcOf<>(input -> System.out.printf("\'%s\' ", input) ), * new IterableOf<>("Mary", "John", "William", "Napkin") * ).value(); // will print 'Mary' 'John' 'William' 'Napkin' to standard output * // the result of this operation is always false * } * *

This class could be also used for matching multiple boolean * expressions:

* * {@code * new Or( * new False(), * new True(), * new True() * ).value(); // the result is true * * new Or( * new False(), * new False(), * new False() * ).value(); // the result is false * } * *

There is no thread-safety guarantee. * *

This class implements {@link Scalar}, which throws a checked * {@link Exception}. This may not be convenient in many cases. To make * it more convenient and get rid of the checked exception you can * use the {@link Unchecked} decorator. Or you may use * {@link IoChecked} to wrap it in an IOException.

* * @since 0.8 */ public final class Or implements Scalar { /** * The iterator. */ private final Iterable> origin; /** * Ctor. * @param proc Proc to map * @param src The iterable * @param Type of items in the iterable */ @SafeVarargs public Or(final Proc proc, final X... src) { this(new FuncOf<>(proc, false), src); } /** * Ctor. * @param func Func to map * @param src The iterable * @param Type of items in the iterable */ @SafeVarargs public Or(final Func func, final X... src) { this(func, new IterableOf<>(src)); } /** * Ctor. * @param proc Proc to use * @param src The iterable * @param Type of items in the iterable * @since 0.24 */ public Or(final Proc proc, final Iterable src) { this(new FuncOf<>(proc, false), src); } /** * Ctor. * @param func Func to map * @param src The iterable * @param Type of items in the iterable */ public Or(final Func func, final Iterable src) { this( new Mapped<>( item -> new ScalarOf<>(() -> func.apply(item)), src ) ); } /** * Ctor. * @param subject The subject * @param conditions Funcs to map * @param Type of items in the iterable */ @SafeVarargs public Or(final X subject, final Func... conditions) { this( new Mapped<>( item -> new ScalarOf<>(() -> item.apply(subject)), new IterableOf<>(conditions) ) ); } /** * Ctor. * @param scalar The Scalar. */ @SafeVarargs public Or(final Scalar... scalar) { this(new IterableOf<>(scalar)); } /** * Ctor. * @param iterable The iterable. */ public Or(final Iterable> iterable) { this.origin = iterable; } @Override public Boolean value() throws Exception { boolean result = false; for (final Scalar item : this.origin) { if (item.value()) { result = true; break; } } return result; } } cactoos-0.49/src/main/java/org/cactoos/scalar/PropertiesOf.java000066400000000000000000000075531400054650300245170ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.scalar; import java.io.IOException; import java.io.InputStream; import java.util.Map; import java.util.Properties; import org.cactoos.Input; import org.cactoos.Scalar; import org.cactoos.Text; import org.cactoos.io.InputOf; import org.cactoos.iterable.IterableOf; import org.cactoos.iterable.Mapped; import org.cactoos.map.MapEntry; import org.cactoos.map.MapOf; import org.cactoos.text.TextOf; /** * Map as {@link Properties}. * *

There is no thread-safety guarantee. * * @since 0.12 * @checkstyle ClassDataAbstractionCouplingCheck (500 lines) */ public final class PropertiesOf implements Scalar { /** * The underlying properties. */ private final IoChecked scalar; /** * Ctor. * @param content String */ public PropertiesOf(final String content) { this(new TextOf(content)); } /** * Ctor. * @param text Text */ public PropertiesOf(final Text text) { this(new InputOf(text)); } /** * Ctor. * @param input Input */ public PropertiesOf(final Input input) { this( () -> { final Properties props = new Properties(); try (InputStream stream = input.stream()) { props.load(stream); } return props; } ); } /** * Ctor. * @param entries The map with properties */ public PropertiesOf(final Map.Entry... entries) { this(new IterableOf<>(entries)); } /** * Ctor. * @param entries The map with properties * @since 0.23 */ public PropertiesOf(final Iterable> entries) { this( new MapOf<>( input -> new MapEntry<>( input.getKey().toString(), input.getValue().toString() ), entries ) ); } /** * Ctor. * @param map The map with properties */ public PropertiesOf(final Map map) { this( () -> { final Properties props = new Properties(); for (final Map.Entry entry : map.entrySet()) { props.setProperty( entry.getKey().toString(), entry.getValue().toString() ); } return props; } ); } /** * Ctor. * @param sclr The underlying properties */ private PropertiesOf(final Scalar sclr) { this.scalar = new IoChecked<>(sclr); } @Override public Properties value() throws IOException { return this.scalar.value(); } } cactoos-0.49/src/main/java/org/cactoos/scalar/Reduced.java000066400000000000000000000073371400054650300234510ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.scalar; import java.util.Iterator; import java.util.NoSuchElementException; import org.cactoos.BiFunc; import org.cactoos.Scalar; import org.cactoos.iterable.Mapped; /** * Reduces iterable via BiFunc. * *

{@code
 * new Reduced<>(
 *     (first, last) -> first + last,
 *     new IterableOf<>(() -> 1L, () -> 2L, () -> 3L, () -> 4L)
 * ).value() // returns 10L
 * }
* *

Here is how you can use it to * find one of items according to the specified {@link BiFunc}:

* *
{@code
 * final String apple = new Reduced<>(
 *     (first, last) -> first,
 *     new IterableOf>(
 *         () -> "Apple",
 *         () -> "Banana",
 *         () -> "Orange"
 *     )
 * ).value();
 * final String orange = new Reduced<>(
 *     (first, last) -> last,
 *     new IterableOf>(
 *         () -> "Apple",
 *         () -> "Banana",
 *         () -> "Orange"
 *     )
 * ).value();
 * }
* *

There is no thread-safety guarantee. * *

This class implements {@link Scalar}, which throws a checked * {@link Exception}. This may not be convenient in many cases. To make * it more convenient and get rid of the checked exception you can * use the {@link Unchecked} decorator. Or you may use * {@link IoChecked} to wrap it in an IOException.

* * @param Scalar type * @since 0.30 */ public final class Reduced implements Scalar { /** * Items. */ private final Iterable> items; /** * Folding function. */ private final BiFunc function; /** * Ctor. * @param reduce Reducing function * @param scalars The scalars */ public Reduced( final BiFunc reduce, final Iterable> scalars ) { this.items = scalars; this.function = reduce; } /** * Ctor. * @param reduce Reducing function * @param values Values to be wrapped as scalars */ @SafeVarargs public Reduced( final BiFunc reduce, final T... values ) { this(reduce, new Mapped<>(Constant::new, values)); } @Override public T value() throws Exception { final Iterator> iter = this.items.iterator(); if (!iter.hasNext()) { throw new NoSuchElementException( "Can't find first element in an empty iterable" ); } T acc = iter.next().value(); while (iter.hasNext()) { final T next = iter.next().value(); acc = this.function.apply(acc, next); } return acc; } } cactoos-0.49/src/main/java/org/cactoos/scalar/Repeated.java000066400000000000000000000040561400054650300236220ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.scalar; import org.cactoos.Scalar; import org.cactoos.func.FuncOf; /** * Scalar that runs repeatedly for a number of times. * * @param Type of output * @since 0.49.2 */ public final class Repeated implements Scalar { /** * Scalar. */ private final Scalar scalar; /** * Times to repeat. */ private final int times; /** * Ctor. * *

If {@code max} is equal or less than zero {@link #value()} will return * an exception.

* * @param scalar Scalar to repeat. * @param times How many times. */ public Repeated(final Scalar scalar, final int times) { this.scalar = scalar; this.times = times; } @Override public X value() throws Exception { return new org.cactoos.func.Repeated<>( new FuncOf<>(this.scalar), this.times ).apply(true); } } cactoos-0.49/src/main/java/org/cactoos/scalar/Retry.java000066400000000000000000000103231400054650300231700ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.scalar; import java.time.Duration; import org.cactoos.Func; import org.cactoos.Scalar; /** * Func that will try a few times before throwing an exception. * *
{@code
 * new RetryScalar<>(
 *     () -> {
 *         if (new SecureRandom().nextDouble() > 0.3d) {
 *             throw new IllegalArgumentException("May happen");
 *         }
 *         return 0;
 *     },
 *     5
 * ).value() // will try to run 5 times before throwing an exception
 * }
* *

There is no thread-safety guarantee. * *

This class implements {@link Scalar}, which throws a checked * {@link Exception}. This may not be convenient in many cases. To make * it more convenient and get rid of the checked exception you can * use the {@link Unchecked} decorator. Or you may use * {@link IoChecked} to wrap it in an IOException.

* * @param Type of output * @since 0.9 */ public final class Retry implements Scalar { /** * Original scalar. */ private final Scalar origin; /** * Exit condition. */ private final Func func; /** * Wait between executions. */ private final Duration wait; /** * Ctor. * @param scalar Scalar original */ public Retry(final Scalar scalar) { this(scalar, Duration.ZERO); } /** * Ctor. * @param scalar Scalar original * @param wait The {@link java.time.Duration} to wait between attempts */ public Retry(final Scalar scalar, final Duration wait) { // @checkstyle MagicNumberCheck (1 line) this(scalar, 3, wait); } /** * Ctor. * @param scalar Scalar original * @param attempts Maximum number of attempts */ public Retry(final Scalar scalar, final int attempts) { this(scalar, attempts, Duration.ZERO); } /** * Ctor. * @param scalar Scalar original * @param attempts Maximum number of attempts * @param wait The {@link java.time.Duration} to wait between attempts */ public Retry(final Scalar scalar, final int attempts, final Duration wait) { this(scalar, attempt -> attempt >= attempts, wait); } /** * Ctor. * @param scalar Func original * @param exit Exit condition, returns TRUE if there is no reason to try */ public Retry(final Scalar scalar, final Func exit) { this(scalar, exit, Duration.ZERO); } /** * Ctor. * @param scalar Func original * @param exit Exit condition, returns TRUE if there is no reason to try * @param wait The {@link java.time.Duration} to wait between attempts */ public Retry(final Scalar scalar, final Func exit, final Duration wait) { this.origin = scalar; this.func = exit; this.wait = wait; } @Override public T value() throws Exception { return new org.cactoos.func.Retry<>( (Func) input -> this.origin.value(), this.func, this.wait ).apply(true); } } cactoos-0.49/src/main/java/org/cactoos/scalar/ScalarEnvelope.java000066400000000000000000000033071400054650300247720ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.scalar; import org.cactoos.Scalar; /** * Envelope for Scalar. * *

There is no thread-safety guarantee. * * @param Type of result * @since 0.41 */ public abstract class ScalarEnvelope implements Scalar { /** * The delegate scalar. */ private final Scalar scalar; /** * Ctor. * @param scalar The scalar */ public ScalarEnvelope(final Scalar scalar) { this.scalar = scalar; } @Override public final T value() throws Exception { return this.scalar.value(); } } cactoos-0.49/src/main/java/org/cactoos/scalar/ScalarOf.java000066400000000000000000000046261400054650300235660ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.scalar; import java.util.concurrent.Callable; import org.cactoos.Func; import org.cactoos.Proc; import org.cactoos.func.FuncOf; /** * ScalarOf. * * @param Element type * @since 0.4 */ public final class ScalarOf extends ScalarEnvelope { /** * Ctor. * @param runnable Encapsulated proc * @param result Result to return * @since 0.48 */ public ScalarOf(final Runnable runnable, final T result) { this(() -> { runnable.run(); return result; }); } /** * Ctor. * @param proc Encapsulated proc * @param ipt Input * @param result Result to return * @param Type of input * @since 0.48 */ public ScalarOf(final Proc proc, final X ipt, final T result) { this(new FuncOf<>(proc, result), ipt); } /** * Ctor. * @param fnc Encapsulated func * @param ipt Input * @param Type of input * @since 0.41 */ public ScalarOf(final Func fnc, final X ipt) { this(() -> fnc.apply(ipt)); } /** * Ctor. * * @param origin The scalar */ public ScalarOf(final Callable origin) { super(origin::call); } } cactoos-0.49/src/main/java/org/cactoos/scalar/ScalarOfSupplier.java000066400000000000000000000027731400054650300253130ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.scalar; import java.util.function.Supplier; /** * ScalarOfSupplier. * * @param Element type. * @since 0.47 */ public final class ScalarOfSupplier extends ScalarEnvelope { /** * Ctor. * * @param supplier The supplier */ public ScalarOfSupplier(final Supplier supplier) { super(supplier::get); } } cactoos-0.49/src/main/java/org/cactoos/scalar/ScalarWithFallback.java000066400000000000000000000102771400054650300255540ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.scalar; import java.util.Comparator; import java.util.Map; import org.cactoos.Fallback; import org.cactoos.Scalar; import org.cactoos.func.FuncWithFallback; import org.cactoos.iterable.IterableOf; import org.cactoos.iterator.Filtered; import org.cactoos.iterator.Sorted; import org.cactoos.map.MapOf; /** * Scalar with fallbacks that enable it to recover from errors. * *

There is no thread-safety guarantee. * * @param Type of result * @see FuncWithFallback * @since 0.31 */ public final class ScalarWithFallback implements Scalar { /** * The origin scalar. */ private final Scalar origin; /** * The fallback. */ private final Iterable> fallbacks; /** * Ctor. * @param origin Original scalar * @param fbks The fallbacks */ @SafeVarargs public ScalarWithFallback( final Scalar origin, final Fallback... fbks ) { this(origin, new IterableOf<>(fbks)); } /** * Ctor. * @param origin Original scalar * @param fbks Fallbacks */ public ScalarWithFallback(final Scalar origin, final Iterable> fbks) { this.origin = origin; this.fallbacks = fbks; } @Override @SuppressWarnings("PMD.AvoidCatchingThrowable") public T value() throws Exception { T result; try { result = this.origin.value(); } catch (final InterruptedException ex) { Thread.currentThread().interrupt(); result = this.fallback(ex); // @checkstyle IllegalCatchCheck (1 line) } catch (final Throwable ex) { result = this.fallback(ex); } return result; } /** * Finds the best fallback for the given exception type and apply it to * the exception or throw the original error if no fallback found. * @param exp The original exception * @return Result of the most suitable fallback * @throws Exception The original exception if no fallback found */ @SuppressWarnings("PMD.AvoidThrowingRawExceptionTypes") private T fallback(final Throwable exp) throws Exception { final Sorted, Integer>> candidates = new Sorted<>( Comparator.comparing(Map.Entry::getValue), new Filtered<>( entry -> new Not( new Equals<>( entry::getValue, () -> Integer.MIN_VALUE ) ).value(), new MapOf<>( fbk -> fbk, fbk -> fbk.support(exp), this.fallbacks ).entrySet().iterator() ) ); if (candidates.hasNext()) { return candidates.next().getKey().apply(exp); } else { throw new Exception( "No fallback found - throw the original exception", exp ); } } } cactoos-0.49/src/main/java/org/cactoos/scalar/Sealed.java000066400000000000000000000041161400054650300232630ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.scalar; import org.cactoos.Scalar; /** * Sealed serializable envelope for the {@link Number}. * *

There is no thread-safety guarantee. * * @since 1.0 */ final class Sealed extends NumberEnvelope { /** * Serialization marker. */ private static final long serialVersionUID = 1376783344164412557L; /** * Ctor. * @param number Number value. */ Sealed(final Number number) { this( number::longValue, number::intValue, number::floatValue, number::doubleValue ); } /** * Ctor. * @param lnm Long scalar * @param inm Integer scalar * @param fnm Float scalar * @param dnm Double scalar * @checkstyle ParameterNumberCheck (5 lines) */ Sealed(final Scalar lnm, final Scalar inm, final Scalar fnm, final Scalar dnm) { super(lnm, inm, fnm, dnm); } } cactoos-0.49/src/main/java/org/cactoos/scalar/Solid.java000066400000000000000000000041241400054650300231370ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.scalar; import org.cactoos.Scalar; /** * Cached and synchronized version of a Scalar. * *

Objects of this class are thread safe. * * @param Type of result * @see Sticky * @see Synced * @since 0.24 */ public final class Solid implements Scalar { /** * Origin. */ private final Scalar origin; /** * Cache. */ private volatile T cache; /** * Sync lock. */ private final Object lock; /** * Ctor. * @param origin The Scalar to cache and sync */ public Solid(final Scalar origin) { this.origin = origin; this.lock = new Object(); } @Override public T value() throws Exception { if (this.cache == null) { synchronized (this.lock) { if (this.cache == null) { this.cache = this.origin.value(); } } } return this.cache; } } cactoos-0.49/src/main/java/org/cactoos/scalar/Sticky.java000066400000000000000000000050661400054650300233410ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.scalar; import org.cactoos.Func; import org.cactoos.Scalar; import org.cactoos.func.StickyFunc; /** * Cached version of a Scalar. * *

This {@link Scalar} decorator technically is an in-memory * cache.

* *

Pay attention that this class is not thread-safe. It is highly * recommended to always decorate it with {@link Synced}.

* *

This class implements {@link Scalar}, which throws a checked * {@link Exception}. This may not be convenient in many cases. To make * it more convenient and get rid of the checked exception you can * use the {@link Unchecked} decorator. Or you may use * {@link IoChecked} to wrap it in an IOException.

* *
{@code
 * final Scalar scalar = new StickyScalar<>(
 *     () -> {
 *         System.out.println("Will be printed only once");
 *         return new SecureRandom().nextInt();
 *     }
 * ).value()
 * }
* *

There is no thread-safety guarantee. * * @param Type of result * @see StickyFunc * @since 0.3 */ public final class Sticky implements Scalar { /** * Func. */ private final Func func; /** * Ctor. * @param scalar The Scalar to cache */ public Sticky(final Scalar scalar) { this.func = new StickyFunc<>( input -> scalar.value() ); } @Override public T value() throws Exception { return this.func.apply(true); } } cactoos-0.49/src/main/java/org/cactoos/scalar/SumOf.java000066400000000000000000000062611400054650300231220ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.scalar; import java.math.BigDecimal; import java.math.MathContext; import org.cactoos.Scalar; import org.cactoos.iterable.IterableOf; import org.cactoos.iterable.Mapped; /** * Int total of numbers. * *

Here is how you can use it to summarize numbers:

* *
 * int sum = new SumOf(1, 2, 3, 4).intValue();
 * long sum = new SumOf(1L, 2L, 3L).longValue();
 * int sum = new SumOf(numbers.toArray(new Integer[numbers.size()])).intValue();
 * 
* *

This class implements {@link Scalar}, which throws a checked * {@link Exception}. This may not be convenient in many cases. To make * it more convenient and get rid of the checked exception you can * use the {@link Unchecked} decorator. Or you may use * {@link IoChecked} to wrap it in an IOException.

* *

There is no thread-safety guarantee. * * @since 0.9 */ public final class SumOf extends NumberEnvelope { /** * Serialization marker. */ private static final long serialVersionUID = 7775359972001208403L; /** * Ctor. * @param src Numbers * @since 0.22 */ public SumOf(final Integer... src) { this(new IterableOf<>(src)); } /** * Ctor. * @param src Numbers * @since 0.22 */ public SumOf(final Long... src) { this(new IterableOf<>(src)); } /** * Ctor. * @param src Numbers * @since 0.22 */ public SumOf(final Double... src) { this(new IterableOf<>(src)); } /** * Ctor. * @param src Numbers * @since 0.22 */ public SumOf(final Float... src) { this(new IterableOf<>(src)); } /** * Ctor. * @param src The iterable */ public SumOf(final Iterable src) { super(() -> new Folded<>( BigDecimal.ZERO, (sum, value) -> sum.add(value, MathContext.DECIMAL128), new Mapped( number -> BigDecimal.valueOf(number.doubleValue()), src )).value().doubleValue() ); } } cactoos-0.49/src/main/java/org/cactoos/scalar/SumOfDouble.java000066400000000000000000000037411400054650300242550ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.scalar; import org.cactoos.Scalar; /** * Double Scalar which sums up the values of other Scalars of the same type. * *

Here is how you can use it to summarize double numbers:

* *
{@code
 * double sum = new SumOfDoubleScalar(() -> 1.1,() -> 2.1, () -> 3.1).value();
 * }
* *

This class implements {@link Scalar}, which throws a checked * {@link Exception}. Despite that this class does NOT throw a checked * exception.

* *

There is no thread-safety guarantee. * * @since 0.30 */ public final class SumOfDouble extends ScalarEnvelope { /** * Ctor. * @param src Varargs of Scalar to sum up values from * @since 0.30 */ @SafeVarargs public SumOfDouble(final Scalar... src) { super(new Mapped<>(Number::doubleValue, new SumOfScalar(src))); } } cactoos-0.49/src/main/java/org/cactoos/scalar/SumOfFloat.java000066400000000000000000000037241400054650300241110ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.scalar; import org.cactoos.Scalar; /** * Float Scalar which sums up the values of other Scalars of the same type * *

Here is how you can use it to summarize float numbers:

* *
{@code
 * float sum = new SumOfFloatScalar(() -> 1f,() -> 2f, () -> 3f).value();
 * }
* *

This class implements {@link Scalar}, which throws a checked * {@link Exception}. Despite that this class does NOT throw a checked * exception.

* *

There is no thread-safety guarantee. * * @since 0.30 */ public final class SumOfFloat extends ScalarEnvelope { /** * Ctor. * @param src Varargs of Scalar to sum up values from * @since 0.30 */ @SafeVarargs public SumOfFloat(final Scalar... src) { super(new Mapped<>(Number::floatValue, new SumOfScalar(src))); } } cactoos-0.49/src/main/java/org/cactoos/scalar/SumOfInt.java000066400000000000000000000037341400054650300235770ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.scalar; import org.cactoos.Scalar; /** * Integer Scalar which sums up the values of other Scalars of the same type * *

Here is how you can use it to summarize numbers:

* *
{@code
 * int sum = new SumOfIntScalar(() -> 1,() -> 2, () -> 3).value();
 * // sum equal to 6
 * }
* *

This class implements {@link Scalar}, which throws a checked * {@link Exception}. Despite that this class does NOT throw a checked * exception.

* *

There is no thread-safety guarantee. * * @since 0.30 */ public final class SumOfInt extends ScalarEnvelope { /** * Ctor. * @param src Varargs of Scalar to sum up values from * @since 0.30 */ @SafeVarargs public SumOfInt(final Scalar... src) { super(new Mapped<>(Number::intValue, new SumOfScalar(src))); } } cactoos-0.49/src/main/java/org/cactoos/scalar/SumOfLong.java000066400000000000000000000037031400054650300237400ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.scalar; import org.cactoos.Scalar; /** * Long Scalar which sums up the values of other Scalars of the same type * *

Here is how you can use it to summarize numbers:

* *
{@code
 * long sum = new SumOfLongScalar(() -> 1,() -> 2, () -> 3).value();
 * }
* *

This class implements {@link Scalar}, which throws a checked * {@link Exception}. Despite that this class does NOT throw a checked * exception.

* *

There is no thread-safety guarantee. * * @since 0.30 */ public final class SumOfLong extends ScalarEnvelope { /** * Ctor. * @param src Varargs of Scalar to sum up values from * @since 0.30 */ @SafeVarargs public SumOfLong(final Scalar... src) { super(new Mapped<>(Number::longValue, new SumOfScalar(src))); } } cactoos-0.49/src/main/java/org/cactoos/scalar/SumOfScalar.java000066400000000000000000000035401400054650300242450ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.scalar; import org.cactoos.Scalar; import org.cactoos.iterable.Mapped; /** * Make a scalar which is sum of scalar's values. * *

This class implements {@link Scalar}, which throws a checked * {@link Exception}. Despite that this class does NOT throw a checked * exception.

* *

There is no thread-safety guarantee. *

Note this class is for internal usage only * * @since 0.30 */ final class SumOfScalar extends ScalarEnvelope { /** * Ctor. * @param src Varargs of Scalar to sum up values from * @since 0.30 */ @SafeVarargs SumOfScalar(final Scalar... src) { super(() -> new SumOf(new Mapped<>(Scalar::value, src))); } } cactoos-0.49/src/main/java/org/cactoos/scalar/Synced.java000066400000000000000000000050701400054650300233130ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.scalar; import org.cactoos.Scalar; /** * Scalar that is thread-safe. * *

This class implements {@link Scalar}, which throws a checked * {@link Exception}. This may not be convenient in many cases. To make * it more convenient and get rid of the checked exception you can * use the {@link Unchecked} decorator. Or you may use * {@link IoChecked} to wrap it in an IOException.

* *
{@code
 * final List list = new LinkedList<>();
 * final int threads = 100;
 * new RunsInThreads<>(
 *     new SyncScalar<>(() -> list.add(1)), threads
 * ); // list.size() will be equal to threads value
 * }
* *

Objects of this class are thread-safe.

* * @param Type of result * @since 0.3 */ public final class Synced implements Scalar { /** * The scalar to cache. */ private final Scalar origin; /** * Sync lock. */ private final Object mutex; /** * Ctor. * @param src The Scalar to cache */ public Synced(final Scalar src) { this(src, src); } /** * Ctor. * @param scalar The Scalar to cache * @param lock Sync lock */ public Synced(final Scalar scalar, final Object lock) { this.origin = scalar; this.mutex = lock; } @Override public T value() throws Exception { synchronized (this.mutex) { return this.origin.value(); } } } cactoos-0.49/src/main/java/org/cactoos/scalar/Ternary.java000066400000000000000000000103721400054650300235130ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.scalar; import org.cactoos.Func; import org.cactoos.Scalar; import org.cactoos.func.FuncOf; /** * Ternary operation. * *

There is no thread-safety guarantee. * *

This class implements {@link Scalar}, which throws a checked * {@link Exception}. This may not be convenient in many cases. To make * it more convenient and get rid of the checked exception you can * use the {@link Unchecked} decorator. Or you may use * {@link IoChecked} to wrap it in an IOException.

* *
{@code
 * new Ternary<>(
 *     scalar,
 *     value -> value > 3,
 *     value -> true,
 *     value -> false
 * ).value() // will be equal to true
 * }
* * @param Type of item. * @since 0.8 */ public final class Ternary extends ScalarEnvelope { /** * Ctor. * @param cnd The condition * @param cons The consequent * @param alter The alternative * @since 0.9 */ public Ternary(final boolean cnd, final T cons, final T alter) { this(() -> cnd, cons, alter); } /** * Ctor. * @param cnd The condition * @param cons The consequent * @param alter The alternative */ public Ternary(final Scalar cnd, final T cons, final T alter) { this(cnd, () -> cons, () -> alter); } /** * Ctor. * @param cnd The condition * @param cons The consequent * @param alter The alternative * @since 0.9 */ public Ternary(final boolean cnd, final Scalar cons, final Scalar alter) { this(new Constant<>(cnd), cons, alter); } /** * Ctor. * @param cnd The condition * @param cons The consequent * @param alter The alternative * @since 0.9 */ public Ternary(final Scalar cnd, final Scalar cons, final Scalar alter) { this( new Object(), new FuncOf<>(cnd), new FuncOf<>(cons), new FuncOf<>(alter) ); } /** * Ctor. * @param input The input to pass to all of them * @param cnd The condition * @param cons The consequent * @param alter The alternative * @param Type of input * @since 0.9 * @checkstyle ParameterNumberCheck (5 lines) */ public Ternary( final X input, final Func cnd, final Func cons, final Func alter ) { this(new Constant<>(input), cnd, cons, alter); } /** * Ctor. * @param input The input to pass to all of them * @param cnd The condition * @param cons The consequent * @param alter The alternative * @param Type of input * @since 0.9 * @checkstyle ParameterNumberCheck (5 lines) */ public Ternary( final Scalar input, final Func cnd, final Func cons, final Func alter ) { super(() -> { final X inp = input.value(); final Func result; if (cnd.apply(inp)) { result = cons; } else { result = alter; } return result.apply(inp); }); } } cactoos-0.49/src/main/java/org/cactoos/scalar/True.java000066400000000000000000000026101400054650300230020ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.scalar; import org.cactoos.Scalar; /** * Logical truth. * *

This class is thread-safe. * * @since 0.7 */ public final class True implements Scalar { @Override public Boolean value() { return true; } } cactoos-0.49/src/main/java/org/cactoos/scalar/Unchecked.java000066400000000000000000000036171400054650300237640ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.scalar; import java.io.IOException; import java.io.UncheckedIOException; import org.cactoos.Scalar; /** * Scalar that doesn't throw checked {@link Exception}. * *

There is no thread-safety guarantee. * * @param Type of result * @since 0.3 */ public final class Unchecked implements Scalar { /** * Original origin. */ private final Scalar origin; /** * Ctor. * @param scalar Encapsulated origin */ public Unchecked(final Scalar scalar) { this.origin = scalar; } @Override public T value() { try { return new IoChecked<>(this.origin).value(); } catch (final IOException ex) { throw new UncheckedIOException(ex); } } } cactoos-0.49/src/main/java/org/cactoos/scalar/Xor.java000066400000000000000000000050751400054650300226430ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.scalar; import org.cactoos.Scalar; import org.cactoos.iterable.IterableOf; import org.cactoos.iterable.Joined; /** * Logical exclusive or. * Returns {@link True} when an odd number of elements have value true, * otherwise return {@link False}. * *

This class could be also used for matching multiple boolean * expressions:

* * {@code * new Xor( * new True(), * new True(), * new True() * ).value(); // the result is true * * new Xor( * new True(), * new False(), * new True() * ).value(); // the result is false * } * *

This class implements {@link Scalar}, which throws a checked * {@link Exception}. This may not be convenient in many cases. To make * it more convenient and get rid of the checked exception you can * use the {@link Unchecked} decorator. Or you may use * {@link IoChecked} to wrap it in an IOException.

* *

There is no thread-safety guarantee. * * @see Unchecked * @see IoChecked * @since 0.49 */ public final class Xor extends ScalarEnvelope { /** * Ctor. * @param scalar The Scalar. */ @SafeVarargs public Xor(final Scalar... scalar) { this(new IterableOf<>(scalar)); } /** * Ctor. * @param iterable The iterable. */ public Xor(final Iterable> iterable) { super(new Reduced<>((a, b) -> a ^ b, new Joined<>(new False(), iterable)) ); } } cactoos-0.49/src/main/java/org/cactoos/scalar/package-info.java000066400000000000000000000023051400054650300244100ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ /** * Scalars. * * @since 0.12 */ package org.cactoos.scalar; cactoos-0.49/src/main/java/org/cactoos/set/000077500000000000000000000000001400054650300205475ustar00rootroot00000000000000cactoos-0.49/src/main/java/org/cactoos/set/SetEnvelope.java000066400000000000000000000033121400054650300236420ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.set; import java.util.Set; import org.cactoos.collection.CollectionEnvelope; /** * Set envelope. *

There is no thread-safety guarantee.

* * @param Element type * @checkstyle AbstractClassNameCheck (500 lines) * @since 0.49.2 */ @SuppressWarnings( { "PMD.TooManyMethods", "PMD.AbstractNaming" } ) public abstract class SetEnvelope extends CollectionEnvelope implements Set { /** * Ctor. * * @param src Source */ public SetEnvelope(final Set src) { super(src); } } cactoos-0.49/src/main/java/org/cactoos/set/SetOf.java000066400000000000000000000034671400054650300224440ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.set; import java.util.HashSet; import java.util.Set; import org.cactoos.iterable.IterableOf; /** * Iterable as {@link Set} based on {@link HashSet}. * *

There is no thread-safety guarantee. * * @param Set type * @since 0.49.2 */ public final class SetOf extends SetEnvelope { /** * Ctor. * * @param array An array of some elements */ @SafeVarargs public SetOf(final T... array) { this(new IterableOf<>(array)); } /** * Ctor. * @param src An {@link Iterable} */ public SetOf(final Iterable src) { super(new HashSet<>()); src.forEach(super::add); } } cactoos-0.49/src/main/java/org/cactoos/set/Sorted.java000066400000000000000000000041051400054650300226520ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.set; import java.util.Comparator; import java.util.Set; import java.util.TreeSet; import org.cactoos.iterable.IterableOf; /** * Iterable as Sorted {@link Set} based on {@link TreeSet}. * *

There is no thread-safety guarantee. * * @param Set type * @since 1.0.0 */ public final class Sorted extends SortedSetEnvelope { /** * Ctor. * @param cmp Comparator * @param array An array of some elements */ @SafeVarargs public Sorted(final Comparator cmp, final T... array) { this(cmp, new IterableOf<>(array)); } /** * Ctor. * @param cmp Comparator * @param src An {@link Iterable} */ @SuppressWarnings("PMD.ConstructorOnlyInitializesOrCallOtherConstructors") public Sorted( final Comparator cmp, final Iterable src ) { super(new TreeSet<>(cmp)); src.forEach(super::add); } } cactoos-0.49/src/main/java/org/cactoos/set/SortedSetEnvelope.java000066400000000000000000000050231400054650300250240ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.set; import java.util.Comparator; import java.util.SortedSet; /** * SortedSet envelope. *

There is no thread-safety guarantee.

* * @param Element type * @checkstyle AbstractClassNameCheck (500 lines) * @since 0.45 */ @SuppressWarnings( { "PMD.TooManyMethods", "PMD.AbstractNaming" } ) public abstract class SortedSetEnvelope extends SetEnvelope implements SortedSet { /** * The original Set this object delegates to. */ private final SortedSet origin; /** * Primary ctor. * @param origin The original SortedSet to delegate to. */ protected SortedSetEnvelope(final SortedSet origin) { super(origin); this.origin = origin; } @Override public final Comparator comparator() { return this.origin.comparator(); } @Override public final SortedSet subSet(final T begin, final T end) { return this.origin.subSet(begin, end); } @Override public final SortedSet headSet(final T end) { return this.origin.headSet(end); } @Override public final SortedSet tailSet(final T from) { return this.origin.tailSet(from); } @Override public final T first() { return this.origin.first(); } @Override public final T last() { return this.origin.last(); } } cactoos-0.49/src/main/java/org/cactoos/set/package-info.java000066400000000000000000000023011400054650300237320ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ /** * Sets. * * @since 0.49.2 */ package org.cactoos.set; cactoos-0.49/src/main/java/org/cactoos/text/000077500000000000000000000000001400054650300207405ustar00rootroot00000000000000cactoos-0.49/src/main/java/org/cactoos/text/Abbreviated.java000066400000000000000000000061161400054650300240170ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.text; import org.cactoos.Text; import org.cactoos.scalar.LengthOf; import org.cactoos.scalar.ScalarOf; import org.cactoos.scalar.Ternary; /** * Abbreviates a Text using ellipses. * *

There is no thread-safety guarantee. * * @since 0.29 * @checkstyle ClassDataAbstractionCouplingCheck (500 lines) */ public final class Abbreviated extends TextEnvelope { /** * The default max line width. */ private static final int MAX_WIDTH = 80; /** * The ellipses. */ private static final String ELLIPSES = "..."; /** * Ctor. * *

By default, the max line width is 80 characters. * * @param text The Text */ public Abbreviated(final String text) { this(new TextOf(text)); } /** * Ctor. * *

By default, the max line width is 80 characters. * * @param text The Text */ public Abbreviated(final Text text) { this(text, Abbreviated.MAX_WIDTH); } /** * Ctor. * * @param text A String * @param max Max width of the result string */ public Abbreviated(final String text, final int max) { this(new TextOf(text), max); } /** * Ctor. * @param text The Text * @param max Max width of the result string */ public Abbreviated(final Text text, final int max) { super( new Flattened( new Ternary<>( new ScalarOf<>(() -> new Sticky(text)), (Text t) -> new LengthOf(t).longValue() <= max, t -> t, t -> new FormattedText( "%s%s", new Sub( t, 0, max - Abbreviated.ELLIPSES.length() ), Abbreviated.ELLIPSES ) ) ) ); } } cactoos-0.49/src/main/java/org/cactoos/text/Base64Decoded.java000066400000000000000000000034311400054650300241000ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.text; import org.cactoos.Text; import org.cactoos.bytes.Base64Bytes; import org.cactoos.bytes.BytesOf; /** * Decodes the origin text using the Base64 encoding scheme. * @since 0.20.2 */ public final class Base64Decoded extends TextEnvelope { /** * Ctor. * * @param input The String */ public Base64Decoded(final String input) { this(new TextOf(input)); } /** * Ctor. * * @param origin Origin text */ public Base64Decoded(final Text origin) { super(new TextOf( new Base64Bytes( new BytesOf(origin) ) )); } } cactoos-0.49/src/main/java/org/cactoos/text/Base64Encoded.java000066400000000000000000000034341400054650300241150ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.text; import org.cactoos.Text; import org.cactoos.bytes.BytesBase64; import org.cactoos.bytes.BytesOf; /** * Encodes the origin text using the Base64 encoding scheme. * * @since 0.20.2 */ public final class Base64Encoded extends TextEnvelope { /** * Ctor. * * @param input The String */ public Base64Encoded(final String input) { this(new TextOf(input)); } /** * Ctor. * * @param origin Origin text */ public Base64Encoded(final Text origin) { super(new TextOf( new BytesBase64( new BytesOf(origin) ) )); } } cactoos-0.49/src/main/java/org/cactoos/text/Capitalized.java000066400000000000000000000047251400054650300240440ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.text; import org.cactoos.Text; import org.cactoos.scalar.ScalarOf; import org.cactoos.scalar.Ternary; /** * Text in capitalized case, * changed the first character to title case as per {@link Character#toTitleCase(int)}, * no other characters are changed. * * @since 0.46 * @checkstyle ClassDataAbstractionCouplingCheck (500 lines) */ public final class Capitalized extends TextEnvelope { /** * Ctor. * * @param text The text */ public Capitalized(final String text) { this(new TextOf(text)); } /** * Ctor. * @param text The text */ public Capitalized(final Text text) { super( new Flattened( new Ternary<>( new ScalarOf<>(() -> new Sticky(text)), new org.cactoos.func.Flattened<>(IsBlank::new), t -> t, t -> new Joined( "", new TextOf( Character.toChars( Character.toTitleCase( t.asString().codePointAt(0) ) ) ), new Sub(t, 1) ) ) ) ); } } cactoos-0.49/src/main/java/org/cactoos/text/ComparableText.java000066400000000000000000000037451400054650300245260ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.text; import org.cactoos.Text; import org.cactoos.scalar.Unchecked; /** * Text implementing Comparable.
* Below the example how you can sort words in a string: *

{@code
 * Iterable sorted = new Sorted<>(
 *     new Mapped<>(
 *         ComparableText::new,
 *         new SplitText("The quick brown fox jumps over the lazy dog", " ")
 *     )
 * )
 * }
* *

There is no thread-safety guarantee. * * @since 0.27 */ public final class ComparableText extends TextEnvelope implements Comparable { /** * Ctor. * @param text The text */ public ComparableText(final Text text) { super(text); } @Override public int compareTo(final Text other) { return new Unchecked<>( () -> this.asString().compareTo(other.asString()) ).value(); } } cactoos-0.49/src/main/java/org/cactoos/text/Concatenated.java000066400000000000000000000040001400054650300241650ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.text; import org.cactoos.Text; import org.cactoos.iterable.IterableOf; import org.cactoos.iterable.Mapped; /** * Concatenate a Text. * *

There is no thread-safety guarantee. * * @since 0.47 */ public class Concatenated extends TextEnvelope { /** * Ctor. * @param txts Texts to be concatenated */ public Concatenated(final Text... txts) { this(new IterableOf<>(txts)); } /** * Ctor. * @param strs Strings to be concatenated */ public Concatenated(final String... strs) { this( new Mapped<>( TextOf::new, new IterableOf<>(strs) ) ); } /** * Ctor. * @param txts Texts to be concatenated */ public Concatenated(final Iterable txts) { super(new Joined(new TextOf(""), txts)); } } cactoos-0.49/src/main/java/org/cactoos/text/Contains.java000066400000000000000000000046341400054650300233700ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.text; import org.cactoos.Scalar; import org.cactoos.Text; /** * Tests if this Text contains other Text. * * @since 1.0 */ public final class Contains implements Scalar { /** * The origin. */ private final Text origin; /** * The other. */ private final Text other; /** * Ctor. * @param origin The origin * @param other The other */ public Contains(final String origin, final String other) { this(new TextOf(origin), new TextOf(other)); } /** * Ctor. * @param origin The origin * @param other The other */ public Contains(final String origin, final Text other) { this(new TextOf(origin), other); } /** * Ctor. * @param origin The origin * @param other The other */ public Contains(final Text origin, final String other) { this(origin, new TextOf(other)); } /** * Ctor. * @param origin The origin * @param other The other */ public Contains(final Text origin, final Text other) { this.origin = origin; this.other = other; } @Override public Boolean value() throws Exception { return this.origin.asString().contains(this.other.asString()); } } cactoos-0.49/src/main/java/org/cactoos/text/EndsWith.java000066400000000000000000000040251400054650300233310ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.text; import org.cactoos.Scalar; import org.cactoos.Text; /** * Tests if this Text ends with the specified suffix. * * @since 1.0 */ public final class EndsWith implements Scalar { /** * The origin. */ private final Text origin; /** * The suffix. */ private final Text suffix; /** * Ctor. * @param origin The origin * @param suffix The suffix */ public EndsWith(final Text origin, final String suffix) { this(origin, new TextOf(suffix)); } /** * Ctor. * @param origin The origin * @param suffix The suffix */ public EndsWith(final Text origin, final Text suffix) { this.origin = origin; this.suffix = suffix; } @Override public Boolean value() throws Exception { return this.origin.asString().endsWith(this.suffix.asString()); } } cactoos-0.49/src/main/java/org/cactoos/text/Flattened.java000066400000000000000000000031051400054650300235100ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.text; import org.cactoos.Scalar; import org.cactoos.Text; import org.cactoos.scalar.Mapped; /** * {@link Text} from {@link Scalar}. * *

There is no thread-safety guarantee. * * @since 0.46 */ public final class Flattened extends TextEnvelope { /** * Ctor. * @param sclr The text */ public Flattened(final Scalar sclr) { super(new TextOf(new Mapped<>(Text::asString, sclr))); } } cactoos-0.49/src/main/java/org/cactoos/text/FormattedText.java000066400000000000000000000103561400054650300244020ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.text; import java.util.Collection; import java.util.Formatter; import java.util.Locale; import org.cactoos.Text; import org.cactoos.list.ListOf; /** * Text in Sprinf format. * *

There is no thread-safety guarantee. * * @since 0.1 */ public final class FormattedText extends TextEnvelope { /** * New formatted string with default locale. * * @param ptn Pattern * @param arguments Arguments */ public FormattedText(final String ptn, final Object... arguments) { this(ptn, new ListOf<>(arguments)); } /** * New formatted string with default locale. * * @param ptn Pattern * @param arguments Arguments */ public FormattedText(final Text ptn, final Object... arguments) { this(ptn, new ListOf<>(arguments)); } /** * New formatted string with specified locale. * * @param ptn Pattern * @param locale Format locale * @param arguments Arguments */ public FormattedText( final String ptn, final Locale locale, final Object... arguments ) { this(ptn, locale, new ListOf<>(arguments)); } /** * New formatted string with specified locale. * * @param ptn Pattern * @param locale Format locale * @param arguments Arguments */ public FormattedText( final Text ptn, final Locale locale, final Object... arguments ) { this(ptn, locale, new ListOf<>(arguments)); } /** * New formatted string with default locale. * * @param ptn Pattern * @param arguments Arguments */ public FormattedText(final String ptn, final Collection arguments) { this(ptn, Locale.getDefault(Locale.Category.FORMAT), arguments); } /** * New formatted string with default locale. * * @param ptn Pattern * @param arguments Arguments */ public FormattedText(final Text ptn, final Collection arguments) { this(ptn, Locale.getDefault(Locale.Category.FORMAT), arguments); } /** * New formatted string with specified locale. * * @param ptn Pattern * @param locale Format locale * @param arguments Arguments */ public FormattedText( final String ptn, final Locale locale, final Collection arguments ) { this(new TextOf(ptn), locale, arguments); } /** * New formatted string with specified locale. * * @param ptn Pattern * @param locale Format locale * @param args Arguments */ public FormattedText( final Text ptn, final Locale locale, final Collection args ) { super( new Mapped( pattern -> { final StringBuilder out = new StringBuilder(pattern.length()); try (Formatter fmt = new Formatter(out, locale)) { fmt.format(pattern, args.toArray()); } return out.toString(); }, ptn ) ); } } cactoos-0.49/src/main/java/org/cactoos/text/HexOf.java000066400000000000000000000044141400054650300226170ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.text; import org.cactoos.Bytes; /** * Hexadecimal representation of Bytes. * *

There is no thread-safety guarantee. * * @since 0.28 */ public final class HexOf extends TextEnvelope { /** * The hexadecimal chars. */ private static final char[] HEX_CHARS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', }; /** * Ctor. * @param bytes The bytes */ public HexOf(final Bytes bytes) { super( new TextOf( () -> { final byte[] bts = bytes.asBytes(); final char[] hex = new char[bts.length * 2]; int chr = -1; for (int idx = 0; idx < bts.length; ++idx) { // @checkstyle MagicNumber (3 line) final int value = 0xff & bts[idx]; hex[++chr] = HexOf.HEX_CHARS[value >>> 4]; hex[++chr] = HexOf.HEX_CHARS[value & 0x0f]; } return new String(hex); } ) ); } } cactoos-0.49/src/main/java/org/cactoos/text/IsBlank.java000066400000000000000000000034001400054650300231230ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.text; import org.cactoos.Scalar; import org.cactoos.Text; /** * Determines if text is blank (consists of spaces) or not. * *

There is no thread-safety guarantee. * @see IsEmpty * @since 0.1 */ public final class IsBlank implements Scalar { /** * The text. */ private final Text origin; /** * Ctor. * @param text The text */ public IsBlank(final Text text) { this.origin = text; } @Override public Boolean value() throws Exception { return this.origin.asString().chars() .allMatch(Character::isWhitespace); } } cactoos-0.49/src/main/java/org/cactoos/text/IsEmpty.java000066400000000000000000000032101400054650300231710ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.text; import org.cactoos.Scalar; import org.cactoos.Text; /** * Determines if text is empty or not. * @see IsBlank * @since 0.47 */ public final class IsEmpty implements Scalar { /** * The text. */ private final Text txt; /** * Ctor. * @param text The text */ public IsEmpty(final Text text) { this.txt = text; } @Override public Boolean value() throws Exception { return this.txt.asString().isEmpty(); } } cactoos-0.49/src/main/java/org/cactoos/text/Joined.java000066400000000000000000000056561400054650300230270ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.text; import java.util.StringJoiner; import org.cactoos.Text; import org.cactoos.iterable.IterableOf; import org.cactoos.iterable.Mapped; /** * Join a Text. * *

There is no thread-safety guarantee. * * @since 0.9 */ public final class Joined extends TextEnvelope { /** * Ctor. * @param delimit Delimit among strings * @param strs Strings to be joined */ public Joined(final String delimit, final String... strs) { this(delimit, new IterableOf<>(strs)); } /** * Ctor. * @param delimit Delimit among strings * @param strs Strings to be joined */ public Joined(final String delimit, final Iterable strs) { this( new TextOf(delimit), new Mapped<>(TextOf::new, strs) ); } /** * Ctor. * @param delimit Delimit among texts * @param txts Texts to be joined */ public Joined(final Text delimit, final Text... txts) { this(delimit, new IterableOf<>(txts)); } /** * Ctor. * @param delimit Delimit among texts * @param txts Texts to be joined */ public Joined(final String delimit, final Text... txts) { this(new TextOf(delimit), new IterableOf<>(txts)); } /** * Ctor. * @param delimit Delimit among texts * @param txts Texts to be joined */ public Joined(final Text delimit, final Iterable txts) { super( new TextOf( () -> { final StringJoiner joint = new StringJoiner(delimit.asString()); for (final Text text : txts) { joint.add(text.asString()); } return joint.toString(); } ) ); } } cactoos-0.49/src/main/java/org/cactoos/text/Lowered.java000066400000000000000000000035201400054650300232040ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.text; import java.util.Locale; import org.cactoos.Text; /** * Text in lower case. * *

There is no thread-safety guarantee. * * @since 0.1 */ public final class Lowered extends TextEnvelope { /** * Ctor. * @param text The text */ public Lowered(final String text) { this(new TextOf(text)); } /** * Ctor. * @param text The text */ public Lowered(final Text text) { this(text, Locale.ENGLISH); } /** * Ctor. * @param text The text * @param locale The locale */ public Lowered(final Text text, final Locale locale) { super(new Mapped(str -> str.toLowerCase(locale), text)); } } cactoos-0.49/src/main/java/org/cactoos/text/Mapped.java000066400000000000000000000030351400054650300230120ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.text; import org.cactoos.Func; import org.cactoos.Text; /** * Mapped text. * * @since 0.47 */ public final class Mapped extends TextEnvelope { /** * Ctor. * * @param fnc Function to apply * @param txt Original text */ public Mapped(final Func fnc, final Text txt) { super(new TextOf(() -> fnc.apply(txt.asString()))); } } cactoos-0.49/src/main/java/org/cactoos/text/NoNulls.java000066400000000000000000000040441400054650300231770ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.text; import org.cactoos.Text; /** * Text check for no nulls. * *

There is no thread-safety guarantee. * * @since 0.11 */ public final class NoNulls extends TextEnvelope { /** * Ctor. * @param text The text */ public NoNulls(final Text text) { super( new TextOf( () -> { if (text == null) { throw new IllegalArgumentException( "NULL instead of a valid text" ); } final String string = text.asString(); if (string == null) { throw new IllegalStateException( "NULL instead of a valid result string" ); } return string; } ) ); } } cactoos-0.49/src/main/java/org/cactoos/text/Normalized.java000066400000000000000000000033401400054650300237070ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.text; import org.cactoos.Text; /** * Normalize (replace sequences of whitespace characters by a single space) * a Text. * * @since 0.9 */ public final class Normalized extends TextEnvelope { /** * Ctor. * @param text A Text */ public Normalized(final String text) { this(new TextOf(text)); } /** * Ctor. * @param text A Text */ public Normalized(final Text text) { super( new Replaced( new Trimmed(text), "\\s+", " " ) ); } } cactoos-0.49/src/main/java/org/cactoos/text/PaddedStart.java000066400000000000000000000040451400054650300240050ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.text; import org.cactoos.Text; /** * Text padded at start to reach the given length. * *

There is thread safe. * * @since 0.32 */ public final class PaddedStart extends TextEnvelope { /** * Ctor. * @param text The text * @param length The minimum length of the resulting string * @param symbol The padding symbol */ public PaddedStart( final Text text, final int length, final char symbol) { super( new Flattened( () -> { final String original = text.asString(); return new Joined( new TextOf(""), new Repeated( new TextOf(symbol), length - original.length() ), new TextOf(original) ); } ) ); } } cactoos-0.49/src/main/java/org/cactoos/text/PrefixOf.java000066400000000000000000000044151400054650300233310ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.text; import org.cactoos.Text; import org.cactoos.func.FuncOf; import org.cactoos.scalar.Constant; import org.cactoos.scalar.ScalarOf; import org.cactoos.scalar.Ternary; /** * Returns a text that is before given boundary. * *

There is no thread-safety guarantee. * * @since 1.0 */ public final class PrefixOf extends TextEnvelope { /** * Ctor. * @param text Text representing the text value * @param boundary String to which text will be split */ public PrefixOf(final String text, final String boundary) { this(new TextOf(text), boundary); } /** * Ctor. * @param text Text representing the text value * @param boundary String to which text will be split */ public PrefixOf(final Text text, final String boundary) { super( new Flattened( new Ternary<>( new ScalarOf<>(() -> new Sticky(text)), (Text t) -> t.asString().indexOf(boundary) >= 0, t -> new Sub(t, 0, s -> s.indexOf(boundary)), t -> t ) ) ); } } cactoos-0.49/src/main/java/org/cactoos/text/Randomized.java000066400000000000000000000113511400054650300237000ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.text; import java.security.SecureRandom; import java.util.List; import java.util.Random; import org.cactoos.Scalar; import org.cactoos.list.ListOf; /** * Randomized text. * *

There is no thread-safety guarantee. * * @since 0.32 */ public final class Randomized extends TextEnvelope { /** * Max length of generated text (if no length is specified). */ private static final int MAX_RANDOM_LENGTH = 255; /** * Ctor. */ public Randomized() { this( () -> new SecureRandom().nextInt( Randomized.MAX_RANDOM_LENGTH - 1 ) + 1 ); } /** * Ctor. * @param len Length of generated text. */ public Randomized(final Integer len) { this(() -> len); } /** * Ctor. * @param len Length of generated text. */ public Randomized(final Scalar len) { this( new ListOf<>( '!', '"', '#', '$', '%', '&', '\'', '(', ')', '*', '+', ',', '-', '.', '/', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ':', ';', '<', '=', '>', '?', '@', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '[', '\\', ']', '^', '_', '`', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '{', '|', '}', '~' ), len ); } /** * Ctor. * @param chrs Array of characters allowed for generating. */ public Randomized(final Character... chrs) { this(new ListOf<>(chrs)); } /** * Ctor. * @param chrs List of characters allowed for generating. */ public Randomized(final List chrs) { this( chrs, () -> new SecureRandom().nextInt( Randomized.MAX_RANDOM_LENGTH - 1 ) + 1 ); } /** * Ctor. * @param len Length of generated text. * @param chrs Array of characters allowed for generating. */ public Randomized(final Integer len, final Character... chrs) { this(() -> len, chrs); } /** * Ctor. * @param len Length of generated text. * @param chrs Array of characters allowed for generating. */ public Randomized(final Scalar len, final Character... chrs) { this(new ListOf<>(chrs), len); } /** * Ctor. * @param chrs List of characters allowed for generating. * @param len Length of generated text. */ public Randomized(final List chrs, final Scalar len) { this(chrs, len, new SecureRandom()); } /** * Ctor. * @param chrs List of characters allowed for generating. * @param len Length of generated text. * @param rnd Characters index randomizer. */ public Randomized(final List chrs, final Scalar len, final Random rnd) { super( new TextOf( () -> { final int length = len.value(); final StringBuilder builder = new StringBuilder(length); final int bound = chrs.size(); for (int index = 0; index < length; index = index + 1) { builder.append(chrs.get(rnd.nextInt(bound))); } return builder.toString(); } ) ); } } cactoos-0.49/src/main/java/org/cactoos/text/Repeated.java000066400000000000000000000040601400054650300233340ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.text; import org.cactoos.Text; /** * Repeat an text count times. * *

There is no thread-safety guarantee. * * @since 0.9 */ public final class Repeated extends TextEnvelope { /** * Ctor. * @param text A String * @param count How many times repeat the Text */ public Repeated(final String text, final int count) { this(new TextOf(text), count); } /** * Ctor. * @param text The Text * @param count How many times repeat the Text */ public Repeated(final Text text, final int count) { super( new TextOf( () -> { final StringBuilder out = new StringBuilder(); for (int cnt = 0; cnt < count; ++cnt) { out.append(text.asString()); } return out.toString(); } ) ); } } cactoos-0.49/src/main/java/org/cactoos/text/Replaced.java000066400000000000000000000071231400054650300233250ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.text; import java.io.IOException; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; import org.cactoos.Func; import org.cactoos.Scalar; import org.cactoos.Text; /** * Replace the Text. * * @since 0.2 */ public final class Replaced extends TextEnvelope { /** * Ctor. *

* Will replace all instances of the substring matched by {@code find} * with {@code replace}. * @param text The text * @param find The regular expression * @param replace The replacement string */ public Replaced( final Text text, final String find, final String replace ) { this(text, () -> Pattern.compile(find), matcher -> replace); } /** * Ctor. *

* The given {@link Pattern regex} is used to produce a * {@link Pattern#matcher(java.lang.CharSequence) matcher} that will be * transformed by {@code func} into a replacement string to replace each * {@link Matcher#find() matching} substring. *

* Example usage: *

{@code
     * final String result = new Replaced(
     *      new TextOf("one two THREE four FIVE six"),
     *      () -> Pattern.compile("[a-z]+"),
     *      matcher -> String.valueOf(matcher.group().length())
     * ).asString();  //will return the string "3 3 THREE 4 FIVE 3"
     * }
*

* Note: a {@link PatternSyntaxException} will be thrown if the * regular expression's syntax is invalid. * @param text The text * @param regex The regular expression * @param func Transforms the resulting matcher object into a replacement * string. Any exceptions will be wrapped in an {@link IOException}. */ public Replaced( final Text text, final Scalar regex, final Func func ) { super( new Mapped( str -> { final StringBuffer buffer = new StringBuffer(); final Matcher matcher = regex.value().matcher(str); while (matcher.find()) { matcher.appendReplacement( buffer, func.apply(matcher) ); } matcher.appendTail(buffer); return buffer.toString(); }, text ) ); } } cactoos-0.49/src/main/java/org/cactoos/text/Reversed.java000066400000000000000000000030471400054650300233660ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.text; import org.cactoos.Text; /** * Reverse the Text. * * @since 0.2 */ public final class Reversed extends TextEnvelope { /** * Ctor. * * @param text The text */ public Reversed(final Text text) { super( new Mapped( string -> new StringBuilder(string).reverse().toString(), text ) ); } } cactoos-0.49/src/main/java/org/cactoos/text/Rotated.java000066400000000000000000000044031400054650300232060ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.text; import org.cactoos.Text; /** * Rotate (circular shift) a String of shift characters. * @since 0.12 */ public final class Rotated extends TextEnvelope { /** * Ctor. * @param text The text * @param shift The shift */ public Rotated(final Text text, final int shift) { super( new Mapped( origin -> { final int length = origin.length(); if (length != 0 && shift != 0 && shift % length != 0) { final StringBuilder builder = new StringBuilder(length); int offset = -(shift % length); if (offset < 0) { offset = origin.length() + offset; } origin = builder.append( origin.substring(offset) ).append( origin.substring(0, offset) ).toString(); } return origin; }, text ) ); } } cactoos-0.49/src/main/java/org/cactoos/text/Split.java000066400000000000000000000071601400054650300227020ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.text; import org.cactoos.Text; import org.cactoos.iterable.IterableEnvelope; import org.cactoos.iterable.IterableOf; import org.cactoos.iterable.Mapped; import org.cactoos.iterator.IteratorOf; /** * Split the Text. * * @see String#split(String) * @see String#split(String, int) * @since 0.9 */ public final class Split extends IterableEnvelope { /** * Ctor. * * @param text The text * @param rgx The regex * @see String#split(String) */ public Split(final String text, final String rgx) { this(new TextOf(text), new TextOf(rgx)); } /** * Ctor. * * @param text The text * @param rgx The regex * @param lmt The limit * @see String#split(String, int) */ public Split(final String text, final String rgx, final int lmt) { this(new TextOf(text), new TextOf(rgx), lmt); } /** * Ctor. * @param text The text * @param rgx The regex * @see String#split(String) */ public Split(final String text, final Text rgx) { this(new TextOf(text), rgx); } /** * Ctor. * @param text The text * @param rgx The regex * @param lmt The limit * @see String#split(String, int) */ public Split(final String text, final Text rgx, final int lmt) { this(new TextOf(text), rgx, lmt); } /** * Ctor. * @param text The text * @param rgx The regex * @see String#split(String) */ public Split(final Text text, final String rgx) { this(text, new TextOf(rgx)); } /** * Ctor. * @param text The text * @param rgx The regex * @param lmt The limit * @see String#split(String, int) */ public Split(final Text text, final String rgx, final int lmt) { this(text, new TextOf(rgx), lmt); } /** * Ctor. * @param text The text * @param rgx The regex * @see String#split(String) */ public Split(final Text text, final Text rgx) { this(text, rgx, 0); } /** * Ctor. * @param text The text * @param rgx The regex * @param lmt The limit * @see String#split(String, int) */ public Split(final Text text, final Text rgx, final int lmt) { super( new Mapped<>( TextOf::new, new IterableOf<>( () -> new IteratorOf<>(text.asString().split(rgx.asString(), lmt)) ) ) ); } } cactoos-0.49/src/main/java/org/cactoos/text/StartsWith.java000066400000000000000000000041151400054650300237200ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.text; import org.cactoos.Scalar; import org.cactoos.Text; /** * Determines if text starts with a given prefix. * *

There is no thread-safety guarantee. * * @since 0.44 */ public final class StartsWith implements Scalar { /** * The text. */ private final Text text; /** * The prefix. */ private final Text prefix; /** * Ctor. * * @param text The text * @param prefix The prefix */ public StartsWith(final Text text, final Text prefix) { this.text = text; this.prefix = prefix; } /** * Ctor. * * @param text The text * @param prefix The prefix */ public StartsWith(final String text, final String prefix) { this(new TextOf(text), new TextOf(prefix)); } @Override public Boolean value() throws Exception { return this.text.asString().startsWith(this.prefix.asString()); } } cactoos-0.49/src/main/java/org/cactoos/text/Sticky.java000066400000000000000000000034741400054650300230610ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.text; import org.cactoos.Scalar; import org.cactoos.Text; /** * Cached version of a Text. * *

This {@link Text} decorator technically is an in-memory * cache.

* *

There is no thread-safety guarantee. * * @see org.cactoos.scalar.Sticky * @since 0.47 */ public final class Sticky implements Text { /** * Sticky scalar. */ private final Scalar scalar; /** * Ctor. * @param txt Text to cache */ public Sticky(final Text txt) { this.scalar = new org.cactoos.scalar.Sticky<>(txt::asString); } @Override public String asString() throws Exception { return this.scalar.value(); } } cactoos-0.49/src/main/java/org/cactoos/text/Strict.java000066400000000000000000000045461400054650300230640ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.text; import java.util.regex.Pattern; import org.cactoos.Func; import org.cactoos.Text; /** * Validates encapsulated text using predicate * *

There is no thread-safety guarantee. * * @since 1.0 */ public final class Strict extends TextEnvelope { /** * Ctor. * @param pattern The Pattern for validating encapsulated text * @param origin The Text */ public Strict(final Pattern pattern, final Text origin) { this(str -> pattern.matcher(str).matches(), origin); } /** * Ctor. * @param predicate The Func as a predicate * @param origin The Text */ public Strict(final Func predicate, final Text origin) { super( new Mapped( str -> { if (!predicate.apply(str)) { throw new IllegalArgumentException( new FormattedText( "String '%s' does not match a given predicate", str ).asString() ); } return str; }, origin ) ); } } cactoos-0.49/src/main/java/org/cactoos/text/Sub.java000066400000000000000000000114011400054650300223310ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.text; import org.cactoos.Func; import org.cactoos.Scalar; import org.cactoos.Text; import org.cactoos.func.FuncOf; import org.cactoos.scalar.Constant; /** * Extract a substring from a Text. * *

There is no thread-safety guarantee. * @since 0.11 */ public final class Sub extends TextEnvelope { /** * Ctor. * @param text The String * @param strt Start position in the text */ public Sub(final String text, final int strt) { this(new TextOf(text), strt); } /** * Ctor. * @param text The String * @param strt Start position in the text * @param finish End position in the text */ public Sub(final String text, final int strt, final int finish) { this(new TextOf(text), strt, finish); } /** * Ctor. * @param text The Text * @param strt Start position in the text */ public Sub(final Text text, final int strt) { this(text, new Constant<>(strt)); } /** * Ctor. * @param text The Text * @param strt Start position in the text */ public Sub(final Text text, final Scalar strt) { this(text, new FuncOf<>(strt)); } /** * Ctor. * @param text The Text * @param strt Start position in the text */ public Sub(final Text text, final Func strt) { this(text, strt, String::length); } /** * Ctor. * @param text The Text * @param strt Start position in the text * @param finish End position in the text */ public Sub(final Text text, final int strt, final int finish) { this(text, new Constant<>(strt), new Constant<>(finish)); } /** * Ctor. * @param text The Text * @param strt Start position in the text * @param finish End position in the text */ public Sub(final Text text, final int strt, final Scalar finish) { this(text, new Constant<>(strt), finish); } /** * Ctor. * @param text The Text * @param strt Start position in the text * @param finish End position in the text */ public Sub(final Text text, final int strt, final Func finish) { this(text, new Constant<>(strt), finish); } /** * Ctor. * @param text The Text * @param strt Start position in the text * @param finish End position in the text */ public Sub(final Text text, final Scalar strt, final Scalar finish) { this(text, new FuncOf<>(strt), new FuncOf<>(finish)); } /** * Ctor. * @param text The Text * @param strt Start position in the text * @param finish End position in the text */ public Sub(final Text text, final Scalar strt, final Func finish) { this(text, new FuncOf<>(strt), finish); } /** * Ctor. * @param text The Text * @param start Start position in the text * @param end End position in the text */ public Sub(final Text text, final Func start, final Func end) { super( new Mapped( origin -> { int begin = start.apply(origin); if (begin < 0) { begin = 0; } int finish = end.apply(origin); if (origin.length() < finish) { finish = origin.length(); } return origin.substring(begin, finish); }, text ) ); } } cactoos-0.49/src/main/java/org/cactoos/text/SuffixOf.java000066400000000000000000000044621400054650300233420ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.text; import org.cactoos.Text; import org.cactoos.scalar.ScalarOf; import org.cactoos.scalar.Ternary; /** * Returns a text that is after given boundary. * *

There is no thread-safety guarantee. * * @since 1.0 */ public final class SuffixOf extends TextEnvelope { /** * Ctor. * @param text Text representing the text value * @param boundary String after which text will be split */ public SuffixOf(final String text, final String boundary) { this(new TextOf(text), boundary); } /** * Ctor. * @param text Text representing the text value * @param boundary String after which text will be split */ public SuffixOf(final Text text, final String boundary) { super( new Flattened( new Ternary<>( new ScalarOf<>(() -> new Sticky(text)), (Text t) -> t.asString().indexOf(boundary) >= 0, t -> new Sub( t, s -> s.indexOf(boundary) + boundary.length() ), t -> new TextOf("") ) ) ); } } cactoos-0.49/src/main/java/org/cactoos/text/SwappedCase.java000066400000000000000000000041751400054650300240110ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.text; import org.cactoos.Text; /** * Swaps the case of a Text changing upper and title case to lower case, * and lower case to upper case. * @since 0.13.3 */ public final class SwappedCase extends TextEnvelope { /** * Ctor. * @param text The text */ public SwappedCase(final Text text) { super( new Mapped( origin -> { final char[] chars = origin.toCharArray(); for (int idx = 0; idx < chars.length; idx += 1) { final char chr = chars[idx]; if (Character.isUpperCase(chr)) { chars[idx] = Character.toLowerCase(chr); } else if (Character.isLowerCase(chr)) { chars[idx] = Character.toUpperCase(chr); } } return new String(chars); }, text ) ); } } cactoos-0.49/src/main/java/org/cactoos/text/Synced.java000066400000000000000000000032661400054650300230370ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.text; import org.cactoos.Text; /** * Text that is thread-safe. * *

Objects of this class are thread safe.

* * @since 0.18 */ public final class Synced extends TextEnvelope { /** * Ctor. * @param text The text */ public Synced(final Text text) { this(text, text); } /** * Ctor. * @param text The text * @param lck The lock */ public Synced(final Text text, final Object lck) { super(new TextOf(new org.cactoos.scalar.Synced<>(text::asString, lck))); } } cactoos-0.49/src/main/java/org/cactoos/text/TextEnvelope.java000066400000000000000000000037331400054650300242330ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.text; import org.cactoos.Text; /** * {@link Text} envelope. * * @since 0.32 * @checkstyle AbstractClassNameCheck (500 lines) */ public abstract class TextEnvelope implements Text { /** * Wrapped Text. */ private final Text origin; /** * Ctor. * @param text Text representing the text value. */ public TextEnvelope(final Text text) { this.origin = text; } @Override public final String asString() throws Exception { return this.origin.asString(); } @Override public final String toString() { return this.origin.toString(); } @Override public final boolean equals(final Object obj) { return this.origin.equals(obj); } @Override public final int hashCode() { return this.origin.hashCode(); } } cactoos-0.49/src/main/java/org/cactoos/text/TextOf.java000066400000000000000000000406441400054650300230240ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.text; import java.io.File; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.net.URI; import java.net.URL; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.nio.file.Path; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.time.OffsetDateTime; import java.time.ZoneId; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.util.Date; import java.util.Iterator; import java.util.Locale; import org.cactoos.Bytes; import org.cactoos.Input; import org.cactoos.Scalar; import org.cactoos.Text; import org.cactoos.bytes.BytesOf; import org.cactoos.io.InputOf; import org.cactoos.iterable.Mapped; import org.cactoos.scalar.And; import org.cactoos.scalar.Or; import org.cactoos.scalar.Unchecked; import org.cactoos.time.Iso; /** * TextOf * *

There is no thread-safety guarantee. * * @since 0.12 * @todo #1287:30min Introduce `Text` implementations `TextOfScalar`, * `TextOfBytes` and `TextOfDateTime` (i.e., for all of the constructor * below that delegates to a `Scalar`) and have `TextOf` extends `TextEnvelope` * to delegate to those new classes. If possible remove the checkstyle exclusions * below. * @checkstyle ClassDataAbstractionCouplingCheck (1000 lines) * @checkstyle ClassFanOutComplexityCheck (1000 lines) */ public final class TextOf implements Text { /** * String value of the envelope. */ private final Scalar origin; /** * Ctor. * * @param input The Input */ public TextOf(final Input input) { this(new BytesOf(input)); } /** * Ctor. * @param url The URL * @since 0.16 */ public TextOf(final URL url) { this(new InputOf(url)); } /** * Ctor. * @param uri The URI * @since 0.16 */ public TextOf(final URI uri) { this(new InputOf(uri)); } /** * Ctor. * @param path The Input * @since 0.13 */ public TextOf(final Path path) { this(new InputOf(path)); } /** * Ctor. * @param file The Input * @since 0.13 */ public TextOf(final File file) { this(new InputOf(file)); } /** * Ctor. * * @param input The input * @param max Max length of the buffer for reading */ public TextOf(final Input input, final int max) { this(input, max, StandardCharsets.UTF_8); } /** * Ctor. * * @param input The Input * @param cset The Charset */ public TextOf(final Input input, final Charset cset) { this(new BytesOf(input), cset); } /** * Ctor. * * @param input The Input * @param cset The Charset */ public TextOf(final Input input, final String cset) { this(new BytesOf(input), cset); } /** * Ctor. * * @param input The input * @param max Max length of the buffer for reading * @param cset The Charset */ public TextOf(final Input input, final int max, final Charset cset) { this(new BytesOf(input, max), cset); } /** * Ctor. * * @param rdr Reader */ public TextOf(final Reader rdr) { this(new BytesOf(rdr)); } /** * Ctor. * @param rdr Reader * @param cset Charset */ public TextOf(final Reader rdr, final Charset cset) { this(new BytesOf(rdr, cset)); } /** * Ctor. * @param rdr Reader * @param max Buffer size * @param cset Charset */ public TextOf(final Reader rdr, final int max, final Charset cset) { this(new BytesOf(rdr, cset, max)); } /** * Ctor. * * @param builder The String builder */ public TextOf(final CharSequence builder) { this(new BytesOf(builder)); } /** * Ctor. * * @param builder The String builder * @param cset The Charset */ public TextOf(final CharSequence builder, final Charset cset) { this(new BytesOf(builder, cset), cset); } /** * Ctor. * * @param chars The chars */ public TextOf(final char... chars) { this(new BytesOf(chars)); } /** * Ctor. * * @param chars The chars * @param cset The charset */ public TextOf(final char[] chars, final Charset cset) { this(new BytesOf(chars, cset)); } /** * Ctor. * @param error The exception to serialize */ public TextOf(final Throwable error) { this(new BytesOf(error)); } /** * Ctor. * @param error The exception to serialize * @param charset Charset * @since 0.29 */ public TextOf(final Throwable error, final Charset charset) { this(new BytesOf(error, charset)); } /** * Ctor. * @param error The exception to serialize * @param charset Charset * @since 0.29 */ public TextOf(final Throwable error, final CharSequence charset) { this(new BytesOf(error, charset)); } /** * Ctor. * @param strace The stacktrace to serialize * @since 0.29 */ public TextOf(final StackTraceElement... strace) { this(new BytesOf(strace)); } /** * Ctor. * @param strace The stacktrace to serialize * @param charset Charset * @since 0.29 */ public TextOf(final StackTraceElement[] strace, final Charset charset) { this(new BytesOf(strace, charset)); } /** * Ctor. * @param strace The stacktrace to serialize * @param charset Charset * @since 0.29 */ public TextOf(final StackTraceElement[] strace, final CharSequence charset) { this(new BytesOf(strace, charset)); } /** * Ctor. * * @param bytes The array of bytes */ public TextOf(final byte... bytes) { this(new BytesOf(bytes)); } /** * Ctor. * * @param bytes The Bytes */ public TextOf(final Bytes bytes) { this(bytes, StandardCharsets.UTF_8); } /** * Ctor. * * @param bytes The Bytes * @param cset The Charset */ public TextOf(final Bytes bytes, final Charset cset) { this(() -> new String(bytes.asBytes(), cset)); } /** * Ctor. * * @param bytes The Bytes * @param cset The Charset */ public TextOf(final Bytes bytes, final String cset) { this(() -> new String(bytes.asBytes(), cset)); } /** * Ctor. * * @param input The String */ public TextOf(final String input) { this(input, StandardCharsets.UTF_8); } /** * Ctor. * * @param input The String * @param cset The Charset */ public TextOf(final String input, final Charset cset) { this(() -> new String(input.getBytes(cset), cset)); } /** * Ctor. * @param iterable The iterable to convert to string * @since 0.21 */ public TextOf(final Iterable iterable) { this( () -> new Joined( ", ", new Mapped<>( Object::toString, iterable ) ).asString() ); } /** * Ctor. * * @param iterator The iterable to convert to string */ public TextOf(final Iterator iterator) { this( () -> { final StringBuilder buf = new StringBuilder(); iterator.forEachRemaining(buf::append); return buf.toString(); } ); } /** * Ctor. * * @param input The InputStream where the text is read from * @since 0.21 */ public TextOf(final InputStream input) { this(new InputOf(new InputStreamReader(input, StandardCharsets.UTF_8))); } /** * Formats date using ISO date time format. * @param date The date to format. * @since 1.0 */ public TextOf(final LocalDate date) { this(date, new Iso().value()); } /** * Formats date using provided date time format string using default locale. * @param date The date to format. * @param format The format to use. * @since 1.0 */ public TextOf(final LocalDate date, final String format) { this(date, format, Locale.getDefault(Locale.Category.FORMAT)); } /** * Formats the date using the provided format string using the provided * locale. * @param date The date to format. * @param format The format string to use. * @param locale The locale to use. * @since 1.0 */ public TextOf( final LocalDate date, final String format, final Locale locale ) { this(date, DateTimeFormatter.ofPattern(format, locale)); } /** * Formats the date using the provided formatter. * @param date The date to format. * @param formatter The formatter to use. * @since 1.0 */ public TextOf(final LocalDate date, final DateTimeFormatter formatter) { this( () -> formatter.format( ZonedDateTime.of( date, LocalTime.MIN, ZoneId.systemDefault() ) ) ); } /** * Formats the date using the provided formatter. * @param date The date to format. * @param formatter The formatter to use. */ public TextOf( final LocalDateTime date, final DateTimeFormatter formatter ) { this(() -> formatter.format(date.atZone(ZoneId.systemDefault()))); } /** * Formats date using ISO date time format. * @param date The date to format. */ public TextOf(final LocalDateTime date) { this(date, new Iso().value()); } /** * Formats date using provided date time format string using default locale. * @param date The date to format. * @param format The format to use. */ public TextOf(final LocalDateTime date, final String format) { this(date, format, Locale.getDefault(Locale.Category.FORMAT)); } /** * Formats the date using the provided format string using the provided * locale. * @param date The date to format. * @param format The format string to use. * @param locale The locale to use. */ public TextOf( final LocalDateTime date, final String format, final Locale locale ) { this(date, DateTimeFormatter.ofPattern(format, locale)); } /** * Formats the date with ISO format using the system zone. * @param date The date to format. */ public TextOf(final Date date) { this(date, new Iso().value()); } /** * Formats the date with to format using the default locale and the system * zone. * @param date The date to format. * @param format The format to use. */ public TextOf(final Date date, final String format) { this(date, format, Locale.getDefault(Locale.Category.FORMAT)); } /** * Formats the date using the format and locale using the system default * zone. * @param date The date to format. * @param format The format to use. * @param locale The locale to use. */ public TextOf( final Date date, final String format, final Locale locale ) { this(date, DateTimeFormatter.ofPattern(format, locale)); } /** * Formats the date using the format and locale using the system default * zone. * @param date The date to format. * @param formatter The formatter to use. */ public TextOf(final Date date, final DateTimeFormatter formatter) { this( () -> formatter.format( ZonedDateTime.ofInstant( date.toInstant(), ZoneId.systemDefault() ) ) ); } /** * Formats date using ISO date time format. * @param date The date to format. */ public TextOf(final OffsetDateTime date) { this(date, new Iso().value()); } /** * Formats date using provided date time format string using default locale. * @param date The date to format. * @param format The format to use. */ public TextOf(final OffsetDateTime date, final String format) { this(date, format, Locale.getDefault(Locale.Category.FORMAT)); } /** * Formats the date using the provided format string using the provided * locale. * @param date The date to format. * @param format The format string to use. * @param locale The locale to use. */ public TextOf( final OffsetDateTime date, final String format, final Locale locale ) { this(date, DateTimeFormatter.ofPattern(format, locale)); } /** * Formats the date using the provided formatter. * @param date The date to format. * @param formatter The formatter to use. */ public TextOf( final OffsetDateTime date, final DateTimeFormatter formatter ) { this(() -> formatter.format(date)); } /** * Formats date using ISO date time format. * @param date The date to format. */ public TextOf(final ZonedDateTime date) { this(date, new Iso().value()); } /** * Formats date using provided date time format string using default locale. * @param date The date to format. * @param format The format to use. */ public TextOf(final ZonedDateTime date, final String format) { this(date, format, Locale.getDefault(Locale.Category.FORMAT)); } /** * Formats the date using the provided format string using the provided * locale. * @param date The date to format. * @param format The format string to use. * @param locale The locale to use. */ public TextOf( final ZonedDateTime date, final String format, final Locale locale ) { this(date, DateTimeFormatter.ofPattern(format, locale)); } /** * Formats the date using the provided formatter. * @param date The date to format. * @param formatter The formatter to use. */ public TextOf( final ZonedDateTime date, final DateTimeFormatter formatter ) { this(() -> formatter.format(date)); } /** * Ctor. * * @param scalar The Scalar of String */ public TextOf(final Scalar scalar) { this.origin = scalar; } @Override public String asString() throws Exception { return this.origin.value(); } @Override public String toString() { return new UncheckedText(this).asString(); } @Override public int hashCode() { return new Unchecked<>(this.origin).value().hashCode(); } @Override @edu.umd.cs.findbugs.annotations.SuppressFBWarnings("EQ_UNUSUAL") public boolean equals(final Object obj) { return new Unchecked<>( new Or( () -> this == obj, new And( () -> obj instanceof Text, () -> new UncheckedText(this) .asString() .equals(new UncheckedText((Text) obj).asString()) ) ) ).value(); } } cactoos-0.49/src/main/java/org/cactoos/text/Trimmed.java000066400000000000000000000030231400054650300232020ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.text; import org.cactoos.Text; /** * Text without control characters (char <= 32) from both ends. * *

* There is no thread-safety guarantee. * * @since 0.1 */ public final class Trimmed extends TextEnvelope { /** * Ctor. * @param text The text */ public Trimmed(final Text text) { super(new Mapped(str -> str.trim(), text)); } } cactoos-0.49/src/main/java/org/cactoos/text/TrimmedLeft.java000066400000000000000000000037241400054650300240250ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.text; import org.cactoos.Text; /** * Text without control characters (char <= 32) only from left. * *

* There is no thread-safety guarantee. * * @since 0.12 */ public final class TrimmedLeft extends TextEnvelope { /** * Ctor. * @param text The text */ public TrimmedLeft(final Text text) { super( new Mapped( string -> { int cursor = 0; while ( cursor < string.length() && Character.isWhitespace( string.charAt(cursor) ) ) { cursor = cursor + 1; } return string.substring(cursor); }, text ) ); } } cactoos-0.49/src/main/java/org/cactoos/text/TrimmedRight.java000066400000000000000000000035731400054650300242120ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.text; import org.cactoos.Text; /** * Text without control characters (char <= 32) only from right. * *

There is no thread-safety guarantee. * * @since 0.12 */ public final class TrimmedRight extends TextEnvelope { /** * Ctor. * @param text The text */ public TrimmedRight(final Text text) { super( new Mapped( string -> { int cursor = string.length() - 1; while (cursor >= 0 && Character.isWhitespace(string.charAt(cursor))) { cursor = cursor - 1; } return string.substring(0, cursor + 1); }, text ) ); } } cactoos-0.49/src/main/java/org/cactoos/text/UncheckedText.java000066400000000000000000000066271400054650300243540ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.text; import org.cactoos.Func; import org.cactoos.Text; import org.cactoos.func.UncheckedFunc; import org.cactoos.scalar.And; import org.cactoos.scalar.Or; import org.cactoos.scalar.Unchecked; /** * Text that doesn't throw checked {@link Exception}. * *

There is no thread-safety guarantee. * * @since 0.3 */ public final class UncheckedText implements Text { /** * Original text. */ private final Text text; /** * Fallback. */ private final Func fallback; /** * Ctor. * @param txt Encapsulated text * @since 0.9 */ public UncheckedText(final String txt) { this(new TextOf(txt)); } /** * Ctor. * @param txt Encapsulated text */ @SuppressWarnings("PMD.AvoidThrowingRawExceptionTypes") public UncheckedText(final Text txt) { this( txt, error -> { throw new RuntimeException(error); } ); } /** * Ctor. * @param txt Encapsulated text * @param fbk Fallback func if {@link Exception} happens * @since 0.5 */ public UncheckedText(final Text txt, final Func fbk) { this.text = txt; this.fallback = fbk; } @Override @SuppressWarnings("PMD.AvoidCatchingGenericException") public String asString() { String txt; try { txt = this.text.asString(); // @checkstyle IllegalCatchCheck (1 line) } catch (final Exception ex) { txt = new UncheckedFunc<>(this.fallback).apply(ex); } return txt; } @Override public String toString() { return this.asString(); } @Override @edu.umd.cs.findbugs.annotations.SuppressFBWarnings("EQ_UNUSUAL") public boolean equals(final Object obj) { return new Unchecked<>( new Or( () -> this == obj, new And( () -> obj instanceof Text, () -> this.asString().equals( Text.class.cast(obj).asString() ) ) ) ).value(); } @Override public int hashCode() { return this.asString().hashCode(); } } cactoos-0.49/src/main/java/org/cactoos/text/Upper.java000066400000000000000000000035101400054650300226750ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.text; import java.util.Locale; import org.cactoos.Text; /** * Text in upper case. * *

* There is no thread-safety guarantee. * * @since 0.1 */ public final class Upper extends TextEnvelope { /** * Ctor. * @param text The text */ public Upper(final String text) { this(new TextOf(text)); } /** * Ctor. * @param text The text */ public Upper(final Text text) { this(text, Locale.ENGLISH); } /** * Ctor. * @param text The text * @param locale Locale */ public Upper(final Text text, final Locale locale) { super(new Mapped(str -> str.toUpperCase(locale), text)); } } cactoos-0.49/src/main/java/org/cactoos/text/package-info.java000066400000000000000000000022771400054650300241370ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ /** * Text. * * @since 0.1 */ package org.cactoos.text; cactoos-0.49/src/main/java/org/cactoos/time/000077500000000000000000000000001400054650300207125ustar00rootroot00000000000000cactoos-0.49/src/main/java/org/cactoos/time/DateOf.java000066400000000000000000000054501400054650300227230ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.time; import java.time.LocalDateTime; import java.time.ZoneOffset; import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatterBuilder; import java.time.temporal.ChronoField; import java.util.Date; import org.cactoos.Scalar; import org.cactoos.scalar.Unchecked; /** * Parser for {@link Date} instances. * @since 0.27 */ public final class DateOf implements Scalar { /** * The parsed date. */ private final Unchecked parsed; /** * Parses the provided date as ISO formatted. * @param date The date to parse. */ public DateOf(final CharSequence date) { this(date, new Iso().value()); } /** * Parses the date using the provided format. * @param date The date to parse. * @param format The format to use. */ public DateOf(final CharSequence date, final String format) { this(date, DateTimeFormatter.ofPattern(format)); } /** * Parsing the date using the provided formatter. * @param date The date to parse. * @param formatter The formatter to use. */ public DateOf(final CharSequence date, final DateTimeFormatter formatter) { this.parsed = new Unchecked<>( () -> Date.from( LocalDateTime.parse( date, new DateTimeFormatterBuilder() .append(formatter) .parseDefaulting(ChronoField.HOUR_OF_DAY, 0) .toFormatter() ).toInstant(ZoneOffset.UTC) ) ); } @Override public Date value() { return this.parsed.value(); } } cactoos-0.49/src/main/java/org/cactoos/time/Iso.java000066400000000000000000000027021400054650300223100ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.time; import java.time.format.DateTimeFormatter; import org.cactoos.Scalar; /** * The formatter. * @since 0.27 */ public final class Iso implements Scalar { @Override public DateTimeFormatter value() { return DateTimeFormatter.ISO_OFFSET_DATE_TIME; } } cactoos-0.49/src/main/java/org/cactoos/time/LocalDateTimeOf.java000066400000000000000000000050541400054650300245150ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.time; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import org.cactoos.Scalar; import org.cactoos.scalar.Unchecked; /** * Parser for {@link LocalDateTime} instances. * @since 0.27 */ public final class LocalDateTimeOf implements Scalar { /** * The parsed date. */ private final Unchecked parsed; /** * Parses ISO date to create {@link LocalDateTime} instances. * @param date The date to parse. */ public LocalDateTimeOf(final CharSequence date) { this(date, new Iso().value()); } /** * Parses date using the provided format to create * {@link LocalDateTime} instances. * @param date The date to parse. * @param format The format to use. */ public LocalDateTimeOf(final CharSequence date, final String format) { this(date, DateTimeFormatter.ofPattern(format)); } /** * Parses the date using the formatter to create * {@link LocalDateTime} instances. * @param date The date to parse. * @param formatter The formatter to use. */ public LocalDateTimeOf(final CharSequence date, final DateTimeFormatter formatter) { this.parsed = new Unchecked<>( () -> LocalDateTime.from(formatter.parse(date)) ); } @Override public LocalDateTime value() { return this.parsed.value(); } } cactoos-0.49/src/main/java/org/cactoos/time/OffsetDateTimeOf.java000066400000000000000000000054041400054650300247100ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.time; import java.time.OffsetDateTime; import java.time.ZoneOffset; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import org.cactoos.Scalar; import org.cactoos.scalar.Unchecked; /** * Parser for {@link OffsetDateTime} instances. * @since 0.27 */ public final class OffsetDateTimeOf implements Scalar { /** * The parsed date. */ private final Unchecked parsed; /** * Parses ISO date to create {@link OffsetDateTime} instances. * @param date The date to parse. */ public OffsetDateTimeOf(final CharSequence date) { this(date, new Iso().value()); } /** * Parses date using the provided format to create * {@link OffsetDateTime} instances. * @param date The date to parse. * @param format The format to use. * @param offset The offset to use. */ public OffsetDateTimeOf(final CharSequence date, final String format, final ZoneOffset offset) { this(date, DateTimeFormatter.ofPattern(format).withZone(offset.normalized()) ); } /** * Parses the date using the formatter to create * {@link OffsetDateTime} instances. * @param date The date to parse. * @param formatter The formatter to use. */ public OffsetDateTimeOf(final CharSequence date, final DateTimeFormatter formatter) { this.parsed = new Unchecked<>( () -> ZonedDateTime.from(formatter.parse(date)).toOffsetDateTime() ); } @Override public OffsetDateTime value() { return this.parsed.value(); } } cactoos-0.49/src/main/java/org/cactoos/time/ZonedDateTimeOf.java000066400000000000000000000052171400054650300245430ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.time; import java.time.ZoneId; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import org.cactoos.Scalar; import org.cactoos.scalar.Unchecked; /** * Parser for {@link ZonedDateTime} instances. * @since 0.27 */ public final class ZonedDateTimeOf implements Scalar { /** * The parsed date. */ private final Unchecked parsed; /** * Parses date to create {@link ZonedDateTime} instances. * @param date The date to parse. */ public ZonedDateTimeOf(final CharSequence date) { this(date, new Iso().value()); } /** * Parses date using the provided format to create * {@link ZonedDateTime} instances. * @param date The date to parse. * @param format The format to use. * @param zone The zone to use. */ public ZonedDateTimeOf(final CharSequence date, final String format, final ZoneId zone) { this(date, DateTimeFormatter.ofPattern(format).withZone(zone)); } /** * Parses the date using the formatter to create * {@link ZonedDateTime} instances. * @param date The date to parse. * @param formatter The formatter to use. */ public ZonedDateTimeOf(final CharSequence date, final DateTimeFormatter formatter) { this.parsed = new Unchecked<>( () -> ZonedDateTime.from(formatter.parse(date)) ); } @Override public ZonedDateTime value() { return this.parsed.value(); } } cactoos-0.49/src/main/java/org/cactoos/time/package-info.java000066400000000000000000000022771400054650300241110ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ /** * Time. * * @since 1.0 */ package org.cactoos.time; cactoos-0.49/src/test/000077500000000000000000000000001400054650300146445ustar00rootroot00000000000000cactoos-0.49/src/test/java/000077500000000000000000000000001400054650300155655ustar00rootroot00000000000000cactoos-0.49/src/test/java/org/000077500000000000000000000000001400054650300163545ustar00rootroot00000000000000cactoos-0.49/src/test/java/org/cactoos/000077500000000000000000000000001400054650300200075ustar00rootroot00000000000000cactoos-0.49/src/test/java/org/cactoos/BytesTest.java000066400000000000000000000034041400054650300226010ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos; import org.cactoos.bytes.NoNulls; import org.junit.Test; /** * Test case for {@link NoNulls}. * @since 0.11 * @checkstyle JavadocMethodCheck (500 lines) */ public final class BytesTest { @Test(expected = IllegalArgumentException.class) public void failForNullArgument() throws Exception { new NoNulls(null).asBytes(); } @Test(expected = IllegalStateException.class) public void failForNullResult() throws Exception { new NoNulls(() -> null).asBytes(); } @Test public void okForNoNulls() throws Exception { new NoNulls(() -> new byte[1]).asBytes(); } } cactoos-0.49/src/test/java/org/cactoos/ScalarTest.java000066400000000000000000000042461400054650300227250ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos; import org.cactoos.scalar.NoNulls; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.Throws; /** * Test case for {@link NoNulls}. * @since 0.11 * @checkstyle JavadocMethodCheck (500 lines) */ final class ScalarTest { @Test void failForNullArgument() { new Assertion<>( "Must fail for null argument", () -> new NoNulls<>(null).value(), new Throws<>( "NULL instead of a valid scalar", IllegalArgumentException.class ) ).affirm(); } @Test void failForNullResult() { new Assertion<>( "Must fail for null result", () -> new NoNulls<>(() -> null).value(), new Throws<>( "NULL instead of a valid value", IllegalStateException.class ) ).affirm(); } @Test void okForNoNulls() throws Exception { new NoNulls<>(() -> 1).value(); } } cactoos-0.49/src/test/java/org/cactoos/TextTest.java000066400000000000000000000046621400054650300224460ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos; import org.cactoos.text.NoNulls; import org.cactoos.text.TextOf; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.TextHasString; import org.llorllale.cactoos.matchers.Throws; /** * Test case for {@link Text}. * @since 0.11 * @checkstyle JavadocMethodCheck (500 lines) */ final class TextTest { @Test void failForNullArgument() { new Assertion<>( "Must fail for null argument", () -> new NoNulls(null).asString(), new Throws<>( "NULL instead of a valid text", IllegalArgumentException.class ) ).affirm(); } @Test void failForNullResult() { new Assertion<>( "Must fail for null result", () -> new NoNulls(() -> null).asString(), new Throws<>( "NULL instead of a valid result string", IllegalStateException.class ) ).affirm(); } @Test void okForNoNulls() { final String message = "Hello"; new Assertion<>( "Must work with NoNulls", new NoNulls( new TextOf(message) ), new TextHasString(message) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/bytes/000077500000000000000000000000001400054650300211355ustar00rootroot00000000000000cactoos-0.49/src/test/java/org/cactoos/bytes/Base64BytesTest.java000066400000000000000000000053701400054650300247000ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.bytes; import java.util.Base64; import org.hamcrest.core.IsEqual; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; /** * Test case for {@link org.cactoos.bytes.Base64Bytes}. * * @since 0.20.2 * @checkstyle JavadocMethodCheck (500 lines) */ @SuppressWarnings("PMD.AvoidDuplicateLiterals") final class Base64BytesTest { @Test void checkDecodeBasicDecoder() throws Exception { new Assertion<>( "Must decode bytes using the Base64 encoding basic scheme", new Base64Bytes( new BytesOf( "SGVsbG8h" ) ).asBytes(), new IsEqual<>( new BytesOf("Hello!").asBytes() ) ).affirm(); } @Test void checkDecodeUrlDecoder() throws Exception { new Assertion<>( "Must decode bytes using the Base64 encoding url scheme", new Base64Bytes( new BytesOf( "SGVsbG8h" ), Base64.getUrlDecoder() ).asBytes(), new IsEqual<>( new BytesOf("Hello!").asBytes() ) ).affirm(); } @Test void checkDecodeMimeDecoder() throws Exception { new Assertion<>( "Must decode bytes using the Base64 encoding mime scheme", new Base64Bytes( new BytesOf( "SGVsbG8h" ), Base64.getMimeDecoder() ).asBytes(), new IsEqual<>( new BytesOf("Hello!").asBytes() ) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/bytes/BytesBase64Test.java000066400000000000000000000053401400054650300246750ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.bytes; import java.util.Base64; import org.hamcrest.core.IsEqual; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; /** * Test case for {@link org.cactoos.bytes.BytesBase64}. * @since 0.20.2 * @checkstyle JavadocMethodCheck (500 lines) */ @SuppressWarnings("PMD.AvoidDuplicateLiterals") final class BytesBase64Test { @Test void checkEncodeBasic() throws Exception { new Assertion<>( "Must encode bytes using the Base64 basic encoding scheme", new BytesBase64( new BytesOf( "Hello!" ) ).asBytes(), new IsEqual<>( new BytesOf("SGVsbG8h").asBytes() ) ).affirm(); } @Test void checkEncodeUrl() throws Exception { new Assertion<>( "Must encode bytes using the Base64 URL encoding scheme", new BytesBase64( new BytesOf( "Hello!" ), Base64.getUrlEncoder() ).asBytes(), new IsEqual<>( new BytesOf("SGVsbG8h").asBytes() ) ).affirm(); } @Test void checkEncodeMime() throws Exception { new Assertion<>( "Must encode bytes using the Base64 mime encoding scheme", new BytesBase64( new BytesOf( "Hello!" ), Base64.getMimeEncoder() ).asBytes(), new IsEqual<>( new BytesOf("SGVsbG8h").asBytes() ) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/bytes/BytesOfTest.java000066400000000000000000000170101400054650300242120ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.bytes; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.StringReader; import java.nio.charset.StandardCharsets; import java.util.concurrent.atomic.AtomicBoolean; import org.cactoos.Text; import org.cactoos.io.InputOf; import org.cactoos.io.Sticky; import org.cactoos.iterable.Endless; import org.cactoos.iterable.HeadOf; import org.cactoos.iterable.IterableOf; import org.cactoos.iterable.IterableOfBytes; import org.cactoos.iterator.IteratorOfBytes; import org.cactoos.text.Joined; import org.cactoos.text.TextOf; import org.hamcrest.core.AllOf; import org.hamcrest.core.IsEqual; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.EndsWith; import org.llorllale.cactoos.matchers.IsTrue; import org.llorllale.cactoos.matchers.StartsWith; import org.llorllale.cactoos.matchers.TextHasString; import org.llorllale.cactoos.matchers.TextIs; /** * Test case for {@link BytesOf}. * * @since 0.12 * @checkstyle JavadocMethodCheck (500 lines) * @checkstyle ClassDataAbstractionCouplingCheck (500 lines) */ final class BytesOfTest { @Test void readsLargeInMemoryContent() throws Exception { final int multiplier = 5_000; final String body = "1234567890"; new Assertion<>( "must read large content from in-memory Input", new BytesOf( new InputOf( new Joined( "", new HeadOf<>( multiplier, new Endless<>(body) ) ) ) ).asBytes().length, new IsEqual<>(body.length() * multiplier) ).affirm(); } @Test @SuppressWarnings("unchecked") void readsInputIntoBytes() throws Exception { new Assertion<>( "must read bytes from Input", new TextOf( new BytesOf( new InputOf("Hello, друг!") ) ), new AllOf<>( new IterableOf<>( new StartsWith("Hello, "), new EndsWith("друг!") ) ) ).affirm(); } @Test void readsFromReader() throws Exception { final String source = "hello, друг!"; new Assertion<>( "must read string through a reader", new TextOf( new Sticky( new InputOf( new BytesOf( new StringReader(source), StandardCharsets.UTF_8, // @checkstyle MagicNumberCheck (1 line) 16 << 10 ) ) ) ), new TextIs(source) ).affirm(); } @Test @SuppressWarnings("unchecked") void readsInputIntoBytesWithSmallBuffer() throws Exception { new Assertion<>( "must read bytes from Input with a small reading buffer", new TextOf( new BytesOf( new InputOf("Hello, товарищ!"), 2 ) ), new AllOf<>( new IterableOf<>( new StartsWith("Hello,"), new EndsWith("товарищ!") ) ) ).affirm(); } @Test void closesInputStream() throws Exception { final AtomicBoolean closed = new AtomicBoolean(); final InputStream input = new ByteArrayInputStream( "how are you?".getBytes() ); new TextOf( new InputOf( new InputStream() { @Override public int read() throws IOException { return input.read(); } @Override public void close() throws IOException { input.close(); closed.set(true); } } ), StandardCharsets.UTF_8 ).asString(); new Assertion<>( "must close InputStream correctly", closed.get(), new IsTrue() ).affirm(); } @Test void asBytes() throws Exception { final Text text = new TextOf("Hello!"); new Assertion<>( "Can't convert text into bytes", new BytesOf( new InputOf(text) ).asBytes(), new IsEqual<>( new BytesOf(text.asString()).asBytes() ) ).affirm(); } @Test void asBytesFromIterator() throws Exception { final Text text = new TextOf("Good bye!"); new Assertion<>( "Can't convert iterator into bytes", new BytesOf( new IteratorOfBytes(text) ).asBytes(), new IsEqual<>( new BytesOf(text).asBytes() ) ).affirm(); } @Test void asBytesFromIterable() throws Exception { final Text text = new TextOf("Good bye"); new Assertion<>( "Must convert iterable into bytes", new BytesOf( new IterableOfBytes(text) ).asBytes(), new IsEqual<>(new BytesOf(text).asBytes()) ).affirm(); } @Test void printsStackTrace() { new Assertion<>( "Can't print exception stacktrace", new TextOf( new BytesOf( new IOException( "It doesn't work at all" ) ) ), new TextHasString( new Joined( System.lineSeparator(), "java.io.IOException: It doesn't work at all", "\tat org.cactoos.bytes.BytesOfTest" ) ) ).affirm(); } @Test void printsStackTraceFromArray() { new Assertion<>( "Can't print exception stacktrace from array", new TextOf( new BytesOf( new IOException("").getStackTrace() ) ), new TextHasString("org.cactoos.bytes.BytesOfTest") ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/bytes/CheckedBytesTest.java000066400000000000000000000053321400054650300252000ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.bytes; import java.io.IOException; import org.hamcrest.core.IsNull; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.Throws; /** * Test case for {@link CheckedBytes}. * * @since 0.31 * @checkstyle JavadocMethodCheck (500 lines) */ final class CheckedBytesTest { @Test void runtimeExceptionIsNotWrapped() { new Assertion<>( "must not wrap runtime exception", new CheckedBytes<>( () -> { throw new IllegalStateException("runtime1"); }, IOException::new )::asBytes, new Throws<>(IllegalStateException.class) ).affirm(); } @Test void checkedExceptionIsWrapped() { new Assertion<>( "must wrap checked exception", new CheckedBytes<>( () -> { throw new IOException("runtime2"); }, IOException::new )::asBytes, new Throws<>(IOException.class) ).affirm(); } @Test void extraWrappingIgnored() { try { new CheckedBytes<>( () -> { throw new IOException("runtime3"); }, IOException::new ).asBytes(); } catch (final IOException exp) { new Assertion<>( "must not add extra wrapping of IOException", exp.getCause(), new IsNull<>() ).affirm(); } } } cactoos-0.49/src/test/java/org/cactoos/bytes/EmptyClosableReader.java000066400000000000000000000040561400054650300256730ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.bytes; import java.io.IOException; import java.io.Reader; import org.cactoos.io.ReaderOf; /** * Empty Closable Reader * *

Empty {@link Reader} that can tell you if it was explicitly closed by * calling {@link Reader#close()} method.

* *

This class is for internal use only. Use {@link ReaderOf} instead

* *

There is no thread-safety guarantee.

* * @since 0.29 */ final class EmptyClosableReader extends Reader { /** * Closed reader. */ private boolean closed; @Override public int read(final char[] cbuf, final int off, final int len) throws IOException { return -1; } @Override public void close() throws IOException { this.closed = true; } /** * Ask if the {@link Reader} is closed. * @return True if closed, false otherwise */ public boolean isClosed() { return this.closed; } } cactoos-0.49/src/test/java/org/cactoos/bytes/HexOfTest.java000066400000000000000000000052321400054650300236530ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.bytes; import java.io.IOException; import java.util.Arrays; import org.cactoos.text.TextOf; import org.junit.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.MatcherOf; /** * Test case for {@link HexOf}. * * @since 0.29 * @checkstyle MagicNumberCheck (500 line) * @checkstyle JavadocMethodCheck (500 line) */ public final class HexOfTest { @Test public void emptyText() throws Exception { new Assertion<>( "Must represent an empty hexadecimal text", new HexOf(new TextOf("")).asBytes(), new MatcherOf<>(array -> array.length == 0) ).affirm(); } @Test public void validHex() throws Exception { final byte[] bytes = new byte[256]; for (int index = 0; index < 256; ++index) { bytes[index] = (byte) (index + Byte.MIN_VALUE); } new Assertion<>( "Must convert hexadecimal text to bytes", new HexOf( new org.cactoos.text.HexOf( new BytesOf(bytes) ) ).asBytes(), new MatcherOf<>( (byte[] array) -> Arrays.equals(bytes, array) ) ).affirm(); } @Test(expected = IOException.class) public void invalidHexLength() throws Exception { new HexOf(new TextOf("ABF")).asBytes(); } @Test(expected = IOException.class) public void invalidHex() throws Exception { new HexOf(new TextOf("ABG!")).asBytes(); } } cactoos-0.49/src/test/java/org/cactoos/bytes/InputAsBytesTest.java000066400000000000000000000105061400054650300252340ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.bytes; import java.io.InputStream; import java.nio.charset.StandardCharsets; import org.cactoos.io.InputOf; import org.cactoos.io.SlowInputStream; import org.cactoos.iterable.Endless; import org.cactoos.iterable.HeadOf; import org.cactoos.iterable.IterableOf; import org.cactoos.text.TextOf; import org.hamcrest.core.AllOf; import org.hamcrest.core.IsEqual; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.EndsWith; import org.llorllale.cactoos.matchers.StartsWith; /** * Test case for {@link InputAsBytes}. * * @since 0.1 * @checkstyle JavadocMethodCheck (500 lines) * @checkstyle ClassDataAbstractionCouplingCheck (500 lines) */ @SuppressWarnings("unchecked") final class InputAsBytesTest { @Test void readsLargeInMemoryContent() throws Exception { final int multiplier = 5_000; final String body = "1234567890"; new Assertion<>( "must read large content from in-memory Input", new InputAsBytes( new InputOf( String.join( "", new HeadOf<>( multiplier, new Endless<>(body) ) ) ) ).asBytes().length, new IsEqual<>(body.length() * multiplier) ).affirm(); } @Test // @checkstyle AnonInnerLengthCheck (100 lines) void readsLargeContent() throws Exception { final int size = 100_000; try (InputStream slow = new SlowInputStream(size)) { new Assertion<>( "must read large content from Input", new InputAsBytes( new InputOf(slow) ).asBytes().length, new IsEqual<>(size) ).affirm(); } } @Test void readsInputIntoBytes() throws Exception { new Assertion<>( "must read bytes from Input", new TextOf( new InputAsBytes( new InputOf( new BytesOf( new TextOf("Hello, друг!") ) ) ), StandardCharsets.UTF_8 ), new AllOf<>( new IterableOf<>( new StartsWith("Hello, "), new EndsWith("друг!") ) ) ).affirm(); } @Test void readsInputIntoBytesWithSmallBuffer() throws Exception { new Assertion<>( "must read bytes from Input with a small reading buffer", new TextOf( new InputAsBytes( new InputOf( new BytesOf( new TextOf("Hello, товарищ!") ) ), 2 ), StandardCharsets.UTF_8 ), new AllOf<>( new IterableOf<>( new StartsWith("Hello,"), new EndsWith("товарищ!") ) ) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/bytes/Md5DigestOfTest.java000066400000000000000000000056321400054650300247200ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.bytes; import org.cactoos.io.InputOf; import org.cactoos.io.ResourceOf; import org.cactoos.io.Sticky; import org.cactoos.text.HexOf; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.TextHasString; /** * Test case for {@link Md5DigestOf}. * * @since 0.29 * @checkstyle JavadocMethodCheck (500 lines) */ final class Md5DigestOfTest { @Test void checksumOfEmptyString() { new Assertion<>( "Can't calculate the empty string's MD5 checksum", new HexOf( new Md5DigestOf( new InputOf("") ) ), new TextHasString( "d41d8cd98f00b204e9800998ecf8427e" ) ).affirm(); } @Test void checksumOfString() { new Assertion<>( "Can't calculate the string's MD5 checksum", new HexOf( new Md5DigestOf( new InputOf("Hello World!") ) ), new TextHasString( "ed076287532e86365e841e92bfc50d8c" ) ).affirm(); } @Test void checksumFromFile() throws Exception { new Assertion<>( "Can't calculate the file's MD5 checksum", new HexOf( new Md5DigestOf( new Sticky( new InputOf( new ResourceOf( "org/cactoos/digest-calculation.txt" ).stream() ) ) ) ), new TextHasString( "162665ab3d58424724f83f28e7a147d6" ) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/bytes/ReaderAsBytesTest.java000066400000000000000000000047611400054650300253450ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.bytes; import java.io.StringReader; import org.cactoos.text.TextOf; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.IsTrue; import org.llorllale.cactoos.matchers.TextIs; /** * Test case for {@link ReaderAsBytes}. * * @since 0.12 * @checkstyle JavadocMethodCheck (500 lines) * @checkstyle ClassDataAbstractionCouplingCheck (500 lines) */ public final class ReaderAsBytesTest { /** * Temporary files and folders generator. */ @Rule public final TemporaryFolder folder = new TemporaryFolder(); @Test public void readsString() throws Exception { final String source = "hello, друг!"; new Assertion<>( "Must read string through a reader", new TextOf( new ReaderAsBytes( new StringReader(source) ) ), new TextIs(source) ).affirm(); } @Test public void readsAndClosesReader() throws Exception { final EmptyClosableReader reader = new EmptyClosableReader(); new ReaderAsBytes(reader).asBytes(); new Assertion<>( "Must close the reader after reading it", reader.isClosed(), new IsTrue() ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/bytes/Sha1DigestOfTest.java000066400000000000000000000056751400054650300250760ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.bytes; import org.cactoos.io.InputOf; import org.cactoos.io.ResourceOf; import org.cactoos.io.Sticky; import org.cactoos.text.HexOf; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.TextHasString; /** * Test case for {@link Sha1DigestOf}. * * @since 0.29 * @checkstyle JavadocMethodCheck (500 lines) */ final class Sha1DigestOfTest { @Test void checksumOfEmptyString() { new Assertion<>( "Can't calculate the empty string's SHA-1 checksum", new HexOf( new Sha1DigestOf( new InputOf("") ) ), new TextHasString( "da39a3ee5e6b4b0d3255bfef95601890afd80709" ) ).affirm(); } @Test void checksumOfString() { new Assertion<>( "Can't calculate the string's SHA-1 checksum", new HexOf( new Sha1DigestOf( new InputOf("Hello World!") ) ), new TextHasString( "2ef7bde608ce5404e97d5f042f95f89f1c232871" ) ).affirm(); } @Test void checksumFromFile() throws Exception { new Assertion<>( "Can't calculate the file's SHA-1 checksum", new HexOf( new Sha1DigestOf( new Sticky( new InputOf( new ResourceOf( "org/cactoos/digest-calculation.txt" ).stream() ) ) ) ), new TextHasString( "34f80bdab9b93af514004f127e440139aad63e2d" ) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/bytes/Sha256DigestOfTest.java000066400000000000000000000063001400054650300252340ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.bytes; import org.cactoos.io.InputOf; import org.cactoos.io.ResourceOf; import org.cactoos.io.Sticky; import org.cactoos.text.HexOf; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.TextHasString; /** * Test case for {@link Sha256DigestOf}. * * @since 0.29 * @checkstyle JavadocMethodCheck (500 lines) */ final class Sha256DigestOfTest { @Test void checksumOfEmptyString() { new Assertion<>( "Can't calculate the empty string's SHA-256 checksum", new HexOf( new Sha256DigestOf( new InputOf("") ) ), new TextHasString( // @checkstyle LineLengthCheck (1 lines) "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" ) ).affirm(); } @Test void checksumOfString() { new Assertion<>( "Can't calculate the string's SHA-256 checksum", new HexOf( new Sha256DigestOf( new InputOf("Hello World!") ) ), new TextHasString( // @checkstyle LineLengthCheck (1 lines) "7f83b1657ff1fc53b92dc18148a1d65dfc2d4b1fa3d677284addd200126d9069" ) ).affirm(); } @Test void checksumFromFile() throws Exception { new Assertion<>( "Can't calculate the file's SHA-256 checksum", new HexOf( new Sha256DigestOf( new Sticky( new InputOf( new ResourceOf( "org/cactoos/digest-calculation.txt" ).stream() ) ) ) ), new TextHasString( // @checkstyle LineLengthCheck (1 lines) "c94451bd1476a3728669de11e22c645906d806e63a95c5797de1f3e84f126a3e" ) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/bytes/UncheckedBytesTest.java000066400000000000000000000042021400054650300255360ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.bytes; import java.io.IOException; import org.cactoos.Text; import org.cactoos.text.TextOf; import org.hamcrest.core.IsEqual; import org.junit.Test; import org.llorllale.cactoos.matchers.Assertion; /** * Test case for {@link UncheckedBytes}. * * @since 0.3 * @checkstyle JavadocMethodCheck (500 lines) */ public final class UncheckedBytesTest { @Test(expected = RuntimeException.class) public void rethrowsCheckedToUncheckedException() { new UncheckedBytes( () -> { throw new IOException("intended"); } ).asBytes(); } @Test public void worksNormallyWhenNoExceptionIsThrown() throws Exception { final Text source = new TextOf("hello, cactoos!"); new Assertion<>( "Must works normally when no exception is thrown", new UncheckedBytes( new BytesOf(source) ).asBytes(), new IsEqual<>(new BytesOf(source).asBytes()) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/bytes/package-info.java000066400000000000000000000023131400054650300243230ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ /** * Bytes, tests. * * @since 0.20.2 */ package org.cactoos.bytes; cactoos-0.49/src/test/java/org/cactoos/collection/000077500000000000000000000000001400054650300221425ustar00rootroot00000000000000cactoos-0.49/src/test/java/org/cactoos/collection/BehavesAsCollection.java000066400000000000000000000073751400054650300266760ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.collection; import java.util.Collection; import org.cactoos.list.ListOf; import org.hamcrest.Description; import org.hamcrest.TypeSafeMatcher; import org.hamcrest.collection.IsCollectionWithSize; import org.hamcrest.collection.IsEmptyCollection; import org.hamcrest.core.IsCollectionContaining; import org.hamcrest.core.IsEqual; import org.hamcrest.core.IsNot; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.MatcherOf; /** * Matcher for collection. * @param Type of source item * @since 0.23 * @checkstyle JavadocMethodCheck (500 lines) * @checkstyle ClassDataAbstractionCouplingCheck (500 lines) */ public final class BehavesAsCollection extends TypeSafeMatcher> { /** * Sample item. */ private final E sample; /** * Ctor. * @param item Sample item */ public BehavesAsCollection(final E item) { super(); this.sample = item; } @Override @SuppressWarnings({ "unchecked", "PMD.ClassCastExceptionWithToArray" }) public boolean matchesSafely(final Collection col) { new Assertion<>( "Must contain item", col, new IsCollectionContaining<>( new IsEqual<>( this.sample ) ) ).affirm(); new Assertion<>( "Must not be empty", col, new IsNot<>( new IsEmptyCollection<>() ) ).affirm(); new Assertion<>( "Size must be more than 0", col, new IsCollectionWithSize<>( new MatcherOf<>(s -> s > 0) ) ).affirm(); new Assertion<>( "Array must contain item", new ListOf<>( (E[]) col.toArray() ), new IsCollectionContaining<>( new IsEqual<>(this.sample) ) ).affirm(); final E[] array = (E[]) new Object[col.size()]; col.toArray(array); new Assertion<>( "Array from collection must contain item", new ListOf<>(array), new IsCollectionContaining<>( new IsEqual<>(this.sample) ) ).affirm(); new Assertion<>( "Must contain list with the item", col.containsAll( new ListOf<>(this.sample) ), new IsEqual<>(true) ).affirm(); return true; } @Override public void describeTo(final Description desc) { desc.appendText("not a valid collection"); } } cactoos-0.49/src/test/java/org/cactoos/collection/ImmutableTest.java000066400000000000000000000172251400054650300255730ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.collection; import org.cactoos.list.ListOf; import org.hamcrest.core.IsEqual; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.HasValues; import org.llorllale.cactoos.matchers.MatcherOf; import org.llorllale.cactoos.matchers.Throws; /** * Test case for {@link Immutable}. * * @since 1.16 * @checkstyle MagicNumber (500 lines) * @checkstyle ClassDataAbstractionCouplingCheck (500 lines) */ @SuppressWarnings("PMD.TooManyMethods") public class ImmutableTest { @Test void size() { new Assertion<>( "size() must be equals to original", new Immutable<>( new ListOf<>(1, 2) ).size(), new IsEqual<>(2) ).affirm(); } @Test void isEmpty() { new Assertion<>( "isEmpty() must be equals to original", new Immutable<>( new ListOf<>(1, 2) ).isEmpty(), new IsEqual<>( new ListOf<>(1, 2).isEmpty() ) ).affirm(); } @Test void iterator() { new Assertion<>( "iterator() is equal to original", () -> new Immutable<>( new ListOf<>(1, 2) ).iterator(), new HasValues<>(1, 2) ).affirm(); } @Test void contains() { new Assertion<>( "contains() must be equals to original", new Immutable<>( new ListOf<>(1, 2) ).contains(1), new IsEqual<>( new ListOf<>(1, 2).contains(1) ) ).affirm(); } @Test void toArray() { new Assertion<>( "toArray() must be equals to original", new Immutable<>( new ListOf<>(1, 2) ).toArray(), new IsEqual<>( new ListOf<>(1, 2).toArray() ) ).affirm(); } @Test void testToArray() { new Assertion<>( "toArray(T[]) must be equals to original", new Immutable<>( new ListOf<>(1, 2, 3) ).toArray(new Integer[3]), new IsEqual<>( new ListOf<>(1, 2, 3).toArray(new Integer[3]) ) ).affirm(); } @Test void add() { new Assertion<>( "add() must throw exception", () -> new Immutable<>( new ListOf<>(1, 2) ).add(3), new Throws<>( new MatcherOf<>( (String msg) -> msg.equals("#add(): the collection is read-only") ), UnsupportedOperationException.class ) ).affirm(); } @Test void remove() { new Assertion<>( "remove() must throw exception", () -> new Immutable<>( new ListOf<>(1, 2) ).remove(1), new Throws<>( new MatcherOf<>( (String msg) -> msg.equals("#remove(): the collection is read-only") ), UnsupportedOperationException.class ) ).affirm(); } @Test void containsAll() { final ListOf another = new ListOf<>(3, 4, 5); new Assertion<>( "containsAll() must be equals to original", new Immutable<>( new ListOf<>(1, 2, 3) ).containsAll(another), new IsEqual<>( new ListOf<>(1, 2, 3).containsAll(another) ) ).affirm(); } @Test void addAll() { new Assertion<>( "addAll() must throw exception", () -> new Immutable<>( new ListOf<>(1, 2) ).addAll(new ListOf<>(3, 4)), new Throws<>( new MatcherOf<>( (String msg) -> msg.equals("#addAll(): the collection is read-only") ), UnsupportedOperationException.class ) ).affirm(); } @Test void removeAll() { new Assertion<>( "removeAll() must throw exception", () -> new Immutable<>( new ListOf<>(1, 2, 3) ).removeAll(new ListOf<>(2, 3)), new Throws<>( new MatcherOf<>( (String msg) -> msg.equals("#removeAll(): the collection is read-only") ), UnsupportedOperationException.class ) ).affirm(); } @Test void retainAll() { new Assertion<>( "retainAll() must throw exception", () -> new Immutable<>( new ListOf<>(1, 2, 3) ).retainAll(new ListOf<>(1)), new Throws<>( new MatcherOf<>( (String msg) -> msg.equals("#retainAll(): the collection is read-only") ), UnsupportedOperationException.class ) ).affirm(); } @Test void clear() { new Assertion<>( "clear() must throw exception", () -> { new Immutable<>( new ListOf<>(1, 2, 3) ).clear(); return new Object(); }, new Throws<>( new MatcherOf<>( (String msg) -> msg.equals("#clear(): the collection is read-only") ), UnsupportedOperationException.class ) ).affirm(); } @Test void testToString() { new Assertion<>( "toString() must be equals to original", new Immutable<>( new ListOf<>(1, 2, 3) ).toString(), new IsEqual<>( new ListOf<>(1, 2, 3).toString() ) ).affirm(); } @Test void testHashCode() { new Assertion<>( "hashCode() must be equals to original", new Immutable<>( new ListOf<>(1, 2, 3) ).hashCode(), new IsEqual<>( new ListOf<>(1, 2, 3).hashCode() ) ).affirm(); } @Test void testEquals() { final ListOf another = new ListOf<>(4, 5, 6); new Assertion<>( "equals() must be equals to original", new Immutable<>( new ListOf<>(1, 2, 3) ).equals(another), new IsEqual<>( new ListOf<>(1, 2, 3).equals(another) ) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/collection/NoNullsTest.java000066400000000000000000000207561400054650300252510ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.collection; import java.util.ArrayList; import java.util.Collection; import org.cactoos.iterable.IterableOf; import org.cactoos.list.ListOf; import org.hamcrest.collection.IsEmptyCollection; import org.hamcrest.core.IsEqual; import org.hamcrest.core.IsNot; import org.hamcrest.object.HasToString; import org.hamcrest.text.StringContainsInOrder; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.HasValues; import org.llorllale.cactoos.matchers.IsTrue; import org.llorllale.cactoos.matchers.Throws; /** * Test cases for {@link NoNulls}. * *

* There is no thread-safety guarantee. * * @since 0.35 * @checkstyle JavadocMethodCheck (500 lines) * @checkstyle MagicNumberCheck (500 lines) * @checkstyle ClassDataAbstractionCouplingCheck (500 lines) */ @SuppressWarnings("PMD.TooManyMethods") final class NoNullsTest { @Test void throwsErrorIfNullInToArray() { new Assertion<>( "Must throw exception", () -> new NoNulls<>( new ListOf<>(1, null, 3) ).toArray(), new Throws<>( "Item #1 of #toArray() is NULL", IllegalStateException.class ) ).affirm(); } @Test void throwsErrorIfNullInToArrayWithArg() { new Assertion<>( "Must throw exception for the item#1", () -> new NoNulls<>( new ListOf<>(1, null, 3) ).toArray(new Object[3]), new Throws<>( "Item #1 of #toArray(array) is NULL", IllegalStateException.class ) ).affirm(); } @Test void throwsErrorIfNullInContainsArg() { new Assertion<>( "Must throw exception for #contains(null)", () -> new NoNulls<>( new ListOf<>(1, 2, 3) ).contains(null), new Throws<>( "Argument of #contains(T) is NULL", IllegalArgumentException.class ) ).affirm(); } @Test void testSuccessNotNullArg() { new Assertion<>( "Must contain not null argument", new NoNulls<>( new ListOf<>(1) ).contains(1), new IsTrue() ).affirm(); } @Test void testSuccessAddAll() { final Collection nonulls = new NoNulls<>(new ArrayList<>(0)); nonulls.addAll(new ListOf<>(1, 2)); new Assertion<>( "Must add all", nonulls, new IsEqual<>( new ListOf<>(1, 2) ) ).affirm(); } @Test void throwsErrorIfNullInAddAll() { final Collection nonulls = new NoNulls<>(new ArrayList<>(0)); new Assertion<>( "Must throw exception for nullable #addAll() parameter collection", () -> nonulls.addAll(new ListOf<>(1, 2, null)), new Throws<>( "Item #2 of #toArray() is NULL", IllegalStateException.class ) ).affirm(); } @Test void behavesAsCollection() { new Assertion<>( "Must behave as a no-null collection", new NoNulls<>( new ListOf<>(1) ), new BehavesAsCollection<>(1) ).affirm(); } @Test void hasToString() { new Assertion<>( "Must have correct NoNulls#toString() and contain value of its elements", new NoNulls<>( new ListOf<>(1, 2, 3) ), new HasToString<>( new StringContainsInOrder(new IterableOf<>("1", "2", "3")) ) ).affirm(); } @Test void emptyWhenCleared() { final Collection col = new NoNulls<>( new ListOf<>(1, 2, 3) ); col.clear(); new Assertion<>( "Must be empty after NoNulls#clear() is called", col, new IsEmptyCollection<>() ).affirm(); } @Test void whenItemRemoved() { final Collection col = new NoNulls<>( new ListOf<>(1, 2, 3) ); col.remove(1); new Assertion<>( "Must have item removed from no-null collection", col, new IsEqual<>(new ListOf<>(2, 3)) ).affirm(); } @Test void whenItemAdded() { final Collection col = new NoNulls<>( new ListOf<>(1, 2) ); col.add(3); new Assertion<>( "Must have item added to no-null collection", col, new IsEqual<>(new ListOf<>(1, 2, 3)) ).affirm(); } @Test void throwsAtAttemptToAddNull() { new Assertion<>( "Must throw exception when add NULL", () -> new NoNulls<>( new ListOf<>(1, 3) ).add(null), new Throws<>( "Item of #add(T) is NULL", IllegalStateException.class ) ).affirm(); } @Test void removesAll() { final Collection col = new NoNulls<>( new ListOf<>(1, 2, 3) ); col.removeAll(new ListOf<>(1, null)); new Assertion<>( "Must have an item removed", col, new HasValues<>(2, 3) ).affirm(); } @Test void retainsAll() { final Collection col = new NoNulls<>( new ListOf<>(1, 2, 3) ); new Assertion<>( "NoNulls#retainAll(...) must return false for the same elements", col.retainAll(new ListOf<>(1, 2, 3)), new IsNot<>(new IsTrue()) ).affirm(); } @Test void retainsAllWithNulls() { final Collection col = new NoNulls<>( new ListOf<>(1, 2, 3) ); new Assertion<>( "NoNulls#retailAll(..) must return true for different elements", col.retainAll(new ListOf<>(1, null, 3)), new IsTrue() ).affirm(); } @Test void throwsAtAttemptToRemoveNull() { new Assertion<>( "Must throw exception when removing NULL for NoNull collection", () -> new NoNulls<>( new ListOf<>(1, 2, 3) ).remove(null), new Throws<>( "Item of #remove(T) is NULL", IllegalStateException.class ) ).affirm(); } @Test void hashCodeIsTheSame() { final Collection items = new ListOf<>(1, 2); new Assertion<>( "Must have the same hashCode", new NoNulls<>(items).hashCode(), new IsEqual<>( items.hashCode() ) ).affirm(); } @Test void shouldBeEmpty() { final Collection col = new NoNulls<>( new ListOf<>() ); new Assertion<>( "Must be empty if created from an empty list", col.isEmpty(), new IsTrue() ).affirm(); } @Test void addsToEmptyCollection() { final Collection col = new NoNulls<>( new ListOf<>() ); col.add(1); new Assertion<>( "Must not be empty after an item was added", col.isEmpty(), new IsNot<>(new IsTrue()) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/collection/package-info.java000066400000000000000000000023241400054650300253320ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ /** * Collections, tests. * * @since 0.14 */ package org.cactoos.collection; cactoos-0.49/src/test/java/org/cactoos/experimental/000077500000000000000000000000001400054650300225045ustar00rootroot00000000000000cactoos-0.49/src/test/java/org/cactoos/experimental/ThreadsTest.java000066400000000000000000000132341400054650300256040ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.experimental; import java.io.UncheckedIOException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import org.cactoos.Proc; import org.cactoos.func.Repeated; import org.cactoos.func.UncheckedFunc; import org.cactoos.scalar.ScalarOf; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.HasValues; import org.llorllale.cactoos.matchers.Throws; /** * Test case for {@link Threads}. * * @since 1.0.0 * @checkstyle MagicNumberCheck (500 lines) * @checkstyle ClassDataAbstractionCouplingCheck (500 lines) */ @SuppressWarnings("PMD.AvoidDuplicateLiterals") final class ThreadsTest { /** * Execute the tasks concurrently using {@link Threads} when * {@link ExecutorService} was initiated by someone else. */ @Test void containsResults() { this.repeat( arg -> { final ExecutorService extor = Executors.newFixedThreadPool(3); try { new Assertion<>( "contains results from callables", new Threads( extor, () -> { this.sleep(); return "txt 1"; }, () -> { this.sleep(); return "txt 2"; }, () -> { this.sleep(); return "txt 3"; } ), new HasValues<>("txt 1", "txt 2", "txt 3") ).affirm(); } finally { extor.shutdown(); if (!extor.awaitTermination(1L, TimeUnit.SECONDS)) { extor.shutdownNow(); } } } ); } /** * Execute 1 task within executor service and ensure that we'll get the * expected exception type. */ @Test void failsDueToException() { new Assertion<>( "wraps error into CompletionException", () -> new Threads( Executors.newSingleThreadExecutor(), new ScalarOf<>( () -> { // @checkstyle LineLengthCheck (1 line) throw new IllegalStateException("Something went wrong"); } ) ).iterator().next(), new Throws<>( // @checkstyle LineLengthCheck (1 line) "java.io.IOException: java.util.concurrent.ExecutionException: java.lang.IllegalStateException: Something went wrong", UncheckedIOException.class ) ).affirm(); } /** * Execute the tasks concurrently using {@link Threads} when * {@link ExecutorService} was initiated by {@link Threads} itself. */ @Test void containsValuesWithInlineExecutorService() { this.repeat( arg -> new Assertion<>( // @checkstyle LineLength (1 line) "contains results from the callables when using the inline executor service", new Threads( 3, () -> { this.sleep(); return "txt 1"; }, () -> { this.sleep(); return "txt 2"; }, () -> { this.sleep(); return "txt 3"; } ), new HasValues<>("txt 1", "txt 2", "txt 3") ).affirm() ); } /** * Repeat the test several times. * @param test The test to execute. */ private void repeat(final Proc test) { new UncheckedFunc<>( new Repeated<>( arg -> { test.exec(null); return null; }, 5 ) ).apply(Boolean.TRUE); } /** * Sleep. */ private void sleep() { try { TimeUnit.MILLISECONDS.sleep(100L); } catch (final InterruptedException iex) { throw new IllegalStateException(iex); } } } cactoos-0.49/src/test/java/org/cactoos/experimental/TimedTest.java000066400000000000000000000253561400054650300252640ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.experimental; import java.io.UncheckedIOException; import java.time.Duration; import java.util.concurrent.CancellationException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import org.cactoos.scalar.Repeated; import org.hamcrest.core.IsNull; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.HasValues; import org.llorllale.cactoos.matchers.Throws; /** * Test case for {@link Timed}. * * @since 1.0.0 * @todo #1445:30min Replace all the usage of Repeated in tests that * are used to execute the same test multiple times with the use of * the RepeatedTest annotation from Junit 5. * @checkstyle ClassDataAbstractionCouplingCheck (500 lines) */ final class TimedTest { /** * First text for test. */ private static final String FIRST_TEXT = "txt 1"; /** * Second text for test. */ private static final String SECOND_TEXT = "txt 2"; /** * Third text for test. */ private static final String THIRD_TEXT = "txt 3"; /** * Threads count. */ private static final int THREADS = 3; /** * Repetitions count for running test several times. */ private static final int REPETITIONS_COUNT = 5; /** * Sleep time. */ private static final Duration SLEEP_TIME = Duration.ofMillis(100L); /** * Execute the tasks concurrently using {@link Timed} when * {@link ExecutorService} was initiated by someone else. */ @Test @SuppressWarnings({ "PMD.AvoidThrowingRawExceptionTypes", "PMD.DoNotThrowExceptionInFinally" }) void containsResults() throws Exception { new Repeated<>( () -> { final ExecutorService extor = Executors.newFixedThreadPool( TimedTest.THREADS ); try { new Assertion<>( "Contains results from callables", new Timed( extor, 1L, TimeUnit.SECONDS, () -> { this.sleep(); return TimedTest.FIRST_TEXT; }, () -> { this.sleep(); return TimedTest.SECOND_TEXT; }, () -> { this.sleep(); return TimedTest.THIRD_TEXT; } ), new HasValues<>( TimedTest.FIRST_TEXT, TimedTest.SECOND_TEXT, TimedTest.THIRD_TEXT ) ).affirm(); } finally { extor.shutdown(); try { if (!extor.awaitTermination(1L, TimeUnit.SECONDS)) { extor.shutdownNow(); } } catch (final InterruptedException ex) { Thread.currentThread().interrupt(); throw new RuntimeException(ex); } } return true; }, TimedTest.REPETITIONS_COUNT ).value(); } /** * Execution takes longer than timeout when * {@link ExecutorService} was initiated by someone else. */ @Test @SuppressWarnings({ "PMD.AvoidThrowingRawExceptionTypes", "PMD.DoNotThrowExceptionInFinally" }) void failsDueToTimeoutWithExternalExecutorService() throws Exception { new Repeated<>( () -> { final ExecutorService extor = Executors.newFixedThreadPool( TimedTest.THREADS ); try { new Assertion<>( // @checkstyle LineLengthCheck (1 line) "Fails due to timeout when using the external executor service", () -> new Timed( extor, 1L, TimeUnit.MILLISECONDS, () -> { this.sleep(); return TimedTest.FIRST_TEXT; }, () -> { this.sleep(); return TimedTest.SECOND_TEXT; }, () -> { this.sleep(); return TimedTest.THIRD_TEXT; } ).iterator().next(), new Throws<>( new IsNull<>(), CancellationException.class ) ).affirm(); } finally { extor.shutdown(); try { if (!extor.awaitTermination(1L, TimeUnit.SECONDS)) { extor.shutdownNow(); } } catch (final InterruptedException ex) { Thread.currentThread().interrupt(); throw new RuntimeException(ex); } } return true; }, TimedTest.REPETITIONS_COUNT ).value(); } /** * Execute 1 task within executor service and ensure that we'll get the * expected exception type. */ @Test void failsDueToException() { new Assertion<>( "Wraps error into CompletionException", () -> new Timed( Executors.newSingleThreadExecutor(), 1L, TimeUnit.SECONDS, () -> { // @checkstyle LineLengthCheck (1 line) throw new IllegalStateException("Something went wrong"); } ).iterator().next(), new Throws<>( // @checkstyle LineLengthCheck (1 line) "java.io.IOException: java.util.concurrent.ExecutionException: java.lang.IllegalStateException: Something went wrong", UncheckedIOException.class ) ).affirm(); } /** * Execute the tasks concurrently using {@link Timed} when * {@link ExecutorService} was initiated by {@link Timed} itself. */ @Test void containsValuesWithInlineExecutorService() throws Exception { new Repeated<>( () -> { new Assertion<>( // @checkstyle LineLengthCheck (1 line) "Contains results from the callables when using the inline executor service", new Timed( TimedTest.THREADS, 1L, TimeUnit.SECONDS, () -> { this.sleep(); return TimedTest.FIRST_TEXT; }, () -> { this.sleep(); return TimedTest.SECOND_TEXT; }, () -> { this.sleep(); return TimedTest.THIRD_TEXT; } ), new HasValues<>( TimedTest.FIRST_TEXT, TimedTest.SECOND_TEXT, TimedTest.THIRD_TEXT ) ).affirm(); return true; }, TimedTest.REPETITIONS_COUNT ).value(); } /** * Execution takes longer than timeout when * {@link ExecutorService} was initiated by {@link Timed} itself. */ @Test void failsDueToTimeoutWithInlineExecutorService() throws Exception { new Repeated<>( () -> { new Assertion<>( // @checkstyle LineLengthCheck (1 line) "Fails due to timeout when using the inline executor service", () -> new Timed( TimedTest.THREADS, 1L, TimeUnit.MILLISECONDS, () -> { this.sleep(); return TimedTest.FIRST_TEXT; }, () -> { this.sleep(); return TimedTest.SECOND_TEXT; }, () -> { this.sleep(); return TimedTest.THIRD_TEXT; } ).iterator().next(), new Throws<>( new IsNull<>(), CancellationException.class ) ).affirm(); return true; }, TimedTest.REPETITIONS_COUNT ).value(); } /** * Sleep. */ private void sleep() { try { TimeUnit.MILLISECONDS.sleep(TimedTest.SLEEP_TIME.toMillis()); } catch (final InterruptedException iex) { throw new IllegalStateException(iex); } } } cactoos-0.49/src/test/java/org/cactoos/experimental/package-info.java000066400000000000000000000024031400054650300256720ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ /** * The unit-test for the package {@link org.cactoos.experimental}. * * @since 1.0.0 */ package org.cactoos.experimental; cactoos-0.49/src/test/java/org/cactoos/func/000077500000000000000000000000001400054650300207425ustar00rootroot00000000000000cactoos-0.49/src/test/java/org/cactoos/func/AsyncTest.java000066400000000000000000000127661400054650300235360ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.func; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import org.hamcrest.core.IsEqual; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.FuncApplies; import org.llorllale.cactoos.matchers.MatcherOf; /** * Test case for {@link Async}. * * @since 0.10 * @checkstyle JavadocMethodCheck (500 lines) * @checkstyle ClassDataAbstractionCouplingCheck (500 lines) */ final class AsyncTest { @Test void runsInBackground() { new Assertion<>( "Can't run in the background", new Async<>( input -> { TimeUnit.DAYS.sleep(1L); return "done!"; } ), new FuncApplies<>( true, new MatcherOf<>( future -> !future.isDone() ) ) ).affirm(); } @Test void runsAsProcInBackground() { new Assertion<>( "Can't run proc in the background", input -> { final CountDownLatch latch = new CountDownLatch(1); new Async<>( new FuncOf<>(ipt -> latch.countDown(), true) ).exec(input); latch.await(); return true; }, new FuncApplies<>( true, new IsEqual<>(true) ) ).affirm(); } @Test void runsInBackgroundWithoutFuture() { final CountDownLatch latch = new CountDownLatch(1); new Assertion<>( "Can't run in the background without us touching the Future", new Async<>( new FuncOf<>(input -> latch.countDown(), true) ), new FuncApplies<>( true, new MatcherOf<>( future -> { return latch.await(1L, TimeUnit.SECONDS); } ) ) ).affirm(); } @Test void runsInBackgroundWithThreadFactory() { final String name = "secret name for thread factory"; final ThreadFactory factory = r -> new Thread(r, name); final CountDownLatch latch = new CountDownLatch(1); new Assertion<>( "Can't run in the background with specific thread factory", new Async<>( new FuncOf<>( input -> { if (!input.equals(Thread.currentThread().getName())) { throw new IllegalStateException( "Another thread factory was used" ); } latch.countDown(); }, true ), factory ), new FuncApplies<>( name, new MatcherOf<>( future -> { future.get(); return latch.getCount() == 0; } ) ) ).affirm(); } @Test void runsInBackgroundWithExecutorService() { final String name = "secret name for thread executor"; final ThreadFactory factory = r -> new Thread(r, name); final CountDownLatch latch = new CountDownLatch(1); new Assertion<>( "Can't run in the background with specific thread executor", new Async<>( new FuncOf<>( input -> { if (!input.equals(Thread.currentThread().getName())) { throw new IllegalStateException( "Another thread executor was used" ); } latch.countDown(); }, true ), Executors.newSingleThreadExecutor(factory) ), new FuncApplies<>( name, new MatcherOf<>( future -> { future.get(); return latch.getCount() == 0; } ) ) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/func/BiFuncNoNullsTest.java000066400000000000000000000045121400054650300251300ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.func; import org.junit.Test; /** * Test case for {@link BiFuncNoNulls}. * @since 0.11 * @checkstyle JavadocMethodCheck (500 lines) */ public final class BiFuncNoNullsTest { @Test(expected = IllegalArgumentException.class) public void failForNullFunc() throws Exception { new BiFuncNoNulls<>(null).apply(new Object(), new Object()); } @Test(expected = IllegalArgumentException.class) public void failForNullFirstArg() throws Exception { new BiFuncNoNulls<>( (first, second) -> first ).apply(null, new Object()); } @Test(expected = IllegalArgumentException.class) public void failForNullSecondArg() throws Exception { new BiFuncNoNulls<>( (first, second) -> first ).apply(new Object(), null); } @Test(expected = IllegalStateException.class) public void failForNullResult() throws Exception { new BiFuncNoNulls<>( (first, second) -> null ).apply(new Object(), new Object()); } @Test public void okForNoNulls() throws Exception { new BiFuncNoNulls<>( (first, second) -> first ).apply(new Object(), new Object()); } } cactoos-0.49/src/test/java/org/cactoos/func/BiFuncOfTest.java000066400000000000000000000075551400054650300241140ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.func; import java.util.concurrent.atomic.AtomicReference; import org.cactoos.BiFunc; import org.cactoos.proc.ProcOf; import org.cactoos.scalar.Constant; import org.hamcrest.core.IsSame; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.MatcherOf; /** * Test case for {@link BiFuncOf}. * * @since 0.20 * @checkstyle ClassDataAbstractionCouplingCheck (500 lines) */ @SuppressWarnings("PMD.AvoidDuplicateLiterals") final class BiFuncOfTest { @Test void convertsFuncIntoBiFunc() throws Exception { new Assertion<>( "Must convert function into bi-function", new BiFuncOf<>( new FuncOf<>(input -> input) ), new MatcherOf<>( func -> { final Object first = new Object(); final Object res = func.apply(first, "discarded"); return res.equals(first); } ) ).affirm(); } @Test void convertsProcIntoBiFunc() throws Exception { final AtomicReference done = new AtomicReference<>(); final Object result = new Object(); new Assertion<>( "Must convert procedure into bi-function", new BiFuncOf<>( new ProcOf<>( input -> { done.set(input); } ), result ), new MatcherOf<>( func -> { final Object first = new Object(); final Object res = func.apply(first, "discarded"); return res.equals(result) && done.get().equals(first); } ) ).affirm(); } @Test void convertsScalarIntoBiFunc() throws Exception { final Object obj = new Object(); new Assertion<>( "Must convert scalar into bi-function", new BiFuncOf<>(new Constant<>(obj)).apply("discarded", "discarded"), new IsSame<>(obj) ).affirm(); } @Test void convertsLambdaIntoBiFunc() throws Exception { new Assertion<>( "Must convert lambda into bi-function", new BiFuncOf<>((first, second) -> new Object[] {first, second}), new MatcherOf>( func -> { final Object first = new Object(); final Object second = new Object(); final Object[] res = func.apply(first, second); return res.length == 2 && res[0].equals(first) && res[1].equals(second); } ) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/func/ChainedTest.java000066400000000000000000000060761400054650300240110ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.func; import org.cactoos.Func; import org.cactoos.iterable.Filtered; import org.cactoos.iterable.IterableOf; import org.cactoos.iterable.Mapped; import org.cactoos.scalar.LengthOf; import org.hamcrest.core.IsEqual; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; /** * Test case for {@link Chained}. * * @since 0.7 * @checkstyle JavadocMethodCheck (500 lines) * @checkstyle MagicNumber (500 line) */ final class ChainedTest { @Test void withoutIterable() throws Exception { new Assertion<>( "Must work without iterable", new LengthOf( new Filtered<>( input -> input.endsWith("12"), new Mapped<>( new Chained<>( input -> input.concat("1"), (String input) -> input.concat("2") ), new IterableOf<>("public", "final", "class") ) ) ).intValue(), new IsEqual<>(3) ).affirm(); } @Test void withIterable() throws Exception { new Assertion<>( "Must work with iterable", new LengthOf( new Filtered<>( input -> !input.startsWith("st"), new Mapped<>( new Chained<>( input -> input.concat("1"), new IterableOf>( input -> input.concat("2"), input -> input.replaceAll("a", "b") ), String::trim ), new IterableOf<>("private", "static", "String") ) ) ).intValue(), new IsEqual<>(2) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/func/CheckedBiFuncTest.java000066400000000000000000000056561400054650300250760ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.func; import java.io.EOFException; import java.io.IOException; import org.hamcrest.core.IsEqual; import org.hamcrest.core.IsNull; import org.junit.Test; import org.llorllale.cactoos.matchers.Assertion; /** * Test case for {@link CheckedBiFunc}. * * @since 0.32 * @checkstyle JavadocMethodCheck (500 lines) */ public final class CheckedBiFuncTest { @Test(expected = IllegalStateException.class) public void runtimeExceptionIsNotWrapped() throws Exception { new CheckedBiFunc<>( (first, second) -> { throw new IllegalStateException("runtime1"); }, IOException::new ).apply(true, true); } @Test(expected = IOException.class) public void checkedExceptionIsWrapped() throws Exception { new CheckedBiFunc<>( (first, second) -> { throw new EOFException("runtime2"); }, IOException::new ).apply(true, true); } @Test public void extraWrappingIgnored() { try { new CheckedBiFunc<>( (first, second) -> { throw new IOException("runtime3"); }, IOException::new ).apply(true, true); } catch (final IOException exp) { new Assertion<>( "Extra wrapping of IOException has been added", exp.getCause(), new IsNull<>() ).affirm(); } } @Test public void noExceptionThrown() throws Exception { new Assertion<>( "Must not throw an exception", new CheckedBiFunc<>( (first, second) -> true, exp -> exp ).apply(false, false), new IsEqual<>(true) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/func/CheckedFuncTest.java000066400000000000000000000055401400054650300246130ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.func; import java.io.EOFException; import java.io.IOException; import org.hamcrest.core.IsEqual; import org.hamcrest.core.IsNull; import org.junit.Test; import org.llorllale.cactoos.matchers.Assertion; /** * Test case for {@link CheckedFunc}. * * @since 0.32 * @checkstyle JavadocMethodCheck (500 lines) */ public final class CheckedFuncTest { @Test(expected = IllegalStateException.class) public void runtimeExceptionIsNotWrapped() throws Exception { new CheckedFunc<>( input -> { throw new IllegalStateException("runtime1"); }, IOException::new ).apply(true); } @Test(expected = IOException.class) public void checkedExceptionIsWrapped() throws Exception { new CheckedFunc<>( input -> { throw new EOFException("runtime2"); }, IOException::new ).apply(true); } @Test public void extraWrappingIgnored() { try { new CheckedFunc<>( input -> { throw new IOException("runtime3"); }, IOException::new ).apply(true); } catch (final IOException exp) { new Assertion<>( "Extra wrapping of IOException has been added", exp.getCause(), new IsNull<>() ).affirm(); } } @Test public void noExceptionThrown() throws Exception { new Assertion<>( "Must not throw an exception", new CheckedFunc<>( input -> true, exp -> exp ).apply(false), new IsEqual<>(true) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/func/FallbackFromTest.java000066400000000000000000000052221400054650300247710ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.func; import java.io.IOException; import java.util.IllegalFormatWidthException; import org.cactoos.Fallback; import org.hamcrest.core.IsEqual; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; /** * Test case for {@link Fallback.From}. * * @since 0.31 * @checkstyle JavadocMethodCheck (500 lines) * @checkstyle MagicNumberCheck (500 lines) */ @SuppressWarnings("unchecked") final class FallbackFromTest { @Test void supportsException() { new Assertion<>( "Must support exactly exception class", new Fallback.From<>( IOException.class, exp -> "IOException fallback" ).support(new IOException()), new IsEqual<>(0) ).affirm(); } @Test void supportsInheritedException() { new Assertion<>( "Must support inherited exception class", new Fallback.From<>( RuntimeException.class, exp -> "RuntimeException fallback #1" ).support(new IllegalFormatWidthException(1)), new IsEqual<>(3) ).affirm(); } @Test void doesNotSupportException() { new Assertion<>( "Must not support unrelated exception class", new Fallback.From<>( RuntimeException.class, exp -> "RuntimeException fallback #2" ).support(new ClassNotFoundException()), new IsEqual<>(Integer.MIN_VALUE) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/func/FlattenedTest.java000066400000000000000000000032231400054650300243530ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.func; import org.cactoos.scalar.BoolOf; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.FuncApplies; /** * Tests for {@link Flattened}. * * @since 0.49 */ final class FlattenedTest { @Test void flattens() { new Assertion<>( "must flatten", new Flattened<>( new FuncOf<>(x -> new BoolOf(x)) ), new FuncApplies<>("true", true) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/func/FuncEnvelopeTest.java000066400000000000000000000040001400054650300250300ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.func; import org.cactoos.Text; import org.cactoos.text.FormattedText; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.FuncApplies; import org.llorllale.cactoos.matchers.TextIs; /** * Test case for {@link FuncEnvelope}. * * @since 0.41 * @checkstyle JavadocMethodCheck (500 lines) * @checkstyle JavadocTypeCheck (500 lines) */ final class FuncEnvelopeTest { @Test void envelopeDelegatesCalls() { new Assertion<>( "must delegate calls to apply", new Append(" stuff"), new FuncApplies<>(2, new TextIs("2 stuff")) ).affirm(); } private static final class Append extends FuncEnvelope { Append(final String suffix) { super(input -> new FormattedText("%d%s", input, suffix)); } } } cactoos-0.49/src/test/java/org/cactoos/func/FuncNoNullsTest.java000066400000000000000000000037311400054650300246570ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.func; import java.io.IOException; import org.junit.Test; /** * Test case for {@link FuncNoNulls}. * @since 0.10 * @checkstyle JavadocMethodCheck (500 lines) */ public final class FuncNoNullsTest { @Test(expected = IllegalArgumentException.class) public void failForNullFunc() throws Exception { new FuncNoNulls<>(null).apply(new Object()); } @Test(expected = IllegalArgumentException.class) public void failForNullInput() throws Exception { new FuncNoNulls<>(input -> input).apply(null); } @Test public void okForNoNulls() throws Exception { new FuncNoNulls<>(input -> input).apply(new Object()); } @Test(expected = IOException.class) public void failForNullResult() throws Exception { new FuncNoNulls<>(input -> null).apply(new Object()); } } cactoos-0.49/src/test/java/org/cactoos/func/FuncOfTest.java000066400000000000000000000061441400054650300236320ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.func; import java.util.concurrent.atomic.AtomicReference; import org.cactoos.proc.ProcOf; import org.cactoos.scalar.Constant; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.MatcherOf; /** * Test case for {@link FuncOf}. * * @since 0.20 */ final class FuncOfTest { @Test void convertsProcIntoFunc() throws Exception { final AtomicReference done = new AtomicReference<>(); final Object result = new Object(); new Assertion<>( "Must convert Proc into Func", new FuncOf<>( new ProcOf<>( input -> { done.set(input); } ), result ), new MatcherOf<>( func -> { final Object input = new Object(); final Object res = func.apply(input); return res.equals(result) && done.get().equals(input); } ) ).affirm(); } @Test void convertsScalarIntoFunc() throws Exception { final Object result = new Object(); new Assertion<>( "Must convert Scalar into Func", new FuncOf<>(new Constant<>(result)), new MatcherOf<>( func -> { final Object res = func.apply("discarded"); return res.equals(result); } ) ).affirm(); } @Test void convertsLambdaIntoFunc() throws Exception { new Assertion<>( "Must convert Lambda into Func", new FuncOf<>(input -> input), new MatcherOf<>( func -> { final Object input = new Object(); final Object res = func.apply(input); return res.equals(input); } ) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/func/FuncWithFallbackTest.java000066400000000000000000000105411400054650300256150ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.func; import java.io.IOException; import java.util.IllegalFormatException; import java.util.IllegalFormatWidthException; import org.cactoos.Fallback; import org.cactoos.iterable.IterableOf; import org.junit.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.FuncApplies; /** * Test case for {@link FuncWithFallback}. * * @since 0.2 * @checkstyle JavadocMethodCheck (500 lines) * @checkstyle ClassDataAbstractionCouplingCheck (500 lines) */ @SuppressWarnings("unchecked") public final class FuncWithFallbackTest { @Test public void usesMainFunc() { final String expected = "It's success"; new Assertion<>( "Can't use the main function if no exception", new FuncWithFallback( input -> expected, new Fallback.From<>( Exception.class, ex -> "In case of failure..." ) ), new FuncApplies<>(1, expected) ).affirm(); } @Test public void usesFallback() { final String expected = "Never mind"; new Assertion<>( "Can't use the callback in case of exception", new FuncWithFallback( input -> { throw new IOException("Failure"); }, new Fallback.From<>(IOException.class, ex -> expected) ), new FuncApplies<>(1, expected) ).affirm(); } @Test public void usesFallbackOfInterruptedException() { final String expected = "Fallback from InterruptedException"; new Assertion<>( "Can't use a fallback from Interrupted in case of exception", new FuncWithFallback( input -> { throw new InterruptedException( "Failure with InterruptedException" ); }, new Fallback.From<>(InterruptedException.class, exp -> expected) ), new FuncApplies<>(1, expected) ).affirm(); } @Test public void usesTheClosestFallback() { final String expected = "Fallback from IllegalFormatException"; new Assertion<>( "Can't find the closest fallback", new FuncWithFallback<>( input -> { throw new IllegalFormatWidthException(1); }, new IterableOf<>( new Fallback.From<>( IllegalArgumentException.class, exp -> "Fallback from IllegalArgumentException" ), new Fallback.From<>( IllegalFormatException.class, exp -> expected ) ) ), new FuncApplies<>(1, expected) ).affirm(); } @Test(expected = Exception.class) public void noFallbackIsProvided() throws Exception { new FuncWithFallback<>( input -> { throw new IllegalFormatWidthException(1); }, new IterableOf<>() ).apply(1); } } cactoos-0.49/src/test/java/org/cactoos/func/IoCheckedBiFuncTest.java000066400000000000000000000047311400054650300253570ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.func; import java.io.IOException; import org.junit.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.Throws; /** * Test case for {@link IoCheckedBiFunc}. * @since 0.13 * @checkstyle JavadocMethodCheck (500 lines) */ public final class IoCheckedBiFuncTest { @Test public void rethrowsIoException() { final IOException exception = new IOException("intended"); new Assertion<>( "Must rethrow IOException", () -> new IoCheckedBiFunc<>( (fst, scd) -> { throw exception; } ).apply(1, 2), new Throws<>( exception.getMessage(), exception.getClass() ) ).affirm(); } @Test(expected = IOException.class) public void rethrowsCheckedToIoException() throws Exception { new IoCheckedBiFunc<>( (fst, scd) -> { throw new IOException("intended to fail"); } ).apply(1, 2); } @Test(expected = IllegalStateException.class) public void runtimeExceptionGoesOut() throws IOException { new IoCheckedBiFunc<>( (fst, scd) -> { throw new IllegalStateException("intended to fail here"); } ).apply(1, 2); } } cactoos-0.49/src/test/java/org/cactoos/func/IoCheckedFuncTest.java000066400000000000000000000053171400054650300251050ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.func; import java.io.IOException; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.Throws; /** * Test case for {@link IoCheckedFunc}. * * @since 0.4 * @checkstyle JavadocMethodCheck (500 lines) */ final class IoCheckedFuncTest { @Test void rethrowsIoException() { final IOException exception = new IOException("intended"); new Assertion<>( "Must rethrow original IOException", () -> new IoCheckedFunc<>( i -> { throw exception; } ).apply(1), new Throws<>( exception.getMessage(), exception.getClass() ) ).affirm(); } @Test void rethrowsCheckedToIoException() { new Assertion<>( "Must rethrow as IOException", () -> new IoCheckedFunc<>( i -> { throw new InterruptedException("intended to fail"); } ).apply(1), new Throws<>( IOException.class ) ).affirm(); } @Test void runtimeExceptionGoesOut() { new Assertion<>( "Must throw runtime exception as is", () -> new IoCheckedFunc<>( i -> { throw new IllegalStateException("intended to fail here"); } ).apply(1), new Throws<>( IllegalStateException.class ) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/func/RepeatedTest.java000066400000000000000000000053641400054650300242060ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.func; import java.security.SecureRandom; import java.util.Iterator; import org.cactoos.Func; import org.cactoos.iterator.IteratorOf; import org.hamcrest.core.IsEqual; import org.hamcrest.core.IsNull; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.Throws; /** * Test case for {@link Repeated}. * * @since 0.13.1 * @checkstyle JavadocMethodCheck (500 lines) * @checkstyle MagicNumberCheck (500 line) */ final class RepeatedTest { @Test void runsFuncMultipleTimes() throws Exception { final Iterator iter = new IteratorOf<>(1, 2, 5, 6); final Func func = new Repeated<>( input -> iter.next(), 3 ); new Assertion<>( "Must be applied 3 times", func.apply(true), new IsEqual<>(5) ).affirm(); } @Test void repeatsNullsResults() throws Exception { final Func func = new Repeated<>( input -> null, 2 ); new Assertion<>( "Must repeat NULL", func.apply(true), new IsNull<>() ).affirm(); } @Test void doesntRepeatAny() { final Func func = new Repeated<>( input -> new SecureRandom().nextInt(), 0 ); new Assertion<>( "Must throw if parameter is not correct", () -> func.apply(true), new Throws<>( IllegalArgumentException.class ) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/func/RetryTest.java000066400000000000000000000066321400054650300235610ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.func; import java.security.SecureRandom; import java.time.Duration; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.FuncApplies; import org.llorllale.cactoos.matchers.Throws; /** * Test case for {@link Retry}. * * @since 0.8 * @checkstyle JavadocMethodCheck (500 lines) * @checkstyle MagicNumberCheck (500 line) */ @SuppressWarnings("PMD.AvoidDuplicateLiterals") final class RetryTest { @Test void runsFuncMultipleTimes() { new Assertion<>( "Didn't run multiple times", new Retry<>( input -> { if (new SecureRandom().nextDouble() > 0.3d) { throw new IllegalArgumentException("May happen"); } return 0; }, Integer.MAX_VALUE ), new FuncApplies<>(true, 0) ).affirm(); } @Test void runsFuncConditionMultipleTimes() { new Assertion<>( "Didn't check condition multiple times", new Retry<>( input -> { if (new SecureRandom().nextDouble() > 0.3d) { throw new IllegalArgumentException("May happen"); } return true; }, count -> count == Integer.MAX_VALUE ), new FuncApplies<>(true, true) ).affirm(); } @Test void processInterruptExceptionOnWait() { final Thread main = Thread.currentThread(); new Thread( () -> { while (true) { if (Thread.State.TIMED_WAITING == main.getState()) { main.interrupt(); return; } } }).start(); new Assertion<>( "Must be interrupted on wait", () -> new Retry<>( input -> { throw new IllegalArgumentException("Happens"); }, attempts -> false, Duration.ofMillis(Long.MAX_VALUE) ).apply(true), new Throws<>("sleep interrupted", InterruptedException.class) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/func/SolidBiFuncTest.java000066400000000000000000000056741400054650300246220ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.func; import java.security.SecureRandom; import org.cactoos.BiFunc; import org.cactoos.Func; import org.hamcrest.core.IsEqual; import org.hamcrest.core.IsNot; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.RunsInThreads; /** * Test case for {@link SolidBiFunc}. * * @since 1.0 * @checkstyle JavadocMethodCheck (500 lines) */ final class SolidBiFuncTest { @Test void testThatFuncIsSynchronized() { final int threads = 100; final int[] shared = new int[]{0}; final BiFunc testable = new SolidBiFunc<>( (first, second) -> { shared[0] = shared[0] + 1; return true; } ); new Assertion<>( "SolidBiFunc can't work properly in concurrent threads.", func -> func.apply(true), new RunsInThreads>( input -> testable.apply(1, 1), threads ) ).affirm(); new Assertion<>( "Shared resource has been modified by multiple threads.", shared[0], new IsEqual<>(1) ).affirm(); } @Test void testThatFuncResultCacheIsLimited() throws Exception { final BiFunc func = new SolidBiFunc<>( (first, second) -> new SecureRandom().nextInt(), 1 ); new Assertion<>( "Result of (0, 0) call wasn't invalidated.", func.apply(0, 0) + func.apply(1, 1), new IsNot<>( new IsEqual<>( func.apply(1, 1) + func.apply(0, 0) ) ) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/func/SolidFuncTest.java000066400000000000000000000046441400054650300243430ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.func; import java.security.SecureRandom; import org.cactoos.Func; import org.cactoos.list.ListOf; import org.hamcrest.core.IsEqual; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.RunsInThreads; /** * Test case for {@link SolidFunc}. * * @since 0.24 * @checkstyle JavadocMethodCheck (500 lines) */ final class SolidFuncTest { @Test void cachesFuncResults() throws Exception { final Func func = new SolidFunc<>( input -> new SecureRandom().nextInt() ); new Assertion<>( "Must cache results", func.apply(true) + func.apply(true), new IsEqual<>(func.apply(true) + func.apply(true)) ).affirm(); } @Test void worksInThreads() { new Assertion<>( "Must work well in multiple threads", func -> { new Assertion<>( "Result must be cached", func.apply(true), new IsEqual<>(func.apply(true)) ).affirm(); return true; }, new RunsInThreads<>( new SolidFunc<>(x -> new ListOf<>(1, 2)) ) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/func/StickyBiFuncTest.java000066400000000000000000000036121400054650300250040ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.func; import java.security.SecureRandom; import org.cactoos.BiFunc; import org.hamcrest.core.IsEqual; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; /** * Test case for {@link StickyBiFunc}. * @since 0.13 * @checkstyle JavadocMethodCheck (500 lines) */ final class StickyBiFuncTest { @Test void cachesFuncResults() throws Exception { final BiFunc func = new StickyBiFunc<>( (first, second) -> new SecureRandom().nextInt() ); new Assertion<>( "Must cache results", func.apply(true, true) + func.apply(true, true), new IsEqual<>(func.apply(true, true) + func.apply(true, true)) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/func/StickyFuncTest.java000066400000000000000000000060021400054650300245250ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.func; import java.security.SecureRandom; import org.cactoos.Func; import org.hamcrest.core.IsEqual; import org.hamcrest.core.IsNot; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; /** * Test case for {@link StickyFunc}. * * @since 0.4 * @checkstyle JavadocMethodCheck (500 lines) */ final class StickyFuncTest { @Test void cachesFuncResults() throws Exception { final Func func = new StickyFunc<>( input -> new SecureRandom().nextInt() ); new Assertion<>( "Must cache results", func.apply(true) + func.apply(true), new IsEqual<>( func.apply(true) + func.apply(true) ) ).affirm(); } @Test void cachesWithLimitedBuffer() throws Exception { final Func func = new StickyFunc<>( input -> new SecureRandom().nextInt(), 2 ); final int first = func.apply(0); final int second = func.apply(1); new Assertion<>( "Must cache two results", first + second, new IsEqual<>(func.apply(0) + func.apply(1)) ).affirm(); final int third = func.apply(-1); new Assertion<>( "Must cache next two results", second + third, new IsEqual<>(func.apply(1) + func.apply(-1)) ).affirm(); } @Test void cachesWithZeroBuffer() throws Exception { final Func func = new StickyFunc<>( input -> new SecureRandom().nextInt(), 0 ); new Assertion<>( "Must be not be cached", func.apply(true) + func.apply(true), new IsNot<>( new IsEqual<>( func.apply(true) + func.apply(true) ) ) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/func/SyncFuncTest.java000066400000000000000000000041601400054650300241760ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.func; import java.util.LinkedList; import java.util.List; import org.hamcrest.core.IsEqual; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.RunsInThreads; /** * Test case for {@link SyncFunc}. * * @since 0.24 * @checkstyle JavadocMethodCheck (500 lines) */ final class SyncFuncTest { @Test void funcWorksInThreads() { final List list = new LinkedList<>(); final int threads = 100; new Assertion<>( "Sync func can't work well in multiple threads", func -> func.apply(true), new RunsInThreads<>( new SyncFunc( input -> list.add(1) ), threads ) ).affirm(); new Assertion<>( "Must run the expected amount of threads", list.size(), new IsEqual<>(threads) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/func/TimedFuncTest.java000066400000000000000000000061301400054650300243230ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.func; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeoutException; import org.cactoos.iterable.Endless; import org.cactoos.scalar.And; import org.junit.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.IsTrue; /** * Test case for {@link Timed}. * @since 0.29.3 * @checkstyle JavadocMethodCheck (500 lines) */ public final class TimedFuncTest { @Test(expected = TimeoutException.class) public void functionGetsInterrupted() throws Exception { final long period = 100L; new Timed( input -> { return new And( new Endless<>(() -> input) ).value(); }, period ).apply(true); } @Test @SuppressWarnings("PMD.AvoidCatchingGenericException") public void futureTaskIsCancelled() { final long period = 50L; final long time = 2000L; final Future future = Executors.newSingleThreadExecutor() .submit( () -> { Thread.sleep(time); return true; } ); try { new Timed( period, input -> future ).apply(true); // @checkstyle IllegalCatchCheck (1 line) } catch (final Exception exp) { new Assertion<>( "Must be canceled after 1 sec", future.isCancelled(), new IsTrue() ).affirm(); } } @Test public void functionIsExecuted() throws Exception { final long period = 3000L; new Assertion<>( "Must execute the function", new Timed( input -> true, period ).apply(true), new IsTrue() ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/func/UncheckedBiFuncTest.java000066400000000000000000000043761400054650300254370ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.func; import java.io.IOException; import java.io.UncheckedIOException; import org.junit.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.IsTrue; /** * Test case for {@link UncheckedBiFunc}. * @since 0.13 * @checkstyle JavadocMethodCheck (500 lines) */ public final class UncheckedBiFuncTest { @Test(expected = UncheckedIOException.class) public void rethrowsCheckedToUncheckedException() { new UncheckedBiFunc<>( (fst, scd) -> { throw new IOException("intended"); } ).apply(1, 2); } @Test public void testUncheckedBiFunc() { new Assertion<>( "Must return value", new UncheckedBiFunc<>( (fst, scd) -> true ).apply(1, 2), new IsTrue() ).affirm(); } @Test(expected = IllegalStateException.class) public void runtimeExceptionGoesOut() { new UncheckedBiFunc<>( (fst, scd) -> { throw new IllegalStateException("intended to fail"); } ).apply(1, 2); } } cactoos-0.49/src/test/java/org/cactoos/func/UncheckedFuncTest.java000066400000000000000000000036611400054650300251600ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.func; import java.io.IOException; import java.io.UncheckedIOException; import org.cactoos.Func; import org.junit.Test; /** * Test case for {@link UncheckedFunc}. * * @since 0.2 * @checkstyle JavadocMethodCheck (500 lines) */ public final class UncheckedFuncTest { @Test(expected = UncheckedIOException.class) public void rethrowsCheckedToUncheckedException() { new UncheckedFunc<>( (Func) i -> { throw new IOException("intended"); } ).apply(1); } @Test(expected = IllegalStateException.class) public void runtimeExceptionGoesOut() { new UncheckedFunc<>( i -> { throw new IllegalStateException("intended to fail"); } ).apply(1); } } cactoos-0.49/src/test/java/org/cactoos/func/package-info.java000066400000000000000000000023131400054650300241300ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ /** * Functions, tests. * * @since 0.2 */ package org.cactoos.func; cactoos-0.49/src/test/java/org/cactoos/io/000077500000000000000000000000001400054650300204165ustar00rootroot00000000000000cactoos-0.49/src/test/java/org/cactoos/io/AppendToTest.java000066400000000000000000000074601400054650300236420ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.io; import java.io.File; import java.nio.charset.StandardCharsets; import java.nio.file.NoSuchFileException; import org.cactoos.text.Joined; import org.cactoos.text.Randomized; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.InputHasContent; import org.llorllale.cactoos.matchers.Throws; /** * Test case for {@link AppendTo}. * * @since 1.0 * @checkstyle ClassDataAbstractionCouplingCheck (100 lines) */ public final class AppendToTest { /** * Temporary files and folders generator. */ @Rule public final TemporaryFolder folder = new TemporaryFolder(); /** * Ensures that AppendTo is failing on a negative predicate result. */ @Test public void failsIfFileDoesNotExist() throws Exception { final File source = new File( new Randomized( 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h' ).asString() ); new Assertion<>( "Can't throw exception with proper message", () -> new AppendTo(source).stream(), new Throws<>( source.getPath(), NoSuchFileException.class ) ).affirm(); } /** * Ensures that AppendTo is appending to a given file. * @throws Exception if fails */ @Test public void appendsToFile() throws Exception { final File source = this.folder.newFile(); final String first = "abdcd"; new OutputTo(source).stream().write(first.getBytes()); final String second = "efgh"; new AppendTo(source).stream().write(second.getBytes()); new Assertion<>( "Does not contain expected text", new InputOf(source), new InputHasContent(new Joined("", first, second)) ).affirm(); } /** * Ensures that AppendTo is appending unicode text to a given file. * @throws Exception if fails */ @Test public void appendsUnicodeToFile() throws Exception { final File source = this.folder.newFile(); final String first = "Hello, товарищ output #3 äÄ "; new OutputTo(source) .stream() .write(first.getBytes(StandardCharsets.UTF_8)); final String second = "#4 äÄ üÜ öÖ and ß"; new AppendTo(source) .stream() .write(second.getBytes(StandardCharsets.UTF_8)); new Assertion<>( "Can't find expected unicode text content", new InputOf(source), new InputHasContent(new Joined("", first, second)) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/io/CheckedInputTest.java000066400000000000000000000053241400054650300244730ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.io; import java.io.IOException; import org.hamcrest.core.IsNull; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.Throws; /** * Test case for {@link CheckedInput}. * * @since 0.31 * @checkstyle JavadocMethodCheck (500 lines) */ final class CheckedInputTest { @Test void runtimeExceptionIsNotWrapped() { new Assertion<>( "must not wrap runtime exception", new CheckedInput<>( () -> { throw new IllegalStateException("runtime1"); }, IOException::new )::stream, new Throws<>(IllegalStateException.class) ).affirm(); } @Test void checkedExceptionIsWrapped() { new Assertion<>( "must wrap checked exception", new CheckedInput<>( () -> { throw new IOException("runtime2"); }, IOException::new )::stream, new Throws<>(IOException.class) ).affirm(); } @Test void extraWrappingIgnored() { try { new CheckedInput<>( () -> { throw new IOException("runtime3"); }, IOException::new ).stream(); } catch (final IOException exp) { new Assertion<>( "must not add extra wrapping of IOException", exp.getCause(), new IsNull<>() ).affirm(); } } } cactoos-0.49/src/test/java/org/cactoos/io/CheckedOutputTest.java000066400000000000000000000053311400054650300246720ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.io; import java.io.IOException; import org.hamcrest.core.IsNull; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.Throws; /** * Test case for {@link CheckedOutput}. * * @since 0.31 * @checkstyle JavadocMethodCheck (500 lines) */ final class CheckedOutputTest { @Test void runtimeExceptionIsNotWrapped() { new Assertion<>( "must not wrap runtime exception", new CheckedOutput<>( () -> { throw new IllegalStateException("runtime1"); }, IOException::new )::stream, new Throws<>(IllegalStateException.class) ).affirm(); } @Test void checkedExceptionIsWrapped() { new Assertion<>( "must wrap checked exception", new CheckedOutput<>( () -> { throw new IOException("runtime2"); }, IOException::new )::stream, new Throws<>(IOException.class) ).affirm(); } @Test void extraWrappingIgnored() { try { new CheckedOutput<>( () -> { throw new IOException("runtime3"); }, IOException::new ).stream(); } catch (final IOException exp) { new Assertion<>( "must not add extra wrapping of IOException", exp.getCause(), new IsNull<>() ).affirm(); } } } cactoos-0.49/src/test/java/org/cactoos/io/DeadInputTest.java000066400000000000000000000032641400054650300240030ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.io; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.InputHasContent; /** * Test case for {@link DeadInput}. * * @since 0.16 * @checkstyle JavadocMethodCheck (500 lines) * @checkstyle ClassDataAbstractionCouplingCheck (500 lines) */ final class DeadInputTest { @Test void readsEmptyContent() { new Assertion<>( "must read empty content", new DeadInput(), new InputHasContent("") ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/io/DeadOutputTest.java000066400000000000000000000035341400054650300242040ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.io; import org.hamcrest.Matchers; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.InputHasContent; /** * Test case for {@link DeadOutput}. * * @since 0.16 * @checkstyle JavadocMethodCheck (500 lines) * @checkstyle ClassDataAbstractionCouplingCheck (500 lines) */ final class DeadOutputTest { @Test void readsEmptyContent() { new Assertion<>( "must write empty content", new TeeInput( new InputOf("How are you, мой друг?"), new DeadOutput() ), new InputHasContent(Matchers.endsWith("друг?")) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/io/DirectoryTest.java000066400000000000000000000053251400054650300240720ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.io; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.HasSize; /** * Test case for {@link Directory}. * @since 0.12 * @checkstyle JavadocMethodCheck (500 lines) * @checkstyle ClassDataAbstractionCouplingCheck (500 lines) */ public final class DirectoryTest { /** * Temporary folder. */ @Rule public TemporaryFolder folder = new TemporaryFolder(); @Test public void listsFilesAndFoldersInDirectory() throws IOException { final Path dir = this.folder.newFolder().toPath(); dir.resolve("x/y").toFile().mkdirs(); Files.write(dir.resolve("x/y/test"), "".getBytes()); new Assertion<>( "must list files in a directory represented by a path", new Directory(dir), // @checkstyle MagicNumber (1 line) new HasSize(4) ).affirm(); } @Test public void listsFilesInDirectoryByFile() throws Exception { final File file = this.folder.newFolder(); final Path dir = file.toPath(); dir.resolve("parent/child").toFile().mkdirs(); Files.write(dir.resolve("parent/child/file"), "".getBytes()); new Assertion<>( "must list files in a directory represented by a file", new Directory(file), // @checkstyle MagicNumber (1 line) new HasSize(4) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/io/FakeHandler.java000066400000000000000000000042101400054650300234220ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.io; import java.util.LinkedList; import java.util.List; import java.util.logging.Handler; import java.util.logging.LogRecord; import org.cactoos.text.Joined; import org.cactoos.text.UncheckedText; /** * Fake handler logger. * *

There is no thread-safety guarantee. * @since 0.29 */ public final class FakeHandler extends Handler { /** * Lines. */ private final List entries; /** * Ctor. */ FakeHandler() { super(); this.entries = new LinkedList<>(); } @Override public void publish(final LogRecord record) { this.entries.add(record.getMessage()); } @Override public void close() { // Intended empty. } @Override public void flush() { // Intended empty. } @Override public String toString() { return new UncheckedText( new Joined( System.lineSeparator(), this.entries ) ).asString(); } } cactoos-0.49/src/test/java/org/cactoos/io/FakeLogger.java000066400000000000000000000042661400054650300232770ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.io; import java.util.logging.Level; import java.util.logging.Logger; /** * Fake logger. * *

There is no thread-safety guarantee. * * @since 0.29 */ @SuppressWarnings("PMD.ConstructorOnlyInitializesOrCallOtherConstructors") public final class FakeLogger extends Logger { /** * Ctor. */ public FakeLogger() { this(Level.INFO); } /** * Ctor. * @param lvl Logging level */ public FakeLogger(final Level lvl) { this("FakeLogger", lvl); } /** * Ctor. * @param name Logger name */ public FakeLogger(final String name) { this(name, Level.INFO); } /** * Ctor. * @param name Logger name * @param lvl Logging level */ public FakeLogger(final String name, final Level lvl) { super(name, null); this.setUseParentHandlers(false); this.addHandler(new FakeHandler()); this.setLevel(lvl); } @Override public String toString() { return this.getHandlers()[0].toString(); } } cactoos-0.49/src/test/java/org/cactoos/io/GzipInputTest.java000066400000000000000000000051341400054650300240550ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.io; import java.io.BufferedWriter; import java.io.ByteArrayOutputStream; import java.io.EOFException; import java.io.OutputStreamWriter; import java.io.Writer; import java.util.zip.GZIPOutputStream; import org.cactoos.scalar.LengthOf; import org.cactoos.text.TextOf; import org.hamcrest.core.IsEqual; import org.junit.Test; import org.llorllale.cactoos.matchers.Assertion; /** * Test case for {@link org.cactoos.io.GzipInput}. * @since 0.29 * @checkstyle JavadocMethodCheck (500 lines) * @checkstyle ClassDataAbstractionCouplingCheck (500 lines) */ public final class GzipInputTest { @Test public void readFromGzipInput() throws Exception { final String content = "Hello!"; final ByteArrayOutputStream out = new ByteArrayOutputStream(); try ( Writer writer = new BufferedWriter( new OutputStreamWriter( new GZIPOutputStream(out) ) ) ) { writer.write(content); } final byte[] bytes = out.toByteArray(); new Assertion<>( "Can't read from a gzip input", new TextOf( new GzipInput(new InputOf(bytes)) ).asString(), new IsEqual<>(content) ).affirm(); } @Test(expected = EOFException.class) public void readFromDeadGzipInput() throws Exception { new LengthOf( new GzipInput(new DeadInput()) ).value(); } } cactoos-0.49/src/test/java/org/cactoos/io/GzipOutputTest.java000066400000000000000000000067021400054650300242600ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.io; import java.io.BufferedWriter; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Writer; import java.nio.file.Files; import java.nio.file.Paths; import java.util.zip.GZIPOutputStream; import org.cactoos.scalar.LengthOf; import org.hamcrest.core.IsEqual; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.llorllale.cactoos.matchers.Assertion; /** * Test case for {@link org.cactoos.io.GzipOutput}. * @checkstyle JavadocMethodCheck (500 lines) * @checkstyle ClassDataAbstractionCouplingCheck (500 lines) * @since 0.29 */ @SuppressWarnings("PMD.AvoidDuplicateLiterals") public final class GzipOutputTest { /** * Temporary files and folders generator. */ @Rule public final TemporaryFolder folder = new TemporaryFolder(); @Test public void writeToGzipOutput() throws Exception { final String content = "Hello!"; final ByteArrayOutputStream expected = new ByteArrayOutputStream(); try ( Writer writer = new BufferedWriter( new OutputStreamWriter( new GZIPOutputStream(expected) ) ) ) { writer.write(content); } final ByteArrayOutputStream baos = new ByteArrayOutputStream(); try (OutputStream output = new GzipOutput( new OutputTo(baos) ).stream() ) { new LengthOf( new TeeInput( content, new OutputTo(output) ) ).value(); } new Assertion<>( "Can't write to a gzip output", baos.toByteArray(), new IsEqual<>(expected.toByteArray()) ).affirm(); } @Test(expected = IOException.class) public void writeToClosedGzipOutput() throws Exception { final OutputStream stream = Files.newOutputStream( Paths.get( this.folder.newFile("cactoos.txt").getPath() ) ); stream.close(); new LengthOf( new TeeInput( "Hello!", new GzipOutput(new OutputTo(stream)) ) ).value(); } } cactoos-0.49/src/test/java/org/cactoos/io/HeadInputStreamTest.java000066400000000000000000000074651400054650300251720ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.io; import org.cactoos.text.TextOf; import org.hamcrest.core.IsEqual; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.InputHasContent; import org.llorllale.cactoos.matchers.TextIs; /** * Test cases for {@link HeadInputStream}. * * @since 0.31 * @checkstyle JavadocMethodCheck (500 lines) * @checkstyle MagicNumberCheck (500 lines) * @checkstyle ClassDataAbstractionCouplingCheck (500 lines) */ @SuppressWarnings("PMD.AvoidDuplicateLiterals") final class HeadInputStreamTest { @Test void testSkippingLessThanTotal() throws Exception { final HeadInputStream stream = new HeadInputStream( new InputOf("testSkippingLessThanTotal").stream(), 5 ); final long skipped = stream.skip(3L); new Assertion<>( "Incorrect number of bytes skipped", skipped, new IsEqual<>(3L) ).affirm(); new Assertion<>( "Incorrect head of the input stream has been read", new InputOf(stream), new InputHasContent("tS") ).affirm(); } @Test void testSkippingMoreThanTotal() throws Exception { final HeadInputStream stream = new HeadInputStream( new InputOf("testSkippingMoreThanTotal").stream(), 5 ); final long skipped = stream.skip(7L); new Assertion<>( "Incorrect number of bytes skipped", skipped, new IsEqual<>(5L) ).affirm(); final String input = new TextOf(stream).asString(); new Assertion<>( "The result text wasn't empty", new TextOf(input), new TextIs("") ).affirm(); } @Test void testResetting() throws Exception { final HeadInputStream stream = new HeadInputStream( new InputOf("testResetting").stream(), 5 ); final long skipped = stream.skip(7L); new Assertion<>( "Incorrect number of bytes skipped", skipped, new IsEqual<>(5L) ).affirm(); stream.reset(); new Assertion<>( "Reset didn't change the state", new InputOf(stream), new InputHasContent("testR") ).affirm(); } @Test void testAvailableLessThanTotal() throws Exception { final HeadInputStream stream = new HeadInputStream( new InputOf("testAvailableLessThanTotal").stream(), 5 ); new Assertion<>( "must count available bytes", stream.available(), new IsEqual<>(5) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/io/HeadOfTest.java000066400000000000000000000052121400054650300232470ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.io; import org.cactoos.text.TextOf; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.TextHasString; /** * Test cases for {@link HeadOf}. * * @since 0.31 * @checkstyle JavadocMethodCheck (500 lines) * @checkstyle MagicNumberCheck (500 lines) */ final class HeadOfTest { @Test void readsHeadOfLongerInput() throws Exception { new Assertion<>( "must limit exactly the number of read bytes", new TextOf( new HeadOf( new InputOf("readsHeadOfLongerInput"), 5 ) ), new TextHasString("reads") ).affirm(); } @Test void readsEmptyHeadOfInput() throws Exception { new Assertion<>( "must limit to 0 the number of read bytes", new TextOf( new HeadOf( new InputOf("readsEmptyHeadOfInput"), 0 ) ), new TextHasString("") ).affirm(); } @Test void readsHeadOfShorterInput() throws Exception { final String input = "readsHeadOfShorterInput"; new Assertion<>( "must limit to at most the number of available bytes", new TextOf( new HeadOf( new InputOf(input), 35 ) ), new TextHasString(input) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/io/InputNoNullsTest.java000066400000000000000000000033411400054650300245340ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.io; import org.junit.Test; /** * Test case for {@link InputNoNulls}. * @since 0.10 * @checkstyle JavadocMethodCheck (500 lines) */ public final class InputNoNullsTest { @Test(expected = Exception.class) public void failForNullInput() throws Exception { new InputNoNulls(null).stream(); } @Test(expected = Exception.class) public void failForNullStream() throws Exception { new InputNoNulls(() -> null).stream(); } @Test public void okForNoNullInput() throws Exception { new InputNoNulls(new DeadInput()).stream(); } } cactoos-0.49/src/test/java/org/cactoos/io/InputOfTest.java000066400000000000000000000301551400054650300235110ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.io; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.StringReader; import java.net.URL; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.security.SecureRandom; import java.security.cert.X509Certificate; import java.util.concurrent.atomic.AtomicBoolean; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import org.cactoos.bytes.BytesOf; import org.cactoos.iterable.IterableOf; import org.cactoos.text.TextOf; import org.hamcrest.core.AllOf; import org.hamcrest.core.IsEqual; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.EndsWith; import org.llorllale.cactoos.matchers.InputHasContent; import org.llorllale.cactoos.matchers.MatcherOf; import org.llorllale.cactoos.matchers.MatchesRegex; import org.llorllale.cactoos.matchers.StartsWith; import org.llorllale.cactoos.matchers.TextHasString; import org.takes.http.FtRemote; import org.takes.tk.TkHtml; /** * Test case for {@link InputOf}. * * @since 0.1 * @checkstyle JavadocMethodCheck (500 lines) * @checkstyle ClassDataAbstractionCouplingCheck (500 lines) * @checkstyle ClassFanOutComplexityCheck (500 lines) */ @SuppressWarnings({ "PMD.TooManyMethods", "PMD.ExcessiveImports", "unchecked" }) public final class InputOfTest { /** * Temporary files and folders generator. */ @Rule public final TemporaryFolder folder = new TemporaryFolder(); @Test public void readsAlternativeInputForFileCase() { new Assertion<>( "must read alternative source from file not found", new TextOf( new InputWithFallback( new InputOf( new File("/this-file-does-not-exist.txt") ), new InputOf(new TextOf("Alternative text!")) ) ), new EndsWith("text!") ).affirm(); } @Test public void readsSimpleFileContent() throws IOException { final Path temp = this.folder.newFile("cactoos-1.txt-1") .toPath(); final String content = "Hello, товарищ!"; Files.write(temp, content.getBytes(StandardCharsets.UTF_8)); new Assertion<>( "must read file content", new InputOf(temp), new InputHasContent(content) ).affirm(); } @Test public void closesInputStream() throws Exception { final AtomicBoolean closed = new AtomicBoolean(); final InputStream input = new ByteArrayInputStream( "how are you?".getBytes() ); new Assertion<>( "must close InputStream correctly", new TextOf( new InputOf( new InputStream() { @Override public int read() throws IOException { return input.read(); } @Override public void close() throws IOException { input.close(); closed.set(true); } } ) ).asString(), new MatcherOf<>( text -> { return closed.get(); } ) ).affirm(); } @Test public void readsFileContent() throws Exception { new Assertion<>( "must read bytes from a file-system URL", new BytesOf( new InputOf( this.getClass().getResource( "/org/cactoos/io/InputOf.class" ) ) ).asBytes().length, new MatcherOf<>(len -> len > 0) ).affirm(); } @Test public void readsRealUrl() throws IOException { new FtRemote(new TkHtml("How are you?")).exec( home -> new Assertion<>( "must fetch bytes from the URL", new TextOf( new InputOf(home) ), new MatchesRegex("") ).affirm() ); } @Test public void readsStringUrl() throws IOException { new Assertion<>( "must fetch bytes from the HTTPS URL", new TextOf( new BytesOf( new InputOf( new URL( // @checkstyle LineLength (1 line) "file:src/test/resources/org/cactoos/large-text.txt" ) ) ) ), new TextHasString("Lorem ipsum") ).affirm(); } @Test public void readsStringIntoBytes() throws Exception { new Assertion<>( "must read bytes from Input", new TextOf( new BytesOf( new InputOf("Hello, друг!") ), StandardCharsets.UTF_8 ), new AllOf<>( new IterableOf<>( new StartsWith("Hello, "), new EndsWith("друг!") ) ) ).affirm(); } @Test public void readsStringBuilder() throws Exception { final String starts = "Name it, "; final String ends = "then it exists!"; new Assertion<>( "must receive a string builder", new TextOf( new BytesOf( new InputOf( new StringBuilder(starts) .append(ends) ) ) ), new AllOf<>( new IterableOf<>( new StartsWith(starts), new EndsWith(ends) ) ) ).affirm(); } @Test public void readsStringBuffer() throws Exception { final String starts = "The future "; final String ends = "is now!"; new Assertion<>( "must receive a string buffer", new TextOf( new BytesOf( new InputOf( new StringBuffer(starts) .append(ends) ) ) ), new AllOf<>( new IterableOf<>( new StartsWith(starts), new EndsWith(ends) ) ) ).affirm(); } @Test public void readsArrayOfChars() throws Exception { new Assertion<>( "must read array of chars.", new TextOf( new BytesOf( new InputOf( 'H', 'o', 'l', 'd', ' ', 'i', 'n', 'f', 'i', 'n', 'i', 't', 'y' ) ) ), new AllOf<>( new IterableOf<>( new StartsWith("Hold "), new EndsWith("infinity") ) ) ).affirm(); } @Test public void readsEncodedArrayOfChars() throws Exception { new Assertion<>( "must read array of encoded chars.", new TextOf( new BytesOf( new InputOf( new char[]{ 'O', ' ', 'q', 'u', 'e', ' ', 's', 'e', 'r', 'a', ' ', 'q', 'u', 'e', ' ', 's', 'e', 'r', 'a', }, StandardCharsets.UTF_8 ) ), StandardCharsets.UTF_8 ), new AllOf<>( new IterableOf<>( new StartsWith("O que sera"), new EndsWith(" que sera") ) ) ).affirm(); } @Test public void readsStringFromReader() throws Exception { final String source = "hello, source!"; new Assertion<>( "must read string through a reader", new TextOf( new InputOf( new StringReader(source) ) ).asString(), new IsEqual<>(source) ).affirm(); } @Test public void readsEncodedStringFromReader() throws Exception { final String source = "hello, друг!"; new Assertion<>( "must read encoded string through a reader", new TextOf( new BytesOf( new InputOf( new StringReader(source), StandardCharsets.UTF_8 ) ) ).asString(), new IsEqual<>(source) ).affirm(); } @Test public void readsAnArrayOfBytes() throws Exception { final byte[] bytes = new byte[] {(byte) 0xCA, (byte) 0xFE}; new Assertion<>( "must read array of bytes", new BytesOf( new SyncInput(new InputOf(bytes)) ).asBytes(), new IsEqual<>(bytes) ).affirm(); } @Test public void makesDataAvailable() throws Exception { final String content = "Hello,חבר!"; new Assertion<>( "must show that data is available", new InputOf(content).stream().available(), new MatcherOf<>(avl -> avl > 0) ).affirm(); } @Test // @checkstyle MethodBodyCommentsCheck (50 lines) public void readsSecureUrlContent() throws Exception { final TrustManager[] managers = { new X509TrustManager() { @Override public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } @Override public void checkClientTrusted( final X509Certificate[] cert, final String arg) { // nothing to do } @Override public void checkServerTrusted( final X509Certificate[] cert, final String arg) { // nothing to do } }, }; final SSLContext context = SSLContext.getInstance("TLS"); context.init(null, managers, new SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory( context.getSocketFactory() ); new Assertion<>( "Can't read bytes from HTTPS URL", new BytesOf( new InputOf( new URL( "https://www.yegor256.com/robots.txt" ) ) ).asBytes().length, new MatcherOf<>(len -> len > 0) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/io/InputStreamOfTest.java000066400000000000000000000212761400054650300246710ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.io; import java.io.File; import java.io.IOException; import java.io.StringReader; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import org.cactoos.bytes.BytesOf; import org.cactoos.scalar.LengthOf; import org.cactoos.text.TextOf; import org.hamcrest.Matchers; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.InputHasContent; /** * Test case for {@link InputStreamOf}. * * @since 0.13 * @checkstyle JavadocMethodCheck (500 lines) * @checkstyle ClassDataAbstractionCouplingCheck (500 lines) */ @SuppressWarnings("PMD.TooManyMethods") public final class InputStreamOfTest { /** * Temporary files and folders generator. */ @Rule public final TemporaryFolder folder = new TemporaryFolder(); @Test public void readsSimpleFileContent() throws IOException { final Path temp = this.folder.newFile("cactoos-1.txt-1") .toPath(); final String content = "Hello, товарищ!"; Files.write(temp, content.getBytes(StandardCharsets.UTF_8)); new Assertion<>( "Can't read file content", new InputOf(new InputStreamOf(temp)), new InputHasContent(content) ).affirm(); } @Test public void readsFromReader() { final String content = "Hello, дорогой товарищ!"; new Assertion<>( "Can't read from reader", new InputOf(new InputStreamOf(new StringReader(content))), new InputHasContent(content) ); } @Test public void readsFromReaderThroughSmallBuffer() { final String content = "Hello, صديق!"; new Assertion<>( "Can't read from reader through small buffer", new InputOf(new InputStreamOf(new StringReader(content), 1)), new InputHasContent(content) ); } @Test public void makesDataAvailable() throws IOException { final String content = "Hello,חבר!"; new Assertion<>( "Can't show that data is available", new InputStreamOf(content).available(), Matchers.greaterThan(0) ); } @Test public void readsFileContent() throws Exception { final File file = this.folder.newFile("readFileContent.txt-2"); final String content = "Content in a file"; new LengthOf( new TeeInput(content, file) ).intValue(); new Assertion<>( "Can't read from file", new TextOf(new InputStreamOf(file)).asString(), Matchers.equalTo(content) ); } @Test public void readsBytes() throws Exception { final String content = "Bytes content"; new Assertion<>( "Can't read from bytes", new TextOf(new InputStreamOf(new BytesOf(content))).asString(), Matchers.equalTo(content) ); } @Test public void readsBytesArray() throws Exception { final String content = "Bytes array content"; final byte[] bytes = new BytesOf(content).asBytes(); new Assertion<>( "Can't read from byte array", new TextOf(new InputStreamOf(bytes)).asString(), Matchers.equalTo(content) ); } @Test public void readsText() throws Exception { final String content = "Text content"; new Assertion<>( "Can't read from text", new TextOf(new InputStreamOf(new TextOf(content))).asString(), Matchers.equalTo(content) ); } @Test public void readsFromUri() throws Exception { final String content = "Content for reading through URI"; final File file = this.folder.newFile("readFromUri.txt-3"); new LengthOf( new TeeInput(content, file) ).intValue(); new Assertion<>( "Can't read from URI", new TextOf(new InputStreamOf(file.toURI())).asString(), Matchers.equalTo(content) ); } @Test public void readsFromUrl() throws Exception { final String content = "Content for reading through URL"; final File file = this.folder.newFile("readFromUrl.txt-4"); new LengthOf( new TeeInput(content, file) ).intValue(); new Assertion<>( "Can't read from URL", new TextOf(new InputStreamOf(file.toURI().toURL())).asString(), Matchers.equalTo(content) ); } @Test public void readsFromReaderWithMax() throws Exception { final String content = "Reading with charset name and buffer size"; final int max = 3; new Assertion<>( "Can't read from reader with charset name and buffer size", new TextOf( new InputStreamOf( new StringReader(content), StandardCharsets.UTF_8.name(), max ) ).asString(), Matchers.equalTo(content) ); } @Test public void readsFromReaderWithCharsetWithMax() throws Exception { final String content = "Reading with charset and buffer size"; new Assertion<>( "Can't read from reader with charset and buffer size", new TextOf( new InputStreamOf( new StringReader(content), StandardCharsets.UTF_8, 1 ) ).asString(), Matchers.equalTo(content) ); } @Test public void readsFromReaderWithCharset() throws Exception { final String content = "Content for reading with charset"; new Assertion<>( "Can't read from reader with charset name", new TextOf( new InputStreamOf( new StringReader(content), StandardCharsets.UTF_8.name() ) ).asString(), Matchers.equalTo(content) ); } @Test public void readsFromTextWithCharset() throws Exception { final File file = this.folder.newFile("readTextWithCharset.txt-5"); final String content = "Content for reading text with charset"; new LengthOf( new TeeInput(content, file) ).intValue(); new Assertion<>( "Can't read from text with charset", new TextOf( new InputStreamOf( new TextOf(file), StandardCharsets.UTF_8.name() ) ).asString(), Matchers.equalTo(content) ); } @Test public void readsFromCharSequenceWithCharsetName() throws Exception { final String content = "Simple content"; new Assertion<>( "Can't read from char sequence with charset name", new TextOf( new InputStreamOf( content, StandardCharsets.UTF_8.name() ) ).asString(), Matchers.equalTo(content) ); } @Test public void readsFromCharSequenceWithCharset() throws Exception { final String content = "Another simple content"; new Assertion<>( "Can't read from char sequence with charset", new TextOf( new InputStreamOf( content, StandardCharsets.UTF_8 ) ).asString(), Matchers.equalTo(content) ); } } cactoos-0.49/src/test/java/org/cactoos/io/InputWithFallbackTest.java000066400000000000000000000046101400054650300254750ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.io; import java.io.File; import java.io.IOException; import org.cactoos.text.TextOf; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.EndsWith; /** * Test case for {@link InputWithFallback}. * * @since 0.9 * @checkstyle JavadocMethodCheck (500 lines) */ final class InputWithFallbackTest { @Test void readsAlternativeInput() { new Assertion<>( "Can't read alternative source", new TextOf( new InputWithFallback( new InputOf( new File("/this-file-is-absent-for-sure.txt") ), new InputOf("hello, world!") ) ), new EndsWith("world!") ).affirm(); } @Test void readsAlternativeInputUri() { new Assertion<>( "Can't read alternative source from URI", new TextOf( new InputWithFallback( () -> { throw new IOException("Always fails!"); }, new InputOf("it works!") ) ), new EndsWith("works!") ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/io/JoinedTest.java000066400000000000000000000046001400054650300233310ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.io; import java.io.IOException; import org.cactoos.iterable.IterableOf; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.InputHasContent; /** * Unit tests for {@link Joined}. * @since 0.36 * @checkstyle ClassDataAbstractionCouplingCheck (500 lines) */ final class JoinedTest { /** * Must join inputs in the given order. * @throws IOException If an error occurs */ @Test void joinsOk() { new Assertion<>( "Cannot properly join inputs", new Joined( new InputOf("first"), new InputOf("second"), new InputOf("third") ), new InputHasContent("firstsecondthird") ).affirm(); } /** * Must join inputs of the iterable in the given order. */ @Test void fromIterable() { new Assertion<>( "Can't join iterable of inputs", new Joined( new IterableOf<>( new InputOf("ab"), new InputOf("cde"), new InputOf("fghi") ) ), new InputHasContent("abcdefghi") ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/io/LSInputOfTest.java000066400000000000000000000047061400054650300237530ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.io; import org.hamcrest.Matchers; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; /** * Test case for {@link LSInputOf}. * * @since 0.12 * @checkstyle JavadocMethodCheck (500 lines) * @checkstyle AbbreviationAsWordInNameCheck (5 lines) */ final class LSInputOfTest { @Test void readsSimpleInput() { new Assertion<>( "Can't read simple input", new LSInputOf( new InputOf("hello, world!") ).getStringData(), Matchers.endsWith("world!") ).affirm(); } @Test void readsBiggerInput() { final int size = 400_000; new Assertion<>( "Can't read bigger input", new LSInputOf( new InputOf( new SlowInputStream(size) ) ).getStringData().length(), Matchers.equalTo(size) ).affirm(); } @Test void countsBytesInBiggerInput() { final int size = 300_000; new Assertion<>( "Can't count bytes in a bigger input", new LSInputOf( new InputOf( new SlowInputStream(size) ) ).getStringData().length(), Matchers.equalTo(size) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/io/LoggingInputStreamTest.java000066400000000000000000000071351400054650300257110ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.io; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import org.hamcrest.core.IsEqual; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.Throws; /** * Test case for {@link LoggingInputStream}. * * @since 0.39 * @checkstyle JavadocMethodCheck (500 lines) */ final class LoggingInputStreamTest { @Test void reThrowsException() { final String message = "Some read exception."; final LoggingInputStream stream = new LoggingInputStream( new InputStream() { @Override public int read() throws IOException { throw new IOException(message); } }, this.getClass().getSimpleName() ); new Assertion<>( "Read doesn't throw an the exception.", () -> stream.read(), new Throws<>(message, IOException.class) ).affirm(); } @Test void readEmptyStream() throws IOException { final LoggingInputStream stream = new LoggingInputStream( new ByteArrayInputStream( "".getBytes() ), this.getClass().getSimpleName() ); new Assertion<>( "Empty stream did not return -1", stream.read(), // @checkstyle MagicNumberCheck (1 line) new IsEqual<>(-1) ).affirm(); } @Test void readByteByByte() throws IOException { final LoggingInputStream stream = new LoggingInputStream( new ByteArrayInputStream( new byte[] { // @checkstyle MagicNumberCheck (2 lines) (byte) 20, (byte) 10, } ), this.getClass().getSimpleName() ); new Assertion<>( "First byte was not 20", stream.read(), // @checkstyle MagicNumberCheck (1 line) new IsEqual<>(20) ).affirm(); new Assertion<>( "Second byte was not 10", stream.read(), // @checkstyle MagicNumberCheck (1 line) new IsEqual<>(10) ).affirm(); new Assertion<>( "When stream is exhausted it didn't return -1", stream.read(), // @checkstyle MagicNumberCheck (1 line) new IsEqual<>(-1) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/io/LoggingInputTest.java000066400000000000000000000175161400054650300245410ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.io; import java.io.IOException; import java.io.InputStream; import java.util.logging.Level; import java.util.logging.Logger; import org.cactoos.scalar.LengthOf; import org.hamcrest.Matchers; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; /** * Test case for {@link LoggingInput}. * * @since 0.29 * @checkstyle JavadocMethodCheck (500 lines) * @checkstyle ClassDataAbstractionCouplingCheck (500 lines) */ @SuppressWarnings( { "PMD.MoreThanOneLogger", "PMD.AvoidDuplicateLiterals" } ) final class LoggingInputTest { @Test void logReadFromDeadInput() throws IOException { final Logger logger = new FakeLogger(); new LengthOf( new LoggingInput( new DeadInput(), "dead input", logger ) ).intValue(); new Assertion<>( "Can't log zero byte read from dead input", logger.toString(), Matchers.containsString("Read 0 byte(s) from dead input in") ).affirm(); } @Test void logReadFromOneByte() throws IOException { final Logger logger = new FakeLogger(); new LengthOf( new LoggingInput( new InputOf("a"), "memory", logger ) ).intValue(); new Assertion<>( "Can't log one byte read from memory", logger.toString(), Matchers.containsString("Read 1 byte(s) from memory in") ).affirm(); } @Test void logReadFromText() throws IOException { final Logger logger = new FakeLogger(); new LengthOf( new LoggingInput( new InputOf("Hello, товарищ!"), "memory", logger ) ).intValue(); new Assertion<>( "Can't log 22 bytes read from memory", logger.toString(), Matchers.containsString("Read 22 byte(s) from memory in") ).affirm(); } @Test void logReadFromLargeTextFile() throws IOException { final Logger logger = new FakeLogger(); new LengthOf( new LoggingInput( new ResourceOf("org/cactoos/large-text.txt"), "text file", logger ) ).intValue(); new Assertion<>( "Can't log 74536 bytes read from text file", logger.toString(), Matchers.allOf( Matchers.not( Matchers.containsString("Read 16384 byte(s) from text file") ), Matchers.containsString("Read 74536 byte(s) from text file in"), Matchers.containsString("Closed input stream from text file") ) ).affirm(); } @Test void logAllFromLargeTextFile() throws IOException { final Logger logger = new FakeLogger(Level.WARNING); new LengthOf( new LoggingInput( new ResourceOf("org/cactoos/large-text.txt"), "text file", logger ) ).intValue(); new Assertion<>( "Can't log all read and close operations from text file", logger.toString(), Matchers.allOf( Matchers.containsString("Read 16384 byte(s) from text file"), Matchers.containsString("Read 32768 byte(s) from text file"), Matchers.containsString("Read 49152 byte(s) from text file"), Matchers.containsString("Read 65536 byte(s) from text file"), Matchers.containsString("Read 74536 byte(s) from text file"), Matchers.containsString("Closed input stream from text file") ) ).affirm(); } @Test void logSkipFromLargeTextFile() throws Exception { final Logger logger = new FakeLogger(); new LoggingInput( new ResourceOf("org/cactoos/large-text.txt"), "text file", logger // @checkstyle MagicNumber (1 line) ).stream().skip(100); new Assertion<>( "Can't log skip from text file", logger.toString(), Matchers.containsString("Skipped 100 byte(s) from text file.") ).affirm(); } @Test void logAvailableFromLargeTextFile() throws Exception { final Logger logger = new FakeLogger(); new LoggingInput( new ResourceOf("org/cactoos/large-text.txt"), "text file", logger ).stream().available(); new Assertion<>( "Can't log avaliable byte(s) from text file", logger.toString(), Matchers.containsString( "There is(are) 74536 byte(s) available from text file" ) ).affirm(); } @Test void logResetFromLargeTextFile() throws Exception { final Logger logger = new FakeLogger(); final InputStream input = new LoggingInput( new ResourceOf("org/cactoos/large-text.txt"), "text file", logger ).stream(); // @checkstyle MagicNumber (1 line) input.mark(150); input.reset(); new Assertion<>( "Can't log mark and reset from text file", logger.toString(), Matchers.allOf( Matchers.containsString("Marked position 150 from text file"), Matchers.containsString("Reset input stream from text file") ) ).affirm(); } @Test void logMarkSupportedFromLargeTextFile() throws Exception { final Logger logger = new FakeLogger(); new LoggingInput( new ResourceOf("org/cactoos/large-text.txt"), "text file", logger ).stream().markSupported(); new Assertion<>( "Can't log mark and reset are not supported from text file", logger.toString(), Matchers.containsString( "Mark and reset are supported from text file" ) ).affirm(); } @Test void logIntoCreatedLogger() { final FakeHandler handler = new FakeHandler(); final String src = "my source"; final Logger logger = Logger.getLogger(src); logger.addHandler(handler); try { new LengthOf( new LoggingInput( new InputOf("Hi there"), src ) ).intValue(); new Assertion<>( "", handler.toString(), Matchers.containsString("Read 8 byte(s)") ).affirm(); } finally { logger.removeHandler(handler); } } } cactoos-0.49/src/test/java/org/cactoos/io/LoggingOutputTest.java000066400000000000000000000141151400054650300247320ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.io; import java.io.ByteArrayOutputStream; import java.io.OutputStream; import java.nio.file.Path; import java.util.logging.Level; import java.util.logging.Logger; import org.cactoos.bytes.BytesOf; import org.cactoos.scalar.LengthOf; import org.hamcrest.Matchers; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.llorllale.cactoos.matchers.Assertion; /** * Test case for {@link LoggingOutput}. * * @since 0.29 * @checkstyle JavadocMethodCheck (500 lines) * @checkstyle ClassDataAbstractionCouplingCheck (500 lines) */ @SuppressWarnings( { "PMD.MoreThanOneLogger", "PMD.AvoidDuplicateLiterals" } ) public final class LoggingOutputTest { /** * Temporary files and folders generator. */ @Rule public final TemporaryFolder folder = new TemporaryFolder(); @Test public void logWriteZero() { final Logger logger = new FakeLogger(); new LengthOf( new TeeInput( new InputOf(""), new LoggingOutput( () -> new ByteArrayOutputStream(), "memory", logger ) ) ).intValue(); new Assertion<>( "Can't log zero byte written to memory", logger.toString(), Matchers.containsString("Written 0 byte(s) to memory in ") ).affirm(); } @Test public void logWriteOneByte() throws Exception { final Logger logger = new FakeLogger(); try ( OutputStream out = new LoggingOutput( ByteArrayOutputStream::new, "memory", logger ).stream() ) { out.write(new BytesOf("a").asBytes()); } new Assertion<>( "Can't log one byte written to memory", logger.toString(), Matchers.containsString("Written 1 byte(s) to memory in") ).affirm(); } @Test public void logWriteText() throws Exception { final Logger logger = new FakeLogger(); try ( OutputStream out = new LoggingOutput( ByteArrayOutputStream::new, "memory", logger ).stream() ) { out.write(new BytesOf("Hello, товарищ!").asBytes()); } new Assertion<>( "Can't log 22 bytes written to memory", logger.toString(), Matchers.containsString("Written 22 byte(s) to memory in") ).affirm(); } @Test public void logWriteToLargeTextFile() throws Exception { final Logger logger = new FakeLogger(); final Path temp = this.folder.newFolder("ccts-1").toPath(); final Path path = temp.resolve("x/y/z/file.txt"); try (OutputStream output = new LoggingOutput( new OutputTo(path), "text file", logger ).stream() ) { new LengthOf( new TeeInput( new ResourceOf("org/cactoos/large-text.txt"), new OutputTo(output) ) ).intValue(); } new Assertion<>( "Can't log write and close operations to text file", logger.toString(), Matchers.allOf( Matchers.not( Matchers.containsString( "Written 16384 byte(s) to text file" ) ), Matchers.containsString("Written 74536 byte(s) to text file"), Matchers.containsString("Closed output stream from text file") ) ).affirm(); } @Test public void logAllWriteToLargeTextFile() throws Exception { final Logger logger = new FakeLogger(Level.WARNING); final Path temp = this.folder.newFolder("ccts-2").toPath(); final Path path = temp.resolve("a/b/c/file.txt"); try (OutputStream output = new LoggingOutput( new OutputTo(path), "text file", logger ).stream() ) { new LengthOf( new TeeInput( new ResourceOf("org/cactoos/large-text.txt"), new OutputTo(output) ) ).intValue(); } new Assertion<>( "Can't log all write and close operations to text file", logger.toString(), Matchers.allOf( Matchers.containsString("Written 16384 byte(s) to text file"), Matchers.containsString("Written 32768 byte(s) to text file"), Matchers.containsString("Written 49152 byte(s) to text file"), Matchers.containsString("Written 65536 byte(s) to text file"), Matchers.containsString("Written 74536 byte(s) to text file"), Matchers.containsString("Closed output stream from text file") ) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/io/OutputNoNullsTest.java000066400000000000000000000033511400054650300247360ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.io; import org.junit.Test; /** * Test case for {@link OutputNoNulls}. * @since 0.10 * @checkstyle JavadocMethodCheck (500 lines) */ public final class OutputNoNullsTest { @Test(expected = Exception.class) public void failForNullOutput() throws Exception { new OutputNoNulls(null).stream(); } @Test(expected = Exception.class) public void failForNullStream() throws Exception { new OutputNoNulls(() -> null).stream(); } @Test public void okForNoNullOutput() throws Exception { new OutputNoNulls(new DeadOutput()).stream(); } } cactoos-0.49/src/test/java/org/cactoos/io/OutputStreamToTest.java000066400000000000000000000045631400054650300251100ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.io; import java.io.IOException; import java.nio.file.Path; import org.cactoos.text.TextOf; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.TextIs; /** * Test case for {@link OutputStreamTo}. * * @since 0.13 * @checkstyle JavadocMethodCheck (500 lines) * @checkstyle ClassDataAbstractionCouplingCheck (500 lines) */ public final class OutputStreamToTest { /** * Temporary files and folders generator. */ @Rule public final TemporaryFolder folder = new TemporaryFolder(); @Test public void writesLargeContentToFile() throws IOException { final Path temp = this.folder.newFile("cactoos-1.txt-1") .toPath(); new Assertion<>( "Must copy Input to Output and return Input", new TextOf( new Sticky( new TeeInput( new ResourceOf("org/cactoos/large-text.txt"), new OutputTo(new OutputStreamTo(temp)) ) ) ), new TextIs( new TextOf(temp) ) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/io/OutputToTest.java000066400000000000000000000144271400054650300237340ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.io; import java.io.IOException; import java.io.StringWriter; import java.nio.charset.StandardCharsets; import java.nio.file.Path; import org.cactoos.scalar.LengthOf; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.InputHasContent; /** * Test case for {@link OutputTo}. * * @since 0.15 * @checkstyle JavadocMethodCheck (500 lines) * @checkstyle ClassDataAbstractionCouplingCheck (500 lines) */ public final class OutputToTest { /** * Temporary folder. */ @Rule public TemporaryFolder folder = new TemporaryFolder(); @Test public void writesIntoPath() throws IOException { final Path temp = this.folder.newFolder("cactoos-1").toPath(); final Path path = temp.resolve("one/two/three/file.txt"); final String content = "Hello, товарищ!"; new LengthOf(new TeeInput(content, new OutputTo(path))).intValue(); new Assertion<>( "Must write into path", new InputOf(path), new InputHasContent(content) ).affirm(); } @Test public void writesIntoFile() throws IOException { final Path temp = this.folder.newFolder("cactoos-2").toPath(); final Path path = temp.resolve("a/b/c/file.txt"); final String txt = "Hello, друг!"; new LengthOf( new TeeInput(txt, new SyncOutput(new OutputTo(path.toFile()))) ).intValue(); new Assertion<>( "Must write into file", new InputOf(path.toFile()), new InputHasContent(txt) ).affirm(); } @Test public void writesIntoWriter() { final String txt = "Hello, writer!"; final StringWriter output = new StringWriter(); new LengthOf(new TeeInput(txt, new OutputTo(output))).intValue(); new Assertion<>( "Must write into writer", new InputOf(output.getBuffer()), new InputHasContent(txt) ).affirm(); } @Test public void writesIntoWriterWithCharset() { final String txt = "Hello, writer with charset!"; final StringWriter output = new StringWriter(); new LengthOf( new TeeInput(txt, new OutputTo(output, StandardCharsets.UTF_8)) ).intValue(); new Assertion<>( "Must write into writer with charset", new InputOf(output.getBuffer()), new InputHasContent(txt) ).affirm(); } @Test public void writesIntoWriterWithCharsetByName() { final String txt = "Hello, writer with charset by name!"; final StringWriter output = new StringWriter(); new LengthOf( new TeeInput(txt, new OutputTo(output, StandardCharsets.UTF_8)) ).intValue(); new Assertion<>( "Must write into writer with charset by name", new InputOf(output.getBuffer()), new InputHasContent(txt) ).affirm(); } @Test public void writesIntoWriterWithCharsetAndSize() { final String txt = "Hello, writer with charset and size!"; final StringWriter output = new StringWriter(); new LengthOf( new TeeInput( txt, new OutputTo(output, StandardCharsets.UTF_8, 1) ) ).intValue(); new Assertion<>( "Must write into writer with charset and size", new InputOf(output.getBuffer()), new InputHasContent(txt) ).affirm(); } @Test public void writesIntoWriterWithSize() { final String txt = "Hello, writer with size!"; final StringWriter output = new StringWriter(); new LengthOf( new TeeInput( txt, new OutputTo(output, 1) ) ).intValue(); new Assertion<>( "Must write into writer with size", new InputOf(output.getBuffer()), new InputHasContent(txt) ).affirm(); } @Test public void writesIntoWriterWithCharsetByNameAndSize() { final String txt = "Hello, writer with charset by name and size!"; final StringWriter output = new StringWriter(); new LengthOf( new TeeInput( txt, new OutputTo(output, StandardCharsets.UTF_8.name(), 1) ) ).intValue(); new Assertion<>( "Must write into writer with charset by name and size", new InputOf(output.getBuffer()), new InputHasContent(txt) ).affirm(); } @Test public void writesIntoWriterWithDecoderAndSize() { final String txt = "Hello, writer with decoder and size!"; final StringWriter output = new StringWriter(); new LengthOf( new TeeInput( txt, new OutputTo(output, StandardCharsets.UTF_8.newDecoder(), 1) ) ).intValue(); new Assertion<>( "Must write into writer with decoder and size", new InputOf(output.getBuffer()), new InputHasContent(txt) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/io/ReaderOfTest.java000066400000000000000000000315521400054650300236160ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.io; import java.io.File; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import org.cactoos.bytes.BytesOf; import org.cactoos.text.TextOf; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.TextIs; /** * Test case for {@link ReaderOf}. * @since 0.13 * @checkstyle JavadocMethodCheck (500 lines) * @checkstyle ClassDataAbstractionCouplingCheck (500 lines) */ @SuppressWarnings("PMD.TooManyMethods") public final class ReaderOfTest { /** * Temporary files generator. */ @Rule public TemporaryFolder folder = new TemporaryFolder(); @Test public void readsEmpty() throws Exception { final String empty = ""; new Assertion<>( "Must read empty string", new TextOf(new ReaderOf(empty)), new TextIs(empty) ).affirm(); } @Test public void readsCharVarArg() throws Exception { new Assertion<>( "Must read chars var args", new TextOf(new ReaderOf('a', 'b', 'c')), new TextIs("abc") ).affirm(); } @Test public void readsCharArrayWithCharset() throws Exception { final String message = "char array on äÄ üÜ öÖ ß жш"; new Assertion<>( "Must read chars var args with charset", new TextOf( new ReaderOf( message.toCharArray(), StandardCharsets.UTF_8 ) ), new TextIs(message) ).affirm(); } @Test public void readsCharArrayWithCharsetByName() throws Exception { final String message = "char array with charset on äÄ üÜ öÖ ß жш"; new Assertion<>( "Must read chars array with charset", new TextOf( new ReaderOf( message.toCharArray(), StandardCharsets.UTF_8.name() ) ), new TextIs(message) ).affirm(); } @Test public void readsByteArray() throws Exception { final String message = "byte array on äÄ üÜ öÖ ß жш"; new Assertion<>( "Must read bytes array", new TextOf( new ReaderOf( message.getBytes(StandardCharsets.UTF_8) ) ), new TextIs(message) ).affirm(); } @Test public void readsByteArrayWithCharset() throws Exception { final String message = "byte array with charset on äÄ üÜ öÖ ß жш"; new Assertion<>( "Must read bytes array with charset", new TextOf( new ReaderOf( message.getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8 ) ), new TextIs(message) ).affirm(); } @Test public void readsByteArrayWithCharsetByName() throws Exception { final String message = "bte array with charset by name on äÄ üÜ öÖ ß жш"; new Assertion<>( "Must read bytes array with charset by name", new TextOf( new ReaderOf( message.getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8.name() ) ), new TextIs(message) ).affirm(); } @Test public void readsPath() throws Exception { final String message = "path on äÄ üÜ öÖ ß жш"; final File input = this.folder.newFile(); Files.write( input.toPath(), message.getBytes(StandardCharsets.UTF_8) ); new Assertion<>( "Must read from path", new TextOf(new ReaderOf(input)), new TextIs(message) ).affirm(); } @Test public void readsFile() throws Exception { final String message = "file on äÄ üÜ öÖ ß жш"; final File input = this.folder.newFile(); Files.write( input.toPath(), message.getBytes(StandardCharsets.UTF_8) ); new Assertion<>( "Must read from file", new TextOf(new ReaderOf(input)), new TextIs(message) ).affirm(); } @Test public void readsUrl() throws Exception { final String message = "URL on äÄ üÜ öÖ ß жш"; final File input = this.folder.newFile(); Files.write( input.toPath(), message.getBytes(StandardCharsets.UTF_8) ); new Assertion<>( "Must read from url", new TextOf( new ReaderOf( input .toURI() .toURL() ) ), new TextIs(message) ).affirm(); } @Test public void readsUri() throws Exception { final String message = "URI on äÄ üÜ öÖ ß жш"; final File input = this.folder.newFile(); Files.write( input.toPath(), message.getBytes(StandardCharsets.UTF_8) ); new Assertion<>( "Must read from uri", new TextOf(new ReaderOf(input.toURI())), new TextIs(message) ).affirm(); } @Test public void readsBytes() throws Exception { final String input = "Bytes on äÄ üÜ öÖ ß жш"; new Assertion<>( "Must read from bytes", new TextOf(new ReaderOf(new BytesOf(input))), new TextIs(input) ).affirm(); } @Test public void readsText() throws Exception { final String input = "Text on äÄ üÜ öÖ ß жш"; new Assertion<>( "Must read from text", new TextOf(new ReaderOf(new TextOf(input))), new TextIs(input) ).affirm(); } @Test public void readsTextWithCharset() throws Exception { final String input = "Text with charset on äÄ üÜ öÖ ß жш"; new Assertion<>( "Must read from text with charset", new TextOf( new ReaderOf( new TextOf(input), StandardCharsets.UTF_8 ) ), new TextIs(input) ).affirm(); } @Test public void readsTextWithCharsetByName() throws Exception { final String input = "Text with charset by name on äÄ üÜ öÖ ß жш"; new Assertion<>( "Must read from text with charset by name", new TextOf( new ReaderOf( new TextOf(input), StandardCharsets.UTF_8.name() ) ), new TextIs(input) ).affirm(); } @Test public void readsCharSequence() throws Exception { final String input = "char sequence on äÄ üÜ öÖ ß жш"; new Assertion<>( "Must read from char sequence", new TextOf(new ReaderOf(input)), new TextIs(input) ).affirm(); } @Test public void readsCharSequenceWithCharset() throws Exception { final String input = "char sequence with charset on äÄ üÜ öÖ ß жш"; new Assertion<>( "Must read from char sequance with charset", new TextOf( new ReaderOf( input, StandardCharsets.UTF_8 ) ), new TextIs(input) ).affirm(); } @Test public void readsCharSequenceWithCharsetByName() throws Exception { final String input = "char sequence with charset by name on äÄ üÜ öÖ ß жш"; new Assertion<>( "Must read from char sequence with charset by name", new TextOf( new ReaderOf( input, StandardCharsets.UTF_8.name() ) ), new TextIs(input) ).affirm(); } @Test public void readsInput() throws Exception { final String input = "Input on äÄ üÜ öÖ ß жш"; new Assertion<>( "Must read from input", new TextOf(new ReaderOf(new InputOf(input))), new TextIs(input) ).affirm(); } @Test public void readsInputWithCharset() throws Exception { final String input = "Input with charset on äÄ üÜ öÖ ß жш"; new Assertion<>( "Must read from input with charset", new TextOf( new ReaderOf( new InputOf(input), StandardCharsets.UTF_8 ) ), new TextIs(input) ).affirm(); } @Test public void readsInputWithCharsetByName() throws Exception { final String input = "Input with charset by name on äÄ üÜ öÖ ß жш"; new Assertion<>( "Must read from input with charset by name", new TextOf( new ReaderOf( new InputOf(input), StandardCharsets.UTF_8.name() ) ), new TextIs(input) ).affirm(); } @Test public void readsInputWithCharsetDecoder() throws Exception { final String input = "Input with charset decoder on äÄ üÜ öÖ ß жш"; new Assertion<>( "Must read from input with charset decoder", new TextOf( new ReaderOf( new InputOf(input), StandardCharsets.UTF_8.newDecoder() ) ), new TextIs(input) ).affirm(); } @Test public void readsInputStream() throws Exception { final String input = "InputStream on äÄ üÜ öÖ ß жш"; new Assertion<>( "Must read from stream", new TextOf(new ReaderOf(new InputStreamOf(input))), new TextIs(input) ).affirm(); } @Test public void readsInputStreamWithCharset() throws Exception { final String input = "InputStream with charset on äÄ üÜ öÖ ß жш"; new Assertion<>( "Must read from stream with charset", new TextOf( new ReaderOf( new InputStreamOf(input), StandardCharsets.UTF_8 ) ), new TextIs(input) ).affirm(); } @Test public void readsInputStreamWithCharsetByName() throws Exception { final String input = "InputStream with charset by name on äÄ üÜ öÖ ß жш"; new Assertion<>( "Must read from stream with charset by name", new TextOf( new ReaderOf( new InputStreamOf(input), StandardCharsets.UTF_8.name() ) ), new TextIs(input) ).affirm(); } @Test public void readsInputStreamWithCharsetDecoder() throws Exception { final String input = "InputStream with charset decoder on äÄ üÜ öÖ ß жш"; new Assertion<>( "Must read from stream with charset decoder", new TextOf( new ReaderOf( new InputStreamOf(input), StandardCharsets.UTF_8.newDecoder() ) ), new TextIs(input) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/io/ResourceOfTest.java000066400000000000000000000112331400054650300241750ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.io; import java.io.IOException; import java.util.Arrays; import org.cactoos.Text; import org.cactoos.bytes.BytesOf; import org.cactoos.text.FormattedText; import org.cactoos.text.TextOf; import org.hamcrest.Matchers; import org.junit.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.EndsWith; /** * Test case for {@link ResourceOf}. * * @since 0.1 * @checkstyle JavadocMethodCheck (500 lines) */ public final class ResourceOfTest { @Test public void readsBinaryResource() throws Exception { new Assertion<>( "Can't read bytes from a classpath resource", Arrays.copyOfRange( new BytesOf( new ResourceOf( "org/cactoos/io/ResourceOfTest.class" ) ).asBytes(), // @checkstyle MagicNumber (2 lines) 0, 4 ), Matchers.equalTo( new byte[]{ // @checkstyle MagicNumber (1 line) (byte) 0xCA, (byte) 0xFE, (byte) 0xBA, (byte) 0xBE, } ) ).affirm(); } @Test public void readsTextResource() throws Exception { new Assertion<>( "Must read a text resource from classpath", ResourceOfTest.large(), new EndsWith("est laborum.\n") ).affirm(); } @Test public void readsTextResourceThroughClassloader() throws Exception { new Assertion<>( "Must read a text resource from classloader", ResourceOfTest.large(), new EndsWith(" laborum.\n") ).affirm(); } @Test public void readAbsentResourceTest() throws Exception { new Assertion<>( "Can't replace an absent resource with a text", new TextOf( new BytesOf( new ResourceOf( "foo/this-resource-is-definitely-absent.txt", "the replacement" ) ) ).asString(), Matchers.endsWith("replacement") ).affirm(); } @Test(expected = IOException.class) public void throwsWhenResourceIsAbsent() throws Exception { new TextOf( new ResourceOf( "bar/this-resource-is-definitely-absent.txt" ) ).asString(); } @Test public void acceptsTextAsResourceName() throws Exception { new Assertion<>( "Can't accept Text as resource name", new TextOf( new ResourceOf( new TextOf("org/cactoos/small-text.txt") ) ).asString(), Matchers.endsWith("ex ea commodo") ).affirm(); } @Test public void acceptsTextsAsResourceNameAndFallback() throws Exception { new Assertion<>( "Can't use Texts as parameters", new TextOf( new ResourceOf( new FormattedText("%s/absent.txt", "baz"), new TextOf("another replacement") ) ).asString(), Matchers.startsWith("another") ).affirm(); } /** * Large text resource. * @return The content of the large resource */ private static Text large() { return new TextOf( new ResourceOf( "org/cactoos/large-text.txt", ResourceOfTest.class ) ); } } cactoos-0.49/src/test/java/org/cactoos/io/SlowInput.java000066400000000000000000000040661400054650300232330ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.io; import java.io.ByteArrayInputStream; import java.io.InputStream; import org.cactoos.Input; /** * Input that returns content in small portions. * * @since 0.12 */ final class SlowInput implements Input { /** * Original input. */ private final Input origin; /** * Ctor. * @param size The size of the array to encapsulate */ SlowInput(final long size) { this((int) size); } /** * Ctor. * @param size The size of the array to encapsulate */ SlowInput(final int size) { this(new InputOf(new ByteArrayInputStream(new byte[size]))); } /** * Ctor. * @param input Original input to encapsulate and make slower */ SlowInput(final Input input) { this.origin = input; } @Override public InputStream stream() throws Exception { return new SlowInputStream(this.origin.stream()); } } cactoos-0.49/src/test/java/org/cactoos/io/SlowInputStream.java000066400000000000000000000051151400054650300244030ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.io; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; /** * InputStream that returns content in small portions. * * @since 0.12 */ public final class SlowInputStream extends InputStream { /** * Original stream. */ private final InputStream origin; /** * Ctor. * @param size The size of the array to encapsulate */ public SlowInputStream(final int size) { this(new ByteArrayInputStream(new byte[size])); } /** * Ctor. * @param stream Original stream to encapsulate and make slower */ SlowInputStream(final InputStream stream) { super(); this.origin = stream; } @Override public int read() throws IOException { final byte[] buf = new byte[1]; final int result; if (this.read(buf) < 0) { result = -1; } else { result = Byte.toUnsignedInt(buf[0]); } return result; } @Override public int read(final byte[] buf, final int offset, final int len) throws IOException { final int result; if (len > 1) { result = this.origin.read(buf, offset, len - 1); } else { result = this.origin.read(buf, offset, len); } return result; } @Override public int read(final byte[] buf) throws IOException { return this.read(buf, 0, buf.length); } } cactoos-0.49/src/test/java/org/cactoos/io/SlowInputStreamTest.java000066400000000000000000000040531400054650300252430ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.io; import org.cactoos.bytes.BytesOf; import org.hamcrest.core.IsEqual; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; /** * Test for {@link SlowInputStream}. * * @since 0.47 * @checkstyle MagicNumberCheck (40 lines) */ final class SlowInputStreamTest { @Test void readsSigned() throws Exception { new Assertion<>( "must correctly convert signed bytes to int", new SlowInputStream( new InputStreamOf(new BytesOf((byte) -100)) ).read(), new IsEqual<>(156) ).affirm(); } @Test void readsUnsigned() throws Exception { new Assertion<>( "must correctly convert unsigned bytes to int", new SlowInputStream( new InputStreamOf(new BytesOf((byte) 65)) ).read(), new IsEqual<>(65) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/io/SlowInputTest.java000066400000000000000000000044301400054650300240660ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.io; import java.nio.charset.StandardCharsets; import org.cactoos.scalar.LengthOf; import org.cactoos.text.TextOf; import org.hamcrest.Matchers; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; /** * Test case for {@link SlowInput}. * * @since 0.12 * @checkstyle JavadocMethodCheck (500 lines) */ final class SlowInputTest { @Test void calculatesLength() { final String text = "What's up, друг?"; new Assertion<>( "Can't calculate the length of Input", new LengthOf( new SlowInput( new InputOf( new TextOf(text) ) ) ).intValue(), Matchers.equalTo(text.getBytes(StandardCharsets.UTF_8).length) ).affirm(); } @Test void readsFileContentSlowly() { final long size = 100_000L; new Assertion<>( "Can't calculate length if the input is slow", new LengthOf( new SlowInput(size) ).longValue(), Matchers.equalTo(size) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/io/StickyTest.java000066400000000000000000000072041400054650300233720ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.io; import java.net.MalformedURLException; import java.net.URL; import org.cactoos.bytes.BytesOf; import org.cactoos.func.Repeated; import org.cactoos.scalar.LengthOf; import org.cactoos.text.TextOf; import org.hamcrest.Matchers; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.EndsWith; import org.llorllale.cactoos.matchers.MatcherOf; /** * Test case for {@link Sticky}. * @since 0.6 * @checkstyle JavadocMethodCheck (500 lines) * @checkstyle ClassDataAbstractionCouplingCheck (500 lines) */ final class StickyTest { @Test void readsFileContent() { new Assertion<>( "Can't read bytes from a file", new Sticky( new ResourceOf( "org/cactoos/large-text.txt" ) ), new MatcherOf<>( new Repeated<>( input -> new BytesOf( new TeeInput(input, new DeadOutput()) // @checkstyle MagicNumber (2 lines) ).asBytes().length == 74_536, 10 ) ) ).affirm(); } @Test void readsRealUrl() throws MalformedURLException { new Assertion<>( "Can't fetch text page from the URL", new TextOf( new Sticky( new InputOf( new URL( // @checkstyle LineLength (1 line) "file:src/test/resources/org/cactoos/large-text.txt" ) ) ) ), new EndsWith("est laborum.\n") ).affirm(); } @Test void readsFileContentSlowlyAndCountsLength() { final long size = 100_000L; new Assertion<>( "Can't read bytes from a large source slowly and count length", new LengthOf( new Sticky( new SlowInput(size) ) ).longValue(), Matchers.equalTo(size) ).affirm(); } @Test void readsFileContentSlowly() throws Exception { final int size = 130_000; new Assertion<>( "Can't read bytes from a large source slowly", new BytesOf( new Sticky( new SlowInput(size) ) ).asBytes().length, Matchers.equalTo(size) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/io/TailOfTest.java000066400000000000000000000107231400054650300233020ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.io; import java.util.Arrays; import java.util.Random; import org.cactoos.bytes.BytesOf; import org.hamcrest.Matchers; import org.junit.Test; import org.llorllale.cactoos.matchers.Assertion; /** * Tests for {@link TailOf}. * @since 0.30 * @checkstyle JavadocMethodCheck (500 lines) */ public final class TailOfTest { @Test public void tailsOnLongStream() throws Exception { final int size = 4; final byte[] bytes = this.generate(size); new Assertion<>( "Can't tail long stream", new BytesOf( new TailOf( new InputOf(new BytesOf(bytes)), size - 1 ) ).asBytes(), Matchers.equalTo(Arrays.copyOfRange(bytes, 1, bytes.length)) ).affirm(); } @Test public void tailsOnExactStream() throws Exception { final int size = 4; final byte[] bytes = this.generate(size); new Assertion<>( "Can't tail exact stream", new BytesOf( new TailOf( new InputOf(new BytesOf(bytes)), size ) ).asBytes(), Matchers.equalTo(bytes) ).affirm(); } @Test public void tailsOnExactStreamAndBuffer() throws Exception { final int size = 4; final byte[] bytes = this.generate(size); new Assertion<>( "Can't tail exact stream and buffer", new BytesOf( new TailOf( new InputOf(new BytesOf(bytes)), size, size ) ).asBytes(), Matchers.equalTo(bytes) ).affirm(); } @Test public void tailsOnShorterStream() throws Exception { final int size = 4; final byte[] bytes = this.generate(size); new Assertion<>( "Can't tail shorter stream", new BytesOf( new TailOf( new InputOf(new BytesOf(bytes)), size + 1 ) ).asBytes(), Matchers.equalTo(bytes) ).affirm(); } @Test public void tailsOnStreamLongerThanBufferAndBytes() throws Exception { final int size = 4; final byte[] bytes = this.generate(size); new Assertion<>( "Can't tail longer stream", new BytesOf( new TailOf( new InputOf(new BytesOf(bytes)), size - 1, size - 1 ) ).asBytes(), Matchers.equalTo( Arrays.copyOfRange(bytes, 1, bytes.length) ) ).affirm(); } @Test(expected = IllegalArgumentException.class) public void failsIfBufferSizeSmallerThanTailSize() throws Exception { final int size = 4; new BytesOf( new TailOf( new InputOf(new BytesOf(this.generate(size))), size, size - 1 ) ).asBytes(); } /** * Generate random byte array. * @param size Size of array * @return Generated array */ private byte[] generate(final int size) { final byte[] bytes = new byte[size]; new Random().nextBytes(bytes); return bytes; } } cactoos-0.49/src/test/java/org/cactoos/io/TeeInputFromByteArrayTest.java000066400000000000000000000067131400054650300263340ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.io; import java.io.File; import java.nio.charset.StandardCharsets; import org.cactoos.scalar.LengthOf; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.InputHasContent; /** * Test case for {@link TeeInput}. Cases for ctors which use byte array as an * input. * @since 1.0 * @checkstyle JavadocMethodCheck (100 lines) * @checkstyle ClassDataAbstractionCouplingCheck (100 lines) */ public final class TeeInputFromByteArrayTest { /** * Temporary files generator. */ @Rule public TemporaryFolder folder = new TemporaryFolder(); @Test public void copiesFromByteArrayToPath() throws Exception { final String message = "Hello, товарищ path äÄ üÜ öÖ and ß"; final File output = this.folder.newFile(); new LengthOf( new TeeInput( message.getBytes(StandardCharsets.UTF_8), output.toPath() ) ).intValue(); new Assertion<>( "Must copy bytes to path", new InputOf(output), new InputHasContent(message) ).affirm(); } @Test public void copiesFromByteArrayToFile() throws Exception { final String message = "Hello, товарищ file äÄ üÜ öÖ and ß"; final File output = this.folder.newFile(); new LengthOf( new TeeInput( message.getBytes(StandardCharsets.UTF_8), output ) ).intValue(); new Assertion<>( "Must copy bytes to file", new InputOf(output), new InputHasContent(message) ).affirm(); } @Test public void copiesFromByteArrayToOutput() throws Exception { final String message = "Hello, товарищ output äÄ üÜ öÖ and ß"; final File output = this.folder.newFile(); new LengthOf( new TeeInput( message.getBytes(StandardCharsets.UTF_8), new OutputTo(output) ) ).intValue(); new Assertion<>( "Must copy bytes to output", new InputOf(output), new InputHasContent(message) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/io/TeeInputFromBytesTest.java000066400000000000000000000064441400054650300255210ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.io; import java.io.File; import java.io.IOException; import org.cactoos.bytes.BytesOf; import org.cactoos.scalar.LengthOf; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.InputHasContent; /** * Test case for {@link TeeInput}. Cases for ctors which use * {@link org.cactoos.Bytes} as an input. * @since 1.0 * @checkstyle JavadocMethodCheck (100 lines) * @checkstyle ClassDataAbstractionCouplingCheck (100 lines) */ public final class TeeInputFromBytesTest { /** * Temporary files generator. */ @Rule public final TemporaryFolder folder = new TemporaryFolder(); @Test public void copiesFromBytesToPath() throws IOException { final String message = "Hello, товарищ path äÄ üÜ öÖ and ß"; final File output = this.folder.newFile(); new LengthOf( new TeeInput(new BytesOf(message), output.toPath()) ).intValue(); new Assertion<>( "Must copy bytes to file path", new InputOf(output), new InputHasContent(message) ).affirm(); } @Test public void copiesFromBytesToFile() throws IOException { final String message = "Hello, товарищ file äÄ üÜ öÖ and ß"; final File output = this.folder.newFile(); new LengthOf( new TeeInput(new BytesOf(message), output) ).intValue(); new Assertion<>( "Must copy bytes to file", new InputOf(output), new InputHasContent(message) ).affirm(); } @Test public void copiesFromBytesToOutput() throws IOException { final String message = "Hello, товарищ output äÄ üÜ öÖ and ß"; final File output = this.folder.newFile(); new LengthOf( new TeeInput(new BytesOf(message), new OutputTo(output)) ).intValue(); new Assertion<>( "Must bytes to output", new InputOf(output), new InputHasContent(message) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/io/TeeInputFromCharArrayTest.java000066400000000000000000000153001400054650300262760ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.io; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; import org.cactoos.scalar.LengthOf; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.InputHasContent; /** * Test case for {@link TeeInput}. Cases for ctors which use char array as an * input. * @since 1.0 * @checkstyle JavadocMethodCheck (215 lines) * @checkstyle ClassDataAbstractionCouplingCheck (215 lines) */ public final class TeeInputFromCharArrayTest { /** * Temporary files generator. */ @Rule public TemporaryFolder folder = new TemporaryFolder(); @Test public void copiesFromCharArrayWithCharsetToFile() throws IOException { final String input = "Hello, товарищ file #1 äÄ üÜ öÖ and ß"; final File output = this.folder.newFile(); new LengthOf( new TeeInput(input.toCharArray(), output, StandardCharsets.UTF_8) ).intValue(); new Assertion<>( "char array must be copied to the file with charset UTF_8", new InputOf(output), new InputHasContent(input) ).affirm(); } @Test public void copiesFromCharArrayWithCharsetByNameToFile() throws IOException { final String input = "Hello, товарищ file #2 äÄ üÜ öÖ and ß"; final File output = this.folder.newFile(); new LengthOf( new TeeInput(input.toCharArray(), output, StandardCharsets.UTF_8.name()) ).intValue(); new Assertion<>( "char array must be copied to the file with UTF_8 charset's name", new InputOf(output), new InputHasContent(input) ).affirm(); } @Test public void copiesFromCharArrayToOutput() throws IOException { final String input = "Hello, товарищ output #1 äÄ üÜ öÖ and ß"; final File output = this.folder.newFile(); new LengthOf( new TeeInput(input.toCharArray(), new OutputTo(output)) ).intValue(); new Assertion<>( "char array must be copied to the output", new InputOf(output), new InputHasContent(input) ).affirm(); } @Test public void copiesFromCharArrayWithCharsetToOutput() throws IOException { final String input = "Hello, товарищ output #2 äÄ üÜ öÖ and ß"; final File output = this.folder.newFile(); new LengthOf( new TeeInput(input.toCharArray(), new OutputTo(output), StandardCharsets.UTF_8) ).intValue(); new Assertion<>( "char array must be copied to the output with UTF_8 charset", new InputOf(output), new InputHasContent(input) ).affirm(); } @Test public void copiesFromCharArrayWithCharsetByNameToOutput() throws IOException { final String input = "Hello, товарищ output #3 äÄ üÜ öÖ and ß"; final File output = this.folder.newFile(); new LengthOf( new TeeInput(input.toCharArray(), new OutputTo(output), StandardCharsets.UTF_8.name()) ).intValue(); new Assertion<>( "char array must be copied to the output with UTF_8 charset's name", new InputOf(output), new InputHasContent(input) ).affirm(); } @Test public void copiesFromCharArrayToPath() throws IOException { final String input = "Hello, товарищ path #1 äÄ üÜ öÖ and ß"; final File output = this.folder.newFile(); new LengthOf( new TeeInput(input.toCharArray(), output.toPath()) ).intValue(); new Assertion<>( "char array must be copied to the path", new InputOf(output), new InputHasContent(input) ).affirm(); } @Test public void copiesFromCharArrayWithCharsetToPath() throws IOException { final String input = "Hello, товарищ path #2 äÄ üÜ öÖ and ß"; final File output = this.folder.newFile(); new LengthOf( new TeeInput(input.toCharArray(), output.toPath(), StandardCharsets.UTF_8) ).intValue(); new Assertion<>( "char array must be copied to the path with UTF_8 charset", new InputOf(output), new InputHasContent(input) ).affirm(); } @Test public void copiesFromCharArrayWithCharsetByNameToPath() throws IOException { final String input = "Hello, товарищ path #3 äÄ üÜ öÖ and ß"; final File output = this.folder.newFile(); new LengthOf( new TeeInput(input.toCharArray(), output.toPath(), StandardCharsets.UTF_8.name()) ).intValue(); new Assertion<>( "char array must be copied to the path with UTF_8 charset's name", new InputOf(output), new InputHasContent(input) ).affirm(); } @Test public void copiesFromCharArrayToFile() throws IOException { final File output = this.folder.newFile(); final String input = "Hello, товарищ file äÄ üÜ öÖ and ß"; new LengthOf( new TeeInput(input.toCharArray(), output) ).intValue(); new Assertion<>( "char array must be copied to the file", new InputOf(output), new InputHasContent(input) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/io/TeeInputFromCharSequenceTest.java000066400000000000000000000152011400054650300267700ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.io; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; import org.cactoos.scalar.LengthOf; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.InputHasContent; /** * Test case for {@link TeeInput}. Cases for ctors which use char sequence as * an input. * @since 1.0 * @checkstyle JavadocMethodCheck (215 lines) * @checkstyle ClassDataAbstractionCouplingCheck (215 lines) */ public final class TeeInputFromCharSequenceTest { /** * Temporary files generator. */ @Rule public TemporaryFolder folder = new TemporaryFolder(); @Test public void copiesFromCharSequenceToFile() throws IOException { final String input = "Hello, товарищ file #1 äÄ üÜ öÖ and ß"; final File output = this.folder.newFile(); new LengthOf( new TeeInput(input, output) ).intValue(); new Assertion<>( "char sequence must be copied to the file", new InputOf(output), new InputHasContent(input) ).affirm(); } @Test public void copiesFromCharSequenceWithCharsetToFile() throws IOException { final String input = "Hello, товарищ file #2 äÄ üÜ öÖ and ß"; final File output = this.folder.newFile(); new LengthOf( new TeeInput(input, output, StandardCharsets.UTF_8) ).intValue(); new Assertion<>( "char sequence must be copied to the file with UTF_8 charset", new InputOf(output), new InputHasContent(input) ).affirm(); } @Test public void copiesFromCharSequenceWithCharsetByNameToFile() throws IOException { final String input = "Hello, товарищ file #3 äÄ üÜ öÖ and ß"; final File output = this.folder.newFile(); new LengthOf( new TeeInput(input, output, StandardCharsets.UTF_8.name()) ).intValue(); new Assertion<>( "char sequence must be copied to the file with UTF_8 charset's name", new InputOf(output), new InputHasContent(input) ).affirm(); } @Test public void copiesFromCharSequenceToPath() throws IOException { final String input = "Hello, товарищ path #1 äÄ üÜ öÖ and ß"; final File output = this.folder.newFile(); new LengthOf( new TeeInput(input, output.toPath()) ).intValue(); new Assertion<>( "char sequence must be copied to the path", new InputOf(output), new InputHasContent(input) ).affirm(); } @Test public void copiesFromCharSequenceWithCharsetToPath() throws IOException { final String input = "Hello, товарищ path #2 äÄ üÜ öÖ and ß"; final File output = this.folder.newFile(); new LengthOf( new TeeInput(input, output.toPath(), StandardCharsets.UTF_8) ).intValue(); new Assertion<>( "char sequence must be copied to the path with UTF_8 charset", new InputOf(output), new InputHasContent(input) ).affirm(); } @Test public void copiesFromCharSequenceWithCharsetByNameToPath() throws IOException { final String input = "Hello, товарищ path #3 äÄ üÜ öÖ and ß"; final File output = this.folder.newFile(); new LengthOf( new TeeInput(input, output.toPath(), StandardCharsets.UTF_8.name()) ).intValue(); new Assertion<>( "char sequence must be copied to the path with UTF_8 charset's name", new InputOf(output), new InputHasContent(input) ).affirm(); } @Test public void copiesFromCharSequenceToOutput() throws IOException { final String input = "Hello, товарищ output #1 äÄ üÜ öÖ and ß"; final File output = this.folder.newFile(); new LengthOf( new TeeInput(input, new OutputTo(output)) ).intValue(); new Assertion<>( "char sequence must be copied to the output", new InputOf(output), new InputHasContent(input) ).affirm(); } @Test public void copiesFromCharSequenceWithCharsetToOutput() throws IOException { final String input = "Hello, товарищ output #2 äÄ üÜ öÖ and ß"; final File output = this.folder.newFile(); new LengthOf( new TeeInput(input, new OutputTo(output), StandardCharsets.UTF_8) ).intValue(); new Assertion<>( "char sequence must be copied to the output with UTF_8 charset", new InputOf(output), new InputHasContent(input) ).affirm(); } @Test public void copiesFromCharSequenceWithCharsetByNameToOutput() throws IOException { final String input = "Hello, товарищ output #3 äÄ üÜ öÖ and ß"; final File output = this.folder.newFile(); new LengthOf( new TeeInput(input, new OutputTo(output), StandardCharsets.UTF_8.name()) ).intValue(); new Assertion<>( "char sequence must be copied to the output with UTF_8 charset's name", new InputOf(output), new InputHasContent(input) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/io/TeeInputFromFileTest.java000066400000000000000000000076411400054650300253120ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.io; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import org.cactoos.scalar.LengthOf; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.InputHasContent; /** * Test case for {@link TeeInput}. Cases for ctors which use file as an input. * @since 1.0 * @checkstyle JavadocMethodCheck (120 lines) * @checkstyle ClassDataAbstractionCouplingCheck (120 lines) */ public final class TeeInputFromFileTest { /** * Temporary files generator. */ @Rule public TemporaryFolder folder = new TemporaryFolder(); @Test public void copiesFromFileToFile() throws IOException { final String message = "Hello, товарищ file #1 äÄ üÜ öÖ and ß"; final File input = this.folder.newFile(); Files.write( input.toPath(), message.getBytes(StandardCharsets.UTF_8) ); final File output = this.folder.newFile(); new LengthOf( new TeeInput( input, output ) ).intValue(); new Assertion<>( "Must copy from input file to output file", new InputOf(output), new InputHasContent(message) ).affirm(); } @Test public void copiesFromFileToPath() throws IOException { final String message = "Hello, товарищ path #1 äÄ üÜ öÖ and ß"; final File input = this.folder.newFile(); Files.write( input.toPath(), message.getBytes(StandardCharsets.UTF_8) ); final File output = this.folder.newFile(); new LengthOf( new TeeInput( input, output.toPath() ) ).intValue(); new Assertion<>( "Must copy from input file to output path", new InputOf(output), new InputHasContent(message) ).affirm(); } @Test public void copiesFromFileToOutput() throws IOException { final String message = "Hello, товарищ output #1 äÄ üÜ öÖ and ß"; final File input = this.folder.newFile(); Files.write( input.toPath(), message.getBytes(StandardCharsets.UTF_8) ); final File output = this.folder.newFile(); new LengthOf( new TeeInput( input, new OutputTo(output) ) ).intValue(); new Assertion<>( "Must copy from input file to output", new InputOf(output), new InputHasContent(message) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/io/TeeInputFromInputTest.java000066400000000000000000000147561400054650300255370ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.io; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; import org.cactoos.scalar.LengthOf; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.InputHasContent; /** * Test case for {@link TeeInput}. Cases for ctors which use * {@link org.cactoos.Input} as an input. * @since 1.0 * @checkstyle JavadocMethodCheck (200 lines) * @checkstyle ClassDataAbstractionCouplingCheck (200 lines) */ public final class TeeInputFromInputTest { /** * Temporary files generator. */ @Rule public TemporaryFolder folder = new TemporaryFolder(); @Test public void copiesFromInputToPath() throws IOException { final String input = "Hello, товарищ path #1 äÄ üÜ öÖ and ß"; final File output = this.folder.newFile(); new LengthOf( new TeeInput( new InputOf(input), output.toPath() ) ).intValue(); new Assertion<>( "Must copy from input to the output path", new InputOf(output), new InputHasContent(input) ).affirm(); } @Test public void copiesFromInputToFile() throws IOException { final String input = "Hello, товарищ file #1 äÄ üÜ öÖ and ß"; final File output = this.folder.newFile(); new LengthOf( new TeeInput( new InputOf(input), output ) ).intValue(); new Assertion<>( "Must copy from input to the output file", new InputOf(output), new InputHasContent(input) ).affirm(); } @Test public void copiesFromInputToWriter() throws IOException { final String input = "Hello, товарищ write #1 äÄ üÜ öÖ and ß"; final File output = this.folder.newFile(); new LengthOf( new TeeInput( new InputOf(input), new WriterTo(output) ) ).intValue(); new Assertion<>( "Must copy from input to the output", new InputOf(output), new InputHasContent(input) ).affirm(); } @Test public void copiesFromInputWithSizeToWriter() throws IOException { final String input = "Hello, товарищ writer #2 äÄ üÜ öÖ and ß"; final File output = this.folder.newFile(); new LengthOf( new TeeInput( new InputOf(input), new WriterTo(output), input.length() ) ).intValue(); new Assertion<>( "Must copy from input with size to the output", new InputOf(output), new InputHasContent(input) ).affirm(); } @Test public void copiesFromInputWithCharsetToWriter() throws IOException { final String input = "Hello, товарищ writer #3 äÄ üÜ öÖ and ß"; final File output = this.folder.newFile(); new LengthOf( new TeeInput( new InputOf(input), new WriterTo(output), StandardCharsets.UTF_8 ) ).intValue(); new Assertion<>( "Must copy from input with charset to output", new InputOf(output), new InputHasContent(input) ).affirm(); } @Test public void copiesFromInputWithCharsetAndSizeToWriter() throws IOException { final String input = "Hello, товарищ writer #4 äÄ üÜ öÖ and ß"; final File output = this.folder.newFile(); new LengthOf( new TeeInput( new InputOf(input), new WriterTo(output), StandardCharsets.UTF_8, input.length() ) ).intValue(); new Assertion<>( "Must copy from input with charset and size to output", new InputOf(output), new InputHasContent(input) ).affirm(); } @Test public void copiesFromInputWithCharsetByNameToWriter() throws IOException { final String input = "Hello, товарищ writer #5 äÄ üÜ öÖ and ß"; final File output = this.folder.newFile(); new LengthOf( new TeeInput( new InputOf(input), new WriterTo(output), StandardCharsets.UTF_8.name() ) ).intValue(); new Assertion<>( "Must copy from input with charset by name to output", new InputOf(output), new InputHasContent(input) ).affirm(); } @Test public void copiesFromInputWithCharsetByNameAndSizeToWriter() throws Exception { final String input = "Hello, товарищ writer #6 äÄ üÜ öÖ and ß"; final File output = this.folder.newFile(); new LengthOf( new TeeInput( new InputOf(input), new WriterTo(output), StandardCharsets.UTF_8.name(), input.length() ) ).intValue(); new Assertion<>( "Must copy from input with charset by name and size to output", new InputOf(output), new InputHasContent(input) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/io/TeeInputFromPathTest.java000066400000000000000000000075301400054650300253240ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.io; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import org.cactoos.scalar.LengthOf; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.InputHasContent; /** * Test case for {@link TeeInput}. Cases for ctors which use {@link Path} as * an input. * @since 1.0 * @checkstyle JavadocMethodCheck (120 lines) * @checkstyle ClassDataAbstractionCouplingCheck (120 lines) */ public final class TeeInputFromPathTest { /** * Temporary files generator. */ @Rule public TemporaryFolder folder = new TemporaryFolder(); @Test public void copiesFromPathToPath() throws IOException { final String message = "Hello, товарищ path #1 äÄ üÜ öÖ and ß"; final File input = this.folder.newFile(); Files.write( input.toPath(), message.getBytes(StandardCharsets.UTF_8) ); final File output = this.folder.newFile(); new LengthOf( new TeeInput(input.toPath(), output.toPath()) ).intValue(); new Assertion<>( "Must copy from input path to output path", new InputOf(output), new InputHasContent(message) ).affirm(); } @Test public void copiesFromPathToFile() throws IOException { final String message = "Hello, товарищ file #1 äÄ üÜ öÖ and ß"; final File input = this.folder.newFile(); Files.write( input.toPath(), message.getBytes(StandardCharsets.UTF_8) ); final File output = this.folder.newFile(); new LengthOf( new TeeInput(input.toPath(), output) ).intValue(); new Assertion<>( "Must copy from input path to output file", new InputOf(output), new InputHasContent(message) ).affirm(); } @Test public void copiesFromPathToOutput() throws IOException { final String message = "Hello, товарищ output #1 äÄ üÜ öÖ and ß"; final File input = this.folder.newFile(); Files.write( input.toPath(), message.getBytes(StandardCharsets.UTF_8) ); final File output = this.folder.newFile(); new LengthOf( new TeeInput(input.toPath(), new OutputTo(output)) ).intValue(); new Assertion<>( "Must copy from input path to output", new InputOf(output), new InputHasContent(message) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/io/TeeInputFromReaderTest.java000066400000000000000000000313311400054650300256260ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.io; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; import org.cactoos.scalar.LengthOf; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.InputHasContent; /** * Test case for {@link TeeInput}. Cases for ctors which use * {@link java.io.Reader} as an input. * @since 1.0 * @checkstyle JavadocMethodCheck (400 lines) * @checkstyle ClassDataAbstractionCouplingCheck (400 lines) */ @SuppressWarnings("PMD.TooManyMethods") public final class TeeInputFromReaderTest { /** * Temporary files generator. */ @Rule public TemporaryFolder folder = new TemporaryFolder(); @Test public void copiesFromReaderToFile() throws IOException { final String input = "Hello, товарищ file #1 äÄ üÜ öÖ and ß"; final File output = this.folder.newFile(); new LengthOf( new TeeInput(new ReaderOf(input), output) ).intValue(); new Assertion<>( "Must copy from reader to file.", new InputOf(output), new InputHasContent(input) ).affirm(); } @Test public void copiesFromReaderWithSizeToFile() throws IOException { final String input = "Hello, товарищ file #2 äÄ üÜ öÖ and ß"; final File output = this.folder.newFile(); new LengthOf( new TeeInput( new ReaderOf(input), output, input.length() ) ).intValue(); new Assertion<>( "Must copy from reader with size to file.", new InputOf(output), new InputHasContent(input) ).affirm(); } @Test public void copiesFromReaderWithCharsetToFile() throws IOException { final String input = "Hello, товарищ file #3 äÄ üÜ öÖ and ß"; final File output = this.folder.newFile(); new LengthOf( new TeeInput( new ReaderOf(input), output, StandardCharsets.UTF_8 ) ).intValue(); new Assertion<>( "Must copy from reader with charset to file.", new InputOf(output), new InputHasContent(input) ).affirm(); } @Test public void copiesFromReaderWithCharsetAndSizeToFile() throws IOException { final String input = "Hello, товарищ file #4 äÄ üÜ öÖ and ß"; final File output = this.folder.newFile(); new LengthOf( new TeeInput( new ReaderOf(input), output, StandardCharsets.UTF_8, input.length() ) ).intValue(); new Assertion<>( "Must copy from reader with charset and size to file.", new InputOf(output), new InputHasContent(input) ).affirm(); } @Test public void copiesFromReaderWithCharsetByNameToFile() throws IOException { final String input = "Hello, товарищ file #5 äÄ üÜ öÖ and ß"; final File output = this.folder.newFile(); new LengthOf( new TeeInput( new ReaderOf(input), output, StandardCharsets.UTF_8.name() ) ).intValue(); new Assertion<>( "Must copy from reader with charset by name to file.", new InputOf(output), new InputHasContent(input) ).affirm(); } @Test public void copiesFromReaderWithCharsetByNameAndSizeToFile() throws IOException { final String input = "Hello, товарищ file #6 äÄ üÜ öÖ and ß"; final File output = this.folder.newFile(); new LengthOf( new TeeInput( new ReaderOf(input), output, StandardCharsets.UTF_8.name(), input.length() ) ).intValue(); new Assertion<>( "Must copy from reader with charset by name and size to file.", new InputOf(output), new InputHasContent(input) ).affirm(); } @Test public void copiesFromReaderToPath() throws IOException { final String input = "Hello, товарищ path #1 äÄ üÜ öÖ and ß"; final File output = this.folder.newFile(); new LengthOf( new TeeInput( new ReaderOf(input), output.toPath() ) ).intValue(); new Assertion<>( "Must copy from reader to path.", new InputOf(output), new InputHasContent(input) ).affirm(); } @Test public void copiesFromReaderWithSizeToPath() throws IOException { final String input = "Hello, товарищ path #2 äÄ üÜ öÖ and ß"; final File output = this.folder.newFile(); new LengthOf( new TeeInput( new ReaderOf(input), output.toPath(), input.length() ) ).intValue(); new Assertion<>( "Must copy from reader with size to path", new InputOf(output), new InputHasContent(input) ).affirm(); } @Test public void copiesFromReaderWithCharsetToPath() throws IOException { final String input = "Hello, товарищ path #3 äÄ üÜ öÖ and ß"; final File output = this.folder.newFile(); new LengthOf( new TeeInput( new ReaderOf(input), output.toPath(), StandardCharsets.UTF_8 ) ).intValue(); new Assertion<>( "Must copy from reader with charset to path.", new InputOf(output), new InputHasContent(input) ).affirm(); } @Test public void copiesFromReaderWithCharsetAndSizeToPath() throws IOException { final String input = "Hello, товарищ path #4 äÄ üÜ öÖ and ß"; final File output = this.folder.newFile(); new LengthOf( new TeeInput( new ReaderOf(input), output.toPath(), StandardCharsets.UTF_8, input.length() ) ).intValue(); new Assertion<>( "Must copy from reader with charset and size to path.", new InputOf(output), new InputHasContent(input) ).affirm(); } @Test public void copiesFromReaderWithCharsetByNameToPath() throws IOException { final String input = "Hello, товарищ path #5 äÄ üÜ öÖ and ß"; final File output = this.folder.newFile(); new LengthOf( new TeeInput( new ReaderOf(input), output.toPath(), StandardCharsets.UTF_8.name() ) ).intValue(); new Assertion<>( "Must copy from reader with charset by name to path.", new InputOf(output), new InputHasContent(input) ).affirm(); } @Test public void copiesFromReaderWithCharsetByNameAndSizeToPath() throws IOException { final String input = "Hello, товарищ path #6 äÄ üÜ öÖ and ß"; final File output = this.folder.newFile(); new LengthOf( new TeeInput( new ReaderOf(input), output.toPath(), StandardCharsets.UTF_8.name(), input.length() ) ).intValue(); new Assertion<>( "Must copy from reader with charset by name and size to path.", new InputOf(output), new InputHasContent(input) ).affirm(); } @Test public void copiesFromReaderToOutput() throws IOException { final String input = "Hello, товарищ output #1 äÄ üÜ öÖ and ß"; final File output = this.folder.newFile(); new LengthOf( new TeeInput( new ReaderOf(input), new OutputTo(output) ) ).intValue(); new Assertion<>( "Must copy from reader to output.", new InputOf(output), new InputHasContent(input) ).affirm(); } @Test public void copiesFromReaderWithSizeToOutput() throws IOException { final String input = "Hello, товарищ output #2 äÄ üÜ öÖ and ß"; final File output = this.folder.newFile(); new LengthOf( new TeeInput( new ReaderOf(input), new OutputTo(output), input.length() ) ).intValue(); new Assertion<>( "Must copy from reader with size to output.", new InputOf(output), new InputHasContent(input) ).affirm(); } @Test public void copiesFromReaderWithCharsetToOutput() throws IOException { final String input = "Hello, товарищ output #3 äÄ üÜ öÖ and ß"; final File output = this.folder.newFile(); new LengthOf( new TeeInput( new ReaderOf(input), new OutputTo(output), StandardCharsets.UTF_8 ) ).intValue(); new Assertion<>( "Must copy from reader with charset to output.", new InputOf(output), new InputHasContent(input) ).affirm(); } @Test public void copiesFromReaderWithCharsetAndSizeToOutput() throws IOException { final String input = "Hello, товарищ output #4 äÄ üÜ öÖ and ß"; final File output = this.folder.newFile(); new LengthOf( new TeeInput( new ReaderOf(input), new OutputTo(output), StandardCharsets.UTF_8, input.length() ) ).intValue(); new Assertion<>( "Must copy from reader with charset and size to output.", new InputOf(output), new InputHasContent(input) ).affirm(); } @Test public void copiesFromReaderWithCharsetByNameToOutput() throws IOException { final String input = "Hello, товарищ output #5 äÄ üÜ öÖ and ß"; final File output = this.folder.newFile(); new LengthOf( new TeeInput( new ReaderOf(input), new OutputTo(output), StandardCharsets.UTF_8.name() ) ).intValue(); new Assertion<>( "Must copy from reader with charset by name to output.", new InputOf(output), new InputHasContent(input) ).affirm(); } @Test public void copiesFromReaderWithCharsetByNameAndSizeToOutput() throws IOException { final String input = "Hello, товарищ output #6 äÄ üÜ öÖ and ß"; final File output = this.folder.newFile(); new LengthOf( new TeeInput( new ReaderOf(input), new OutputTo(output), StandardCharsets.UTF_8.name(), input.length() ) ).intValue(); new Assertion<>( "Must copy from reader with charset by name and size to output.", new InputOf(output), new InputHasContent(input) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/io/TeeInputFromTextTest.java000066400000000000000000000157231400054650300253570ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.io; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; import org.cactoos.scalar.LengthOf; import org.cactoos.text.TextOf; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.InputHasContent; /** * Test case for {@link TeeInput}. Cases for ctors which use * {@link org.cactoos.Text} as an input. * @since 1.0 * @checkstyle JavadocMethodCheck (215 lines) * @checkstyle ClassDataAbstractionCouplingCheck (215 lines) */ public final class TeeInputFromTextTest { /** * Temporary files generator. */ @Rule public TemporaryFolder folder = new TemporaryFolder(); @Test public void copiesFromTextToPath() throws IOException { final String input = "Hello, товарищ path #1 äÄ üÜ öÖ and ß"; final File output = this.folder.newFile(); new LengthOf( new TeeInput(new TextOf(input), output.toPath()) ).intValue(); new Assertion<>( "text must be copied to the path", new InputOf(output), new InputHasContent(input) ).affirm(); } @Test public void copiesFromTextWithCharsetToPath() throws IOException { final String input = "Hello, товарищ path #2 äÄ üÜ öÖ and ß"; final File output = this.folder.newFile(); new LengthOf( new TeeInput( new TextOf(input), output.toPath(), StandardCharsets.UTF_8 ) ).intValue(); new Assertion<>( "text must be copied to the path with UTF_8 charset", new InputOf(output), new InputHasContent(input) ).affirm(); } @Test public void copiesFromTextWithCharsetByNameToPath() throws IOException { final String input = "Hello, товарищ path #3 äÄ üÜ öÖ and ß"; final File output = this.folder.newFile(); new LengthOf( new TeeInput( new TextOf(input), output.toPath(), StandardCharsets.UTF_8.name() ) ).intValue(); new Assertion<>( "text must be copied to the path with UTF_8 charset's name", new InputOf(output), new InputHasContent(input) ).affirm(); } @Test public void copiesFromTextToFile() throws IOException { final String input = "Hello, товарищ file #1 äÄ üÜ öÖ and ß"; final File output = this.folder.newFile(); new LengthOf( new TeeInput(new TextOf(input), output) ).intValue(); new Assertion<>( "text must be copied to the file", new InputOf(output), new InputHasContent(input) ).affirm(); } @Test public void copiesFromTextWithCharsetToFile() throws IOException { final String input = "Hello, товарищ file #2 äÄ üÜ öÖ and ß"; final File output = this.folder.newFile(); new LengthOf( new TeeInput( new TextOf(input), output, StandardCharsets.UTF_8 ) ).intValue(); new Assertion<>( "text must be copied to the file with UTF_8 charset", new InputOf(output), new InputHasContent(input) ).affirm(); } @Test public void copiesFromTextWithCharsetByNameToFile() throws IOException { final String input = "Hello, товарищ file #3 äÄ üÜ öÖ and ß"; final File output = this.folder.newFile(); new LengthOf( new TeeInput( new TextOf(input), output, StandardCharsets.UTF_8.name() ) ).intValue(); new Assertion<>( "text must be copied to the file with UTF_8 charset's name", new InputOf(output), new InputHasContent(input) ).affirm(); } @Test public void copiesFromTextToOutput() throws IOException { final String input = "Hello, товарищ output #1 äÄ üÜ öÖ and ß"; final File output = this.folder.newFile(); new LengthOf( new TeeInput(new TextOf(input), new OutputTo(output)) ).intValue(); new Assertion<>( "text must be copied to the output", new InputOf(output), new InputHasContent(input) ).affirm(); } @Test public void copiesFromTextWithCharsetToOutput() throws IOException { final String input = "Hello, товарищ output #2 äÄ üÜ öÖ and ß"; final File output = this.folder.newFile(); new LengthOf( new TeeInput( new TextOf(input), new OutputTo(output), StandardCharsets.UTF_8 ) ).intValue(); new Assertion<>( "text must be copied to the output with UTF_8 charset", new InputOf(output), new InputHasContent(input) ).affirm(); } @Test public void copiesFromTextWithCharsetByNameToOutput() throws IOException { final String input = "Hello, товарищ output #3 äÄ üÜ öÖ and ß"; final File output = this.folder.newFile(); new LengthOf( new TeeInput( new TextOf(input), new OutputTo(output), StandardCharsets.UTF_8.name() ) ).intValue(); new Assertion<>( "text must be copied to the output with UTF_8 charset's name", new InputOf(output), new InputHasContent(input) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/io/TeeInputFromUriTest.java000066400000000000000000000075731400054650300251760ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.io; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import org.cactoos.scalar.LengthOf; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.InputHasContent; /** * Test case for {@link TeeInput}. Cases for ctors which use * {@link java.net.URI} as an input. * @since 1.0 * @checkstyle JavadocMethodCheck (120 lines) * @checkstyle ClassDataAbstractionCouplingCheck (120 lines) */ public final class TeeInputFromUriTest { /** * Temporary files generator. */ @Rule public TemporaryFolder folder = new TemporaryFolder(); @Test public void copiesFromUriToPath() throws IOException { final String message = "Hello, товарищ path #1 äÄ üÜ öÖ and ß"; final File input = this.folder.newFile(); Files.write( input.toPath(), message.getBytes(StandardCharsets.UTF_8) ); final File output = this.folder.newFile(); new LengthOf( new TeeInput( input.toURI(), output ) ).intValue(); new Assertion<>( "Must copy from URI to path.", new InputOf(output), new InputHasContent(message) ).affirm(); } @Test public void copiesFromUriToFile() throws IOException { final String message = "Hello, товарищ file #1 äÄ üÜ öÖ and ß"; final File input = this.folder.newFile(); Files.write( input.toPath(), message.getBytes(StandardCharsets.UTF_8) ); final File output = this.folder.newFile(); new LengthOf( new TeeInput( input.toURI(), output ) ).intValue(); new Assertion<>( "Must copy from URI to file.", new InputOf(output), new InputHasContent(message) ).affirm(); } @Test public void copiesFromUriToOutput() throws IOException { final String message = "Hello, товарищ output #1 äÄ üÜ öÖ and ß"; final File input = this.folder.newFile(); Files.write( input.toPath(), message.getBytes(StandardCharsets.UTF_8) ); final File output = this.folder.newFile(); new LengthOf( new TeeInput( input.toURI(), new OutputTo(output) ) ).intValue(); new Assertion<>( "Must copy from URI to output.", new InputOf(output), new InputHasContent(message) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/io/TeeInputFromUrlTest.java000066400000000000000000000074661400054650300252020ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.io; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import org.cactoos.scalar.LengthOf; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.InputHasContent; /** * Test case for {@link TeeInput}. Cases for ctors which use * {@link java.net.URL} as an input. * @since 1.0 * @checkstyle JavadocMethodCheck (125 lines) * @checkstyle ClassDataAbstractionCouplingCheck (125 lines) */ public final class TeeInputFromUrlTest { /** * Temporary files generator. */ @Rule public TemporaryFolder folder = new TemporaryFolder(); @Test public void copiesFromUrlToPath() throws IOException { final String message = "Hello, товарищ path #1 äÄ üÜ öÖ and ß"; final File input = this.folder.newFile(); Files.write( input.toPath(), message.getBytes(StandardCharsets.UTF_8) ); final File output = this.folder.newFile(); new LengthOf( new TeeInput(input.toURI().toURL(), output.toPath()) ).intValue(); new Assertion<>( "Must copy from URL to path.", new InputOf(output), new InputHasContent(message) ).affirm(); } @Test public void copiesFromUrlToFile() throws IOException { final String message = "Hello, товарищ file #1 äÄ üÜ öÖ and ß"; final File input = this.folder.newFile(); Files.write( input.toPath(), message.getBytes(StandardCharsets.UTF_8) ); final File output = this.folder.newFile(); new LengthOf( new TeeInput(input.toURI().toURL(), output) ).intValue(); new Assertion<>( "Must copy from URL to file.", new InputOf(output), new InputHasContent(message) ).affirm(); } @Test public void copiesFromUrlToOutput() throws IOException { final String message = "Hello, товарищ output #1 äÄ üÜ öÖ and ß"; final File input = this.folder.newFile(); Files.write( input.toPath(), message.getBytes(StandardCharsets.UTF_8) ); final File output = this.folder.newFile(); new LengthOf( new TeeInput(input.toURI().toURL(), new OutputTo(output)) ).intValue(); new Assertion<>( "Must copy from URL to output.", new InputOf(output), new InputHasContent(message) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/io/TeeInputStreamTest.java000066400000000000000000000067751400054650300250510ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.io; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.StringWriter; import java.nio.charset.StandardCharsets; import java.util.concurrent.atomic.AtomicBoolean; import org.cactoos.scalar.LengthOf; import org.cactoos.text.TextOf; import org.hamcrest.Matchers; import org.hamcrest.core.IsEqual; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; /** * Test case for {@link TeeInputStream}. * @since 0.1 * @checkstyle JavadocMethodCheck (500 lines) * @checkstyle ClassDataAbstractionCouplingCheck (500 lines) */ final class TeeInputStreamTest { @Test void copiesContentByteByByte() throws Exception { final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final String content = "Hello, товарищ!"; new Assertion<>( "Must copy InputStream to OutputStream byte by byte", new TextOf( new ReaderOf( new TeeInputStream( new ByteArrayInputStream( content.getBytes(StandardCharsets.UTF_8) ), baos ) ) ).asString(), Matchers.allOf( Matchers.equalTo(content), Matchers.equalTo( new String(baos.toByteArray(), StandardCharsets.UTF_8) ) ) ).affirm(); } @Test void leftInputClosed() { try (StringWriterMock write = new StringWriterMock()) { new LengthOf( new TeeInput( "foo", new OutputTo(write) ) ).intValue(); new Assertion<>( "Must use output after usage from TeeInput", write.isClosed(), new IsEqual<>(true) ).affirm(); } } /** * Mock object around StringWriter for checking closing state. * @since 0.1 */ private static final class StringWriterMock extends StringWriter { /** * Closing state. */ private final AtomicBoolean closed = new AtomicBoolean(false); @Override public void close() { this.closed.set(true); } public boolean isClosed() { return this.closed.get(); } } } cactoos-0.49/src/test/java/org/cactoos/io/TeeOutputStreamTest.java000066400000000000000000000052621400054650300252400ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.io; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.nio.charset.StandardCharsets; import org.cactoos.text.TextOf; import org.hamcrest.Matchers; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; /** * Test case for {@link TeeOutputStream}. * @since 0.16 * @checkstyle JavadocMethodCheck (500 lines) * @checkstyle ClassDataAbstractionCouplingCheck (500 lines) */ final class TeeOutputStreamTest { @Test void copiesContentByteByByte() throws Exception { final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final ByteArrayOutputStream copy = new ByteArrayOutputStream(); final String content = "Hello, товарищ!"; new Assertion<>( "Must copy OutputStream to OutputStream byte by byte", new TextOf( new ReaderOf( new TeeInputStream( new ByteArrayInputStream( content.getBytes(StandardCharsets.UTF_8) ), new TeeOutputStream(baos, copy) ) ) ).asString(), Matchers.allOf( Matchers.equalTo(content), Matchers.equalTo( new String(baos.toByteArray(), StandardCharsets.UTF_8) ), Matchers.equalTo( new String(copy.toByteArray(), StandardCharsets.UTF_8) ) ) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/io/TeeOutputTest.java000066400000000000000000000131051400054650300240570ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.io; import java.io.ByteArrayOutputStream; import java.io.File; import java.nio.charset.StandardCharsets; import org.cactoos.text.TextOf; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.InputHasContent; import org.llorllale.cactoos.matchers.TextIs; /** * Test case for {@link TeeOutput}. * @since 0.16 * @checkstyle JavadocMethodCheck (500 lines) * @checkstyle ClassDataAbstractionCouplingCheck (500 lines) */ public final class TeeOutputTest { /** * Temporary files generator. */ @Rule public TemporaryFolder folder = new TemporaryFolder(); @Test public void copiesContent() { final ByteArrayOutputStream baos = new ByteArrayOutputStream(); new Assertion<>( "Can't copy Output to Output and return Input", new TeeInput( new InputOf("Hello, товарищ!"), new TeeOutput( new OutputTo(baos), new OutputTo(new ByteArrayOutputStream()) ) ), new InputHasContent( new TextOf(baos::toByteArray, StandardCharsets.UTF_8) ) ).affirm(); } @Test public void copiesWithWriter() { final ByteArrayOutputStream baos = new ByteArrayOutputStream(); new Assertion<>( "Can't copy Output with writer", new TeeInput( new InputOf("Hello, товарищ! writer"), new TeeOutput( new OutputTo(baos), new WriterTo(new ByteArrayOutputStream()) ) ), new InputHasContent( new TextOf(baos::toByteArray, StandardCharsets.UTF_8) ) ).affirm(); } @Test public void copiesWithWriterAndCharset() { final ByteArrayOutputStream baos = new ByteArrayOutputStream(); new Assertion<>( "Can't copy Output with writer and charset", new TeeInput( new InputOf( "Hello, товарищ! writer and charset" ), new TeeOutput( new OutputTo(baos), new WriterTo(new ByteArrayOutputStream()), StandardCharsets.UTF_8 ) ), new InputHasContent( new TextOf(baos::toByteArray, StandardCharsets.UTF_8) ) ).affirm(); } @Test public void copiesWithPath() throws Exception { final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final File file = this.folder.newFile(); new Assertion<>( "Must copy Output with path", new TextOf( new TeeInput( new InputOf("Hello, товарищ! with path"), new TeeOutput( new OutputTo(baos), file.toPath() ) ) ), new TextIs( new TextOf(file.toPath()) ) ).affirm(); } @Test public void copiesWithFile() throws Exception { final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final File file = this.folder.newFile(); new Assertion<>( "Must copy Output with file", new TextOf( new TeeInput( new InputOf("Hello, товарищ! with file"), new TeeOutput( new OutputTo(baos), file ) ) ), new TextIs( new TextOf(file.toPath()) ) ).affirm(); } @Test public void copiesWithOutputStream() { final ByteArrayOutputStream baos = new ByteArrayOutputStream(); new Assertion<>( "Can't copy Output with output stream", new TeeInput( new InputOf( "Hello, товарищ! with output stream" ), new TeeOutput( new OutputTo(baos), new ByteArrayOutputStream() ) ), new InputHasContent( new TextOf(baos::toByteArray, StandardCharsets.UTF_8) ) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/io/TeeReaderTest.java000066400000000000000000000041551400054650300237660ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.io; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.Reader; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.InputHasContent; /** * Test case for {@link TeeReader}. * * @since 0.13 * @checkstyle JavadocMethodCheck (500 lines) */ final class TeeReaderTest { @Test void testTeeReader() throws IOException { final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final String content = "Hello, товарищ!"; final Reader reader = new TeeReader( new ReaderOf(content), new WriterTo(baos) ); int done = 0; while (done >= 0) { done = reader.read(); } reader.close(); new Assertion<>( "Must read content", new InputOf(new ReaderOf(baos.toByteArray())), new InputHasContent(content) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/io/TempFileTest.java000066400000000000000000000100761400054650300236320ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.io; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import org.cactoos.text.FormattedText; import org.cactoos.text.TextOf; import org.hamcrest.Matchers; import org.hamcrest.core.IsEqual; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.EndsWith; import org.llorllale.cactoos.matchers.MatcherOf; import org.llorllale.cactoos.matchers.StartsWith; /** * Unit tests for {@link TempFile}. * * @since 1.0 * @checkstyle JavadocMethodCheck (500 lines) * @checkstyle ClassDataAbstractionCouplingCheck (500 lines) */ final class TempFileTest { @Test void createFile() throws Exception { try (TempFile file = new TempFile()) { new Assertion<>( "Must create a temp file", Files.exists(file.value()), new IsEqual<>(true) ).affirm(); } } @Test void createFileInCustomPath() throws Exception { final Path custom = Paths.get(System.getProperty("user.home")); try (TempFile file = new TempFile(() -> custom, "", "")) { new Assertion<>( "Must create a temp file at a custom path", file, Matchers.allOf( new MatcherOf<>( tmp -> { return Files.exists(tmp.value()); } ), new MatcherOf<>( tmp -> { return tmp.value().getParent().equals(custom); } ) ) ).affirm(); } } @Test void deleteFile() throws Exception { final TempFile file = new TempFile(); file.close(); new Assertion<>( "Must delete file on close", Files.exists(file.value()), new IsEqual<>(false) ).affirm(); } @Test void createFileWithPrefix() throws Exception { final String prefix = new FormattedText( "randomPrefix%s", System.currentTimeMillis() ).asString(); try (TempFile file = new TempFile(prefix, "")) { new Assertion<>( "File must be created with the given prefix", new TextOf(file.value().getFileName().toString()), new StartsWith(prefix) ).affirm(); } } @Test void createFileWithSuffix() throws Exception { final String suffix = new FormattedText( "randomSuffix%s", System.currentTimeMillis() ).asString(); try (TempFile file = new TempFile("", suffix)) { new Assertion<>( "File must be created with the given suffix", new TextOf(file.value().getFileName().toString()), new EndsWith(suffix) ).affirm(); } } } cactoos-0.49/src/test/java/org/cactoos/io/TempFolderTest.java000066400000000000000000000117751400054650300241750ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.io; import java.io.File; import java.nio.file.Files; import java.nio.file.Path; import org.cactoos.iterable.IterableOf; import org.cactoos.proc.ForEach; import org.cactoos.proc.ProcOf; import org.cactoos.text.Randomized; import org.hamcrest.core.IsNot; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.IsTrue; /** * Test case for {@link TempFolder}. * * @since 1.0 * @checkstyle JavadocMethodCheck (500 lines) * @checkstyle ClassDataAbstractionCouplingCheck (500 lines) */ final class TempFolderTest { @Test void createsDirectory() throws Exception { try (TempFolder folder = new TempFolder()) { final File dir = folder.value().toFile(); new Assertion<>( "must create new directory", dir.exists() && dir.isDirectory(), new IsTrue() ).affirm(); } } @Test void deletesDirectory() throws Exception { final TempFolder dir = new TempFolder( new Randomized('d', 'e', 'g').asString() ); dir.close(); new Assertion<>( "Can't delete folder while closing", !dir.value().toFile().exists(), new IsTrue() ).affirm(); } @Test void deletesNonEmptyDirectory() throws Exception { final TempFolder temp = new TempFolder(); final Path root = temp.value(); new ForEach<>( new ProcOf( name -> { final Path dir = Files.createDirectories( new File(root.toFile(), name).toPath() ); new ForEach<>( new ProcOf( filename -> { new TempFile( () -> dir, filename, "" ).value(); } ) ).exec( new IterableOf<>( "file1.txt", "file2.txt", "file3.txt" ) ); } ) ).exec( new IterableOf<>( "a", "b", "c", "d", "e" ) ); temp.close(); new Assertion<>( "Can't delete not empty folder while closing", temp.value().toFile().exists(), new IsNot<>(new IsTrue()) ).affirm(); } @Test void createDirectoryWithDirectoriesAndFiles() throws Exception { final TempFolder temp = new TempFolder(); final Path root = temp.value(); new ForEach<>( new ProcOf( name -> { final Path dir = Files.createDirectories( new File(root.toFile(), name).toPath() ); new ForEach<>( new ProcOf( filename -> { new TempFile( () -> dir, filename, "" ).value(); } ) ).exec( new IterableOf<>( "1.txt", "2.txt", "3.txt" ) ); } ) ).exec( new IterableOf<>( "1", "2", "3", "4", "5" ) ); new Assertion<>( "Directory contains files and sub directories", temp.value().toFile().exists(), new IsTrue() ).affirm(); temp.close(); } } cactoos-0.49/src/test/java/org/cactoos/io/UncheckedOutputTest.java000066400000000000000000000031371400054650300252370ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.io; import java.io.IOException; import org.junit.Test; /** * Test case for {@link UncheckedOutput}. * * @since 0.11 * @checkstyle JavadocMethodCheck (500 lines) */ public final class UncheckedOutputTest { @Test(expected = RuntimeException.class) public void rethrowsCheckedToUncheckedException() { new UncheckedOutput( () -> { throw new IOException("intended"); } ).stream(); } } cactoos-0.49/src/test/java/org/cactoos/io/WriterAsOutputStreamTest.java000066400000000000000000000116201400054650300262560ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.io; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import org.cactoos.scalar.LengthOf; import org.cactoos.text.TextOf; import org.hamcrest.core.IsNot; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.InputHasContent; import org.llorllale.cactoos.matchers.IsTrue; /** * Test case for {@link WriterAsOutputStream}. * * @since 0.13 * @checkstyle JavadocMethodCheck (500 lines) * @checkstyle ClassDataAbstractionCouplingCheck (500 lines) */ @SuppressWarnings("PMD.AvoidDuplicateLiterals") public final class WriterAsOutputStreamTest { /** * Temporary files and folders generator. */ @Rule public final TemporaryFolder folder = new TemporaryFolder(); @Test public void writesToByteArray() { final String content = "Hello, товарищ! How are you?"; final ByteArrayOutputStream baos = new ByteArrayOutputStream(); new Assertion<>( "Can't copy Input to Writer", new TeeInput( new InputOf(content), new OutputTo( new WriterAsOutputStream( new OutputStreamWriter( baos, StandardCharsets.UTF_8 ), StandardCharsets.UTF_8, // @checkstyle MagicNumber (1 line) 13 ) ) ), new InputHasContent( new TextOf(baos::toByteArray, StandardCharsets.UTF_8) ) ).affirm(); } @Test public void writesLargeContentToFile() throws IOException { final Path temp = this.folder.newFile("cactoos-1.txt-1") .toPath(); try (OutputStreamWriter writer = new OutputStreamWriter( Files.newOutputStream(temp.toAbsolutePath()), StandardCharsets.UTF_8 )) { new Assertion<>( "Can't copy Input to Output and return Input", new TeeInput( new ResourceOf("org/cactoos/large-text.txt"), new OutputTo( new WriterAsOutputStream( writer, StandardCharsets.UTF_8, // @checkstyle MagicNumber (1 line) 345 ) ) ), new InputHasContent( new TextOf(temp) ) ).affirm(); } } @Test public void writesToFileAndRemovesIt() throws Exception { final Path temp = this.folder.newFile().toPath(); final String content = "Hello, товарищ! How are you?"; try (OutputStreamWriter writer = new OutputStreamWriter( Files.newOutputStream(temp.toAbsolutePath()), StandardCharsets.UTF_8 )) { new LengthOf( new TeeInput( new InputOf(content), new OutputTo( new WriterAsOutputStream( writer, StandardCharsets.UTF_8, // @checkstyle MagicNumber (1 line) 345 ) ) ) ).value(); } Files.delete(temp); new Assertion<>( "file must not exist anymore", Files.exists(temp), new IsNot<>(new IsTrue()) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/io/WriterAsOutputTest.java000066400000000000000000000051141400054650300251030ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.io; import java.io.IOException; import java.io.OutputStreamWriter; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import org.cactoos.text.TextOf; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.InputHasContent; /** * Test case for {@link WriterAsOutput}. * * @since 0.13 * @checkstyle JavadocMethodCheck (500 lines) * @checkstyle ClassDataAbstractionCouplingCheck (500 lines) */ public final class WriterAsOutputTest { /** * Temporary files and folders generator. */ @Rule public final TemporaryFolder folder = new TemporaryFolder(); @Test public void writesLargeContentToFile() throws IOException { final Path temp = this.folder.newFile("cactoos-1.txt-1") .toPath(); try (OutputStreamWriter writer = new OutputStreamWriter( Files.newOutputStream(temp.toAbsolutePath()), StandardCharsets.UTF_8 )) { new Assertion<>( "Can't copy Input to Output and return Input", new TeeInput( new ResourceOf("org/cactoos/large-text.txt"), new WriterAsOutput(writer) ), new InputHasContent( new TextOf(temp) ) ).affirm(); } } } cactoos-0.49/src/test/java/org/cactoos/io/WriterToTest.java000066400000000000000000000044061400054650300237040ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.io; import java.io.IOException; import java.nio.file.Path; import org.cactoos.text.TextOf; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.InputHasContent; /** * Test case for {@link WriterTo}. * * @since 0.13 * @checkstyle JavadocMethodCheck (500 lines) * @checkstyle ClassDataAbstractionCouplingCheck (500 lines) */ public final class WriterToTest { /** * Temporary files and folders generator. */ @Rule public final TemporaryFolder folder = new TemporaryFolder(); @Test public void writesLargeContentToFile() throws IOException { final Path temp = this.folder.newFile("cactoos-1.txt-1") .toPath(); new Assertion<>( "Can't copy Input to Output and return Input", new TeeInput( new ResourceOf("org/cactoos/large-text.txt"), new WriterAsOutput(new WriterTo(temp)) ), new InputHasContent( new TextOf(temp) ) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/io/ZipTest.java000066400000000000000000000047431400054650300226730ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.io; import java.nio.file.Files; import java.nio.file.Path; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import org.hamcrest.core.IsEqual; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.llorllale.cactoos.matchers.Assertion; /** * Test case for {@link Zip}. * * @since 0.29 * @checkstyle JavadocMethodCheck (500 lines) */ public final class ZipTest { /** * Temporary folder. */ @Rule public final TemporaryFolder folder = new TemporaryFolder(); @Test public void zip() throws Exception { final Path dir = this.folder.newFolder().toPath(); dir.resolve("x/y").toFile().mkdirs(); Files.write(dir.resolve("x/y/test"), "".getBytes()); try (ZipInputStream input = new ZipInputStream( new Zip( new Directory(dir) ).stream() )) { int cnt = 0; ZipEntry entry = input.getNextEntry(); while (entry != null) { ++cnt; entry = input.getNextEntry(); } new Assertion<>( "Can't list files in a directory represented by a path", cnt, // @checkstyle MagicNumber (1 line) new IsEqual<>(4) ).affirm(); } } } cactoos-0.49/src/test/java/org/cactoos/io/package-info.java000066400000000000000000000023141400054650300236050ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ /** * Input/Output, tests. * * @since 0.1 */ package org.cactoos.io; cactoos-0.49/src/test/java/org/cactoos/iterable/000077500000000000000000000000001400054650300215765ustar00rootroot00000000000000cactoos-0.49/src/test/java/org/cactoos/iterable/CycledTest.java000066400000000000000000000046311400054650300245100ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.iterable; import java.util.Collections; import org.cactoos.scalar.ItemAt; import org.cactoos.scalar.LengthOf; import org.hamcrest.MatcherAssert; import org.hamcrest.Matchers; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.ScalarHasValue; /** * Test Case for {@link Cycled}. * @since 0.8 * @checkstyle JavadocMethodCheck (500 lines) */ final class CycledTest { @Test void repeatIterableTest() { final String expected = "two"; new Assertion<>( "Can't repeat iterable", new ItemAt<>( // @checkstyle MagicNumberCheck (1 line)< 7, new Cycled<>( new IterableOf<>( "one", expected, "three" ) ) ), new ScalarHasValue<>( expected ) ).affirm(); } @Test void notCycledEmptyTest() throws Exception { MatcherAssert.assertThat( "Can't generate an empty iterable", new LengthOf( new Cycled<>( Collections::emptyIterator ) ).intValue(), Matchers.equalTo(0) ); } } cactoos-0.49/src/test/java/org/cactoos/iterable/EndlessTest.java000066400000000000000000000037461400054650300247100ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.iterable; import java.util.NoSuchElementException; import org.hamcrest.MatcherAssert; import org.hamcrest.Matchers; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.Throws; /** * Test Case for {@link Endless}. * @since 0.11 * @checkstyle JavadocMethodCheck (500 lines) */ final class EndlessTest { @Test void endlessIterableTest() { MatcherAssert.assertThat( "Can't get unique endless iterable item", new Endless<>(1), Matchers.hasItem(1) ); } @Test void elementsIsNullTest() { new Assertion<>( "Must get sliced iterable of elements", () -> new Endless<>(null).iterator().next(), new Throws<>(NoSuchElementException.class) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/iterable/FilteredTest.java000066400000000000000000000121331400054650300250370ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.iterable; import org.cactoos.list.ListOf; import org.cactoos.scalar.LengthOf; import org.cactoos.text.StartsWith; import org.hamcrest.MatcherAssert; import org.hamcrest.Matchers; import org.hamcrest.collection.IsEmptyIterable; import org.hamcrest.core.IsNot; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.HasValues; import org.llorllale.cactoos.matchers.ScalarHasValue; /** * Test case for {@link Filtered}. * @since 0.1 * @checkstyle JavadocMethodCheck (500 lines) * @checkstyle MagicNumberCheck (500 lines) * @checkstyle ClassDataAbstractionCouplingCheck (500 lines) */ final class FilteredTest { @Test void filtersList() { MatcherAssert.assertThat( "Can't calculate the length of an iterable", new LengthOf( new Filtered<>( // @checkstyle MagicNumber (1 line) input -> input.length() > 4, new IterableOf<>( "hello", "world", "друг" ) ) ).intValue(), Matchers.equalTo(2) ); } @Test void filtersEmptyList() { MatcherAssert.assertThat( "Can't calculate the length of an empty iterable", new LengthOf( new Filtered<>( input -> input.length() > 1, new IterableOf() ) ).intValue(), Matchers.equalTo(0) ); } @Test void filtersIterablesWithSize() { final Iterable list = new Filtered<>( i -> i > 0, new IterableOf<>(1, 2, -1, 0, 1) ); MatcherAssert.assertThat( "Can't filter the iterable twice", list, Matchers.iterableWithSize(3) ); MatcherAssert.assertThat( "Can't filter the iterable twice, again", list, Matchers.iterableWithSize(3) ); } @Test void filterEmptyList() { new Assertion<>( "Filter must work on empty collection", new Filtered( input -> input.length() > 4, new ListOf<>() ), new IsEmptyIterable<>() ).affirm(); } @Test void length() { new Assertion<>( "Size must be equal to number of items matching the filter", new LengthOf( new Filtered<>( input -> input.length() >= 4, new IterableOf<>("some", "text", "yes") ) ), new ScalarHasValue<>(2.) ).affirm(); } @Test void withItemsNotEmpty() { new Assertion<>( "Must not be empty with items", new Filtered<>( input -> input.length() > 4, new IterableOf<>("first", "second") ), new IsNot<>(new IsEmptyIterable<>()) ).affirm(); } @Test void withoutItemsIsEmpty() { new Assertion<>( "Must be empty without items", new Filtered<>( input -> input.length() > 16, new IterableOf<>("third", "fourth") ), new IsEmptyIterable<>() ).affirm(); } @Test void filtersWithFuncToScalar() { new Assertion<>( "Must be filtered", new Filtered<>( new IterableOf<>("ay", "xb", "yx", "xy"), input -> new StartsWith(input, "x") ), new HasValues<>("xy") ).affirm(); } @Test void filterWithNumberFilter() { new Assertion<>( "Must be filtered with super type filter", new Filtered( (Number d) -> d.doubleValue() > 0, new IterableOf(1d, -2d, 3d) ), new HasValues<>(1d, 3d) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/iterable/HeadOfTest.java000066400000000000000000000034771400054650300244420ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.iterable; import org.hamcrest.MatcherAssert; import org.hamcrest.Matchers; import org.junit.jupiter.api.Test; /** * Test Case for {@link HeadOf}. * @since 0.8 * @checkstyle JavadocMethodCheck (500 lines) */ final class HeadOfTest { @Test @SuppressWarnings("PMD.AvoidDuplicateLiterals") void headIterable() throws Exception { MatcherAssert.assertThat( "Can't skip elements in iterable", new HeadOf<>( 2, new IterableOf<>( "one", "two", "three", "four" ) ), Matchers.contains( "one", "two" ) ); } } cactoos-0.49/src/test/java/org/cactoos/iterable/IterableOfBooleansTest.java000066400000000000000000000031501400054650300267770ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.iterable; import org.hamcrest.MatcherAssert; import org.hamcrest.Matchers; import org.junit.jupiter.api.Test; /** * Test case for {@link IterableOfBooleans}. * * @since 1.0 * @checkstyle JavadocMethodCheck (500 lines) */ final class IterableOfBooleansTest { @Test void convertsBooleanValuesToIterable() { MatcherAssert.assertThat( new IterableOfBooleans(true, false), Matchers.contains(true, false) ); } } cactoos-0.49/src/test/java/org/cactoos/iterable/IterableOfBytesTest.java000066400000000000000000000041051400054650300263240ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.iterable; import org.cactoos.text.TextOf; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.HasValues; /** * Test case for {@link IterableOfBytes}. * * @since 1.0 * @checkstyle JavadocMethodCheck (500 lines) */ final class IterableOfBytesTest { @Test void convertsTextToIterableOfBytes() { new Assertion<>( "Must create Iterable from Text", new IterableOfBytes( new TextOf("ABC") ), new HasValues<>( (byte) 'A', (byte) 'B', (byte) 'C' ) ).affirm(); } @Test void convertsBytesToIterable() { final byte[] bytes = "txt".getBytes(); new Assertion<>( "Must create Iterable from bytes", new IterableOfBytes(bytes), new HasValues<>(bytes[0], bytes[1], bytes[2]) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/iterable/IterableOfCharsTest.java000066400000000000000000000033211400054650300262750ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.iterable; import org.cactoos.text.TextOf; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.HasValues; /** * Test case for {@link IterableOfChars}. * * @since 1.0 * @checkstyle JavadocMethodCheck (500 lines) */ final class IterableOfCharsTest { @Test void convertsCharactersToIterable() { new Assertion<>( "Must create Iterable from Text", new IterableOfChars(new TextOf("txt")), new HasValues<>('t', 'x', 't') ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/iterable/IterableOfDoublesTest.java000066400000000000000000000032521400054650300266350ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.iterable; import org.hamcrest.MatcherAssert; import org.hamcrest.Matchers; import org.junit.jupiter.api.Test; /** * Test case for {@link IterableOfDoubles}. * * @since 1.0 * @checkstyle JavadocMethodCheck (500 lines) */ final class IterableOfDoublesTest { @Test void convertsDoubleValuesToIterable() { final double[] values = new double[]{1, 2, 3}; MatcherAssert.assertThat( new IterableOfDoubles(values), Matchers.contains(values[0], values[1], values[2]) ); } } cactoos-0.49/src/test/java/org/cactoos/iterable/IterableOfFloatsTest.java000066400000000000000000000032311400054650300264650ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.iterable; import org.hamcrest.MatcherAssert; import org.hamcrest.Matchers; import org.junit.jupiter.api.Test; /** * Test case for {@link IterableOfFloats}. * * @since 1.0 * @checkstyle JavadocMethodCheck (500 lines) */ final class IterableOfFloatsTest { @Test void convertsFloatValuesToIterable() { final float[] values = {1, 2, 3}; MatcherAssert.assertThat( new IterableOfFloats(values), Matchers.contains(values[0], values[1], values[2]) ); } } cactoos-0.49/src/test/java/org/cactoos/iterable/IterableOfIntsTest.java000066400000000000000000000032231400054650300261530ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.iterable; import org.hamcrest.MatcherAssert; import org.hamcrest.Matchers; import org.junit.jupiter.api.Test; /** * Test case for {@link IterableOfInts}. * * @since 1.0 * @checkstyle JavadocMethodCheck (500 lines) */ final class IterableOfIntsTest { @Test void convertsIntegerValuesToIterable() { final int[] values = {1, 2, 3}; MatcherAssert.assertThat( new IterableOfInts(values), Matchers.contains(values[0], values[1], values[2]) ); } } cactoos-0.49/src/test/java/org/cactoos/iterable/IterableOfLongsTest.java000066400000000000000000000032361400054650300263240ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.iterable; import org.hamcrest.MatcherAssert; import org.hamcrest.Matchers; import org.junit.jupiter.api.Test; /** * Test case for {@link IterableOfLongs}. * * @since 1.0 * @checkstyle JavadocMethodCheck (500 lines) */ final class IterableOfLongsTest { @Test void convertsLongValuesToIterable() { final long[] values = new long[]{1, 2, 3}; MatcherAssert.assertThat( new IterableOfLongs(values), Matchers.contains(values[0], values[1], values[2]) ); } } cactoos-0.49/src/test/java/org/cactoos/iterable/IterableOfShortsTest.java000066400000000000000000000033221400054650300265200ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.iterable; import org.hamcrest.MatcherAssert; import org.hamcrest.Matchers; import org.junit.jupiter.api.Test; /** * Test case for {@link IterableOfShorts}. * @since 1.0 * @checkstyle JavadocMethodCheck (500 lines) */ final class IterableOfShortsTest { @Test @SuppressWarnings("PMD.AvoidUsingShortType") void convertsShortValuesToIterable() { final short[] values = new short[]{1, 2, 3}; MatcherAssert.assertThat( new IterableOfShorts(values), Matchers.contains(values[0], values[1], values[2]) ); } } cactoos-0.49/src/test/java/org/cactoos/iterable/IterableOfTest.java000066400000000000000000000120021400054650300253100ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.iterable; import org.cactoos.scalar.LengthOf; import org.cactoos.text.TextOf; import org.hamcrest.MatcherAssert; import org.hamcrest.Matchers; import org.hamcrest.core.IsEqual; import org.hamcrest.core.IsNot; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.IsTrue; /** * Test case for {@link IterableOf}. * @since 0.12 * @checkstyle JavadocMethodCheck (500 lines) * @checkstyle ClassDataAbstractionCoupling (2 lines) */ final class IterableOfTest { @Test void convertsScalarsToIterable() { MatcherAssert.assertThat( "must convert scalars to iterable", new LengthOf( new IterableOf<>( "a", "b", "c" ) ).intValue(), // @checkstyle MagicNumber (1 line) Matchers.equalTo(3) ); } @Test void convertsArrayOfIntsToIterable() { MatcherAssert.assertThat( "must convert int scalars to iterable", new IterableOf<>(1, 2, 0, 2), Matchers.hasItem(0) ); } @Test void convertsObjectsToIterable() { MatcherAssert.assertThat( "must convert objects to iterable", new LengthOf( new IterableOf<>( new TextOf("a"), new TextOf("b"), new TextOf("c") ) ).intValue(), // @checkstyle MagicNumber (1 line) Matchers.equalTo(3) ); } @Test void isNotEqualsToIterableWithMoreElements() { new Assertion<>( "Must compare iterables and second one is bigger", new IterableOf<>("a", "b").equals(new IterableOf<>("a")), new IsNot<>(new IsTrue()) ).affirm(); } @Test void isNotEqualsToIterableWithLessElements() { new Assertion<>( "Must compare iterables and first one is bigger", new IterableOf<>("a").equals(new IterableOf<>("a", "b")), new IsNot<>(new IsTrue()) ).affirm(); } @Test void notEqualsToObjectOfAnotherType() { new Assertion<>( "must not equal to object of another type", new IterableOf<>(), new IsNot<>(new IsEqual<>(new Object())) ).affirm(); } @Test void notEqualsToIterableWithDifferentElements() { new Assertion<>( "must not equal to Iterable with different elements", new IterableOf<>(1, 2), new IsNot<>(new IsEqual<>(new IterableOf<>(1, 0))) ).affirm(); } @Test void isEqualToItself() { final IterableOf iterable = new IterableOf<>(1, 2); new Assertion<>( "must be equal to itself", iterable, new IsEqual<>(iterable) ).affirm(); } @Test void isEqualToIterableWithTheSameElements() { new Assertion<>( "must be equal to Iterable with the same elements", new IterableOf<>(1, 2), new IsEqual<>(new IterableOf<>(1, 2)) ).affirm(); } @Test void equalToEmptyIterable() { new Assertion<>( "empty Iterable must be equal to empty Iterable", new IterableOf<>(), new IsEqual<>(new IterableOf<>()) ).affirm(); } @Test void differentHashCode() { new Assertion<>( "must have different hashCode for Iterables with different content", new IterableOf<>(1, 2).hashCode(), new IsNot<>(new IsEqual<>(new IterableOf<>(2, 1).hashCode())) ).affirm(); } @Test void equalHashCode() { new Assertion<>( "must have equal hashCode for Iterables with equal content", new IterableOf<>(1, 2).hashCode(), new IsEqual<>(new IterableOf<>(1, 2).hashCode()) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/iterable/JoinedTest.java000066400000000000000000000047331400054650300245200ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.iterable; import org.hamcrest.core.IsEqual; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; /** * Test case for {@link Joined}. * @since 0.1 * @checkstyle JavadocMethodCheck (500 lines) * @checkstyle MagicNumber (500 lines) */ final class JoinedTest { @Test void joinsIterables() { new Assertion<>( "Must concatenate iterables together", new Joined( new IterableOf<>("h", "w"), new IterableOf<>("a", "y") ), new IsEqual<>(new IterableOf<>("h", "w", "a", "y")) ).affirm(); } @Test void joinsMappedIterables() { new Assertion<>( "Must concatenate mapped iterables together", new Joined<>( new Mapped<>( IterableOf::new, new IterableOf<>("x", "y") ) ), new IsEqual<>(new IterableOf<>("x", "y")) ).affirm(); } @Test @SuppressWarnings("unchecked") void joinItemAndIterable() { new Assertion<>( "Must join item and iterable", new Joined<>( 0, new IterableOf<>(1, 2, 3) ), new IsEqual<>(new IterableOf<>(0, 1, 2, 3)) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/iterable/MappedTest.java000066400000000000000000000056771400054650300245260ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.iterable; import java.util.Collections; import org.cactoos.list.ListOf; import org.cactoos.text.TextOf; import org.cactoos.text.Upper; import org.hamcrest.MatcherAssert; import org.hamcrest.Matchers; import org.hamcrest.core.IsEqual; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; /** * Test case for {@link Mapped}. * @since 0.1 * @checkstyle JavadocMethodCheck (500 lines) * @checkstyle MagicNumberCheck (500 lines) */ final class MappedTest { @Test void transformsList() throws Exception { MatcherAssert.assertThat( "Can't transform an iterable", new Mapped<>( input -> new Upper(new TextOf(input)), new IterableOf<>( "hello", "world", "друг" ) ).iterator().next().asString(), Matchers.equalTo("HELLO") ); } @Test void transformsEmptyList() { MatcherAssert.assertThat( "Can't transform an empty iterable", new Mapped<>( (String input) -> new Upper(new TextOf(input)), Collections.emptyList() ), Matchers.emptyIterable() ); } @Test void string() { MatcherAssert.assertThat( "Can't convert to string", new Mapped<>( x -> x * 2, new ListOf<>(1, 2, 3) ).toString(), Matchers.equalTo("2, 4, 6") ); } @Test void transformsArray() { new Assertion<>( "Transforms an array", new Mapped<>( input -> new Upper(new TextOf(input)).asString(), "a", "b", "c" ), new IsEqual<>(new IterableOf<>("A", "B", "C")) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/iterable/MatchedTest.java000066400000000000000000000122401400054650300246450ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.iterable; import org.cactoos.list.ListOf; import org.cactoos.scalar.LengthOf; import org.hamcrest.Matchers; import org.junit.Assert; import org.junit.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.Throws; /** * Test case for {@link Matched}. * * @since 0.39 * @checkstyle MagicNumberCheck (500 lines) * @checkstyle JavadocMethodCheck (500 lines) */ @SuppressWarnings("PMD.AvoidDuplicateLiterals") public final class MatchedTest { @Test public void iterator() { new Assertion<>( "All elements have correlation function as `equal`", new Matched<>( new IterableOf<>(1, 2, 3), new IterableOf<>(1, 2, 3) ), Matchers.hasItems(1, 2, 3) ).affirm(); } @Test public void noCorrelationWithBiggerSecondIterable() { new Assertion<>( "All elements have correlation function as 'endsWith'", () -> new ListOf<>( new Matched<>( (fst, snd) -> fst.endsWith("elem") && snd.endsWith("elem"), new IterableOf<>("1st elem", "2nd elem"), new IterableOf<>("'A' elem", "'B' elem", "'C' elem") ) ), new Throws<>(IllegalStateException.class) ).affirm(); } @Test public void noCorrelationWithSmallerSecondIterable() { new Assertion<>( "All elements have correlation function as `endsWith`", () -> new ListOf<>( new Matched<>( (fst, snd) -> fst.endsWith("elem") && snd.endsWith("elem"), new IterableOf<>("1st elem", "2nd elem", "3rd elem"), new IterableOf<>("`A` elem", "`B` elem") ) ), new Throws<>(IllegalStateException.class) ).affirm(); } @Test public void endsWith() { new Assertion<>( "All elements have correlation function as `endsWith`", new Matched<>( (fst, snd) -> fst.endsWith("elem") && snd.endsWith("elem"), new IterableOf<>("1st elem", "2nd elem", "3rd elem"), new IterableOf<>("`A` elem", "`B` elem", "'C' elem") ), Matchers.iterableWithSize(3) ).affirm(); } @Test public void matchedAsNumbers() { new Assertion<>( "All elements must be treated as Number", new Matched<>( (Number fst, Number snd) -> fst.intValue() == snd.intValue(), new IterableOf<>(1d, 2d, 3d), new IterableOf<>(1L, 2L, 3L) ), Matchers.iterableWithSize(3) ).affirm(); } @Test(expected = IllegalStateException.class) public void noCorrelation() { new LengthOf( new Matched<>( (fst, snd) -> fst.endsWith("elem") && snd.endsWith("elem"), new IterableOf<>("1st elem", "2nd"), new IterableOf<>("`A` elem", "`B` elem") ) ).intValue(); Assert.fail("There is no 'endsWith'correlation between 2nd elements"); } @Test(expected = IllegalStateException.class) public void nonNullCorrelation() { new LengthOf( new Matched<>( (fst, snd) -> fst != null && snd != null, new IterableOf<>("1st elem", "2nd elem", "3rd elem"), new IterableOf<>("`A` elem", null, "'C' elem") ) ).intValue(); Assert.fail("There is no 'non-null' correlation between 2nd elements"); } @Test public void iterablesOfDifferentTypes() { new Assertion<>( "All elements must be treated according to their type", new Matched<>( (Number fst, String snd) -> fst.intValue() == Integer.parseInt(snd), new IterableOf<>(1, 2, 3), new IterableOf<>("1", "2", "3") ), Matchers.iterableWithSize(3) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/iterable/PagedTest.java000066400000000000000000000107651400054650300243320ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.iterable; import java.util.Iterator; import java.util.NoSuchElementException; import org.cactoos.Scalar; import org.cactoos.iterator.IteratorOf; import org.cactoos.scalar.LengthOf; import org.cactoos.scalar.ScalarOf; import org.cactoos.scalar.Ternary; import org.hamcrest.collection.IsIterableWithSize; import org.hamcrest.core.IsEqual; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.Throws; /** * Test case for {@link Paged}. * @since 0.47 * @checkstyle ClassDataAbstractionCoupling (2 lines) */ final class PagedTest { @Test @SuppressWarnings("unchecked") void containAllPagedContentInOrder() { final Iterable first = new IterableOf<>("one", "two"); final Iterable second = new IterableOf<>("three", "four"); final Iterable third = new IterableOf<>("five"); final Iterator> pages = new IteratorOf<>( first, second, third ); new Assertion>( "must have all page values", new Paged<>( () -> pages.next().iterator(), page -> new Ternary<>( () -> pages.hasNext(), () -> pages.next().iterator(), () -> new IteratorOf() ).value() ), new IsEqual<>(new Joined<>(first, second, third)) ).affirm(); } @Test @SuppressWarnings("unchecked") void reportTotalPagedLength() { final Iterable first = new IterableOf<>("A", "six"); final Iterable second = new IterableOf<>("word", "long"); final Iterable third = new IterableOf<>("sentence"); final Iterable> service = new IterableOf<>( first, second, third ); final Iterator> pages = service.iterator(); new Assertion>( "length must be equal to total number of elements", new Paged<>( () -> pages.next().iterator(), page -> new Ternary<>( () -> pages.hasNext(), () -> pages.next().iterator(), () -> new IteratorOf() ).value() ), new IsIterableWithSize<>( new IsEqual<>( new LengthOf( new Joined<>(first, second, third) ).intValue() ) ) ).affirm(); } @Test @SuppressWarnings("unchecked") void throwsNoSuchElement() { final Iterable> service = new IterableOf<>(); final Iterator> pages = service.iterator(); new Assertion>( "must throw an exception when first iterator is empty", new ScalarOf( () -> new Paged<>( () -> pages.next().iterator(), page -> new Ternary<>( () -> pages.hasNext(), () -> pages.next().iterator(), () -> new IteratorOf() ).value() ).iterator().next() ), new Throws<>(NoSuchElementException.class) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/iterable/PartitionedTest.java000066400000000000000000000040501400054650300255620ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.iterable; import org.cactoos.scalar.LengthOf; import org.hamcrest.MatcherAssert; import org.hamcrest.Matchers; import org.junit.jupiter.api.Test; /** * Test case for {@link Partitioned}. * * @since 0.29 * @checkstyle JavadocMethodCheck (500 lines) * @checkstyle MagicNumber (500 lines) */ final class PartitionedTest { @Test void partitionedEmpty() { MatcherAssert.assertThat( "Can't generate a Partitioned without values.", new LengthOf( new Partitioned<>(2) ).intValue(), Matchers.equalTo(0) ); } @Test void partitionedWithPartial() { MatcherAssert.assertThat( "Can't generate a Partitioned with partition size.", new LengthOf( new Partitioned<>(2, new IterableOf<>(1, 2, 3)) ).intValue(), Matchers.equalTo(2) ); } } cactoos-0.49/src/test/java/org/cactoos/iterable/RangeOfTest.java000066400000000000000000000074351400054650300246330ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.iterable; import java.time.LocalDate; import java.time.temporal.ChronoUnit; import org.cactoos.Func; import org.cactoos.list.ListOf; import org.hamcrest.MatcherAssert; import org.hamcrest.Matchers; import org.junit.jupiter.api.Test; /** * Test of range implementation. * * @since 1.0 * @checkstyle JavadocMethodCheck (500 lines) * @checkstyle MagicNumber (500 lines) */ public class RangeOfTest { @Test public final void testIntegerRange() { MatcherAssert.assertThat( "Can't generate a range of integers", new ListOf<>( new RangeOf<>(1, 5, value -> ++value) ), Matchers.contains(1, 2, 3, 4, 5) ); } @Test public final void testIntegerFibonacciRange() { MatcherAssert.assertThat( "Can't generate a range of fibonacci integers", new ListOf<>( new RangeOf<>( 1, 100, new Func() { private int last; @Override public Integer apply( final Integer input) throws Exception { final int next = this.last + input; this.last = input; return next; } } ) ), Matchers.contains(1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89) ); } @Test public final void testLongRange() { MatcherAssert.assertThat( "Can't generate a range of long", new ListOf<>( new RangeOf<>(1L, 5L, value -> ++value) ), Matchers.contains(1L, 2L, 3L, 4L, 5L) ); } @Test public final void testCharacterRange() { MatcherAssert.assertThat( "Can't generate a range of characters", new ListOf<>( new RangeOf<>('a', 'c', value -> ++value) ), Matchers.contains('a', 'b', 'c') ); } @Test public final void testLocalDateRange() { MatcherAssert.assertThat( "Can't generate a range of local dates.", new ListOf<>( new RangeOf<>( LocalDate.of(2017, 1, 1), LocalDate.of(2017, 1, 3), value -> value.plus(1, ChronoUnit.DAYS) ) ), Matchers.contains( LocalDate.of(2017, 1, 1), LocalDate.of(2017, 1, 2), LocalDate.of(2017, 1, 3) ) ); } } cactoos-0.49/src/test/java/org/cactoos/iterable/RepeatedTest.java000066400000000000000000000050371400054650300250370ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.iterable; import org.cactoos.scalar.LengthOf; import org.hamcrest.MatcherAssert; import org.hamcrest.Matchers; import org.junit.jupiter.api.Test; /** * Test case for {@link Repeated}. * * @since 0.1 * @checkstyle JavadocMethodCheck (500 lines) * @checkstyle MagicNumber (500 lines) */ final class RepeatedTest { @Test void allSameTest() throws Exception { final int size = 42; final int element = 11; MatcherAssert.assertThat( "Can't generate an iterable with fixed size", new LengthOf( new Filtered<>( input -> input == element, new Repeated<>(size, element) ) ).intValue(), Matchers.equalTo(size) ); } @Test void emptyTest() throws Exception { MatcherAssert.assertThat( "Can't generate an empty iterable", new LengthOf(new Repeated<>(0, 0)).intValue(), Matchers.equalTo(0) ); } @Test void repeatsIntegerTwice() throws Exception { final Iterable list = new Repeated<>(5, 1); MatcherAssert.assertThat( "Can't repeat an integer", list, Matchers.iterableWithSize(5) ); MatcherAssert.assertThat( "Can't repeat an integer, again", list, Matchers.iterableWithSize(5) ); } } cactoos-0.49/src/test/java/org/cactoos/iterable/ReversedTest.java000066400000000000000000000071471400054650300250710ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.iterable; import org.cactoos.list.ListOf; import org.hamcrest.collection.IsEmptyIterable; import org.hamcrest.core.IsEqual; import org.hamcrest.core.IsNot; import org.junit.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.HasSize; /** * Test case for {@link Reversed}. * @since 0.9 * @checkstyle JavadocMethodCheck (500 lines) * @checkstyle MagicNumberCheck (500 lines) * @checkstyle ClassDataAbstractionCouplingCheck (500 lines) */ public final class ReversedTest { @Test public void reversesIterable() { new Assertion<>( "Must reverse an iterable", new Reversed<>( new IterableOf<>( "h", "w", "d" ) ), new IsEqual<>(new IterableOf<>("d", "w", "h")) ).affirm(); } @Test public void iteratesMultipleTimes() { final Iterable itr = new Reversed<>( new IterableOf<>("h", "w", "d") ); final Iterable expected = new IterableOf<>("d", "w", "h"); new Assertion<>( "Must iterates once", itr, new IsEqual<>(expected) ).affirm(); new Assertion<>( "Must iterates twice", itr, new IsEqual<>(expected) ).affirm(); } @Test public void reverseList() { final String last = "last"; new Assertion<>( "Must reverse list", new Reversed<>( new ListOf<>( "item", last ) ).iterator().next(), new IsEqual<>(last) ).affirm(); } @Test public void reverseEmptyList() { new Assertion<>( "Must reverse empty list", new Reversed<>( new ListOf<>() ), new IsEmptyIterable<>() ).affirm(); } @Test public void size() { new Assertion<>( "Size must be the same", new Reversed<>( new IterableOf<>( "0", "1", "2" ) ), new HasSize(3) ).affirm(); } @Test public void isEmpty() { new Assertion<>( "Must be not empty", new Reversed<>( new IterableOf<>( 6, 16 ) ), new IsNot<>(new IsEmptyIterable<>()) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/iterable/ShuffledTest.java000066400000000000000000000044151400054650300250450ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.iterable; import org.cactoos.list.ListOf; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.HasValues; /** * Test Case for {@link Shuffled}. * * @since 0.20 * @checkstyle JavadocMethodCheck (500 lines) * @checkstyle MagicNumberCheck (500 lines) */ final class ShuffledTest { @Test void shuffleArray() throws Exception { new Assertion<>( "Must shuffle an iterable", new Shuffled<>( new IterableOf<>( 6, 2, 5 ) ), new HasValues<>(2, 5, 6) ).affirm(); } @Test void shuffleCollection() { new Assertion<>( "Must shuffle elements in collection", new Shuffled<>(new ListOf<>(1, 2, 0, -1)), new HasValues<>(1, 2, 0, -1) ).affirm(); } @Test void shufflesIterable() { new Assertion<>( "Must shuffle elements in iterable", new Shuffled<>(new IterableOf<>(1, 2, 0, -1)), new HasValues<>(1, 2, 0, -1) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/iterable/SkippedTest.java000066400000000000000000000100661400054650300247030ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.iterable; import org.cactoos.list.ListOf; import org.hamcrest.collection.IsEmptyIterable; import org.hamcrest.core.IsEqual; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; /** * Test Case for {@link Skipped}. * * @since 0.34 * @checkstyle JavadocMethodCheck (500 lines) */ final class SkippedTest { @Test void skipIterable() { final String one = "one"; final String two = "two"; final String three = "three"; final String four = "four"; new Assertion<>( "Must skip elements in iterable", new Skipped<>( 2, new IterableOf<>(one, two, three, four) ), new IsEqual<>( new IterableOf<>( three, four ) ) ).affirm(); } @Test void skipArray() { final String five = "five"; final String six = "six"; final String seven = "seven"; final String eight = "eight"; new Assertion<>( "Must skip elements in array", new Skipped<>( 2, five, six, seven, eight ), new IsEqual<>( new IterableOf<>( seven, eight ) ) ).affirm(); } @Test void skipCollection() { final String nine = "nine"; final String eleven = "eleven"; final String twelve = "twelve"; final String hundred = "hundred"; new Assertion<>( "Must skip elements in collection", new Skipped<>( 2, new ListOf<>(nine, eleven, twelve, hundred) ), new IsEqual<>( new IterableOf<>(twelve, hundred) ) ).affirm(); } @Test void skippedAllElements() { new Assertion<>( "Must skip all elements", new Skipped<>( 2, "Frodo", "Gandalf" ), new IsEmptyIterable<>() ).affirm(); } @Test void skippedMoreThanExists() { new Assertion<>( "Can't skip more than exists", new Skipped<>( Integer.MAX_VALUE, "Sauron", "Morgoth" ), new IsEmptyIterable<>() ).affirm(); } @Test void skippedNegativeSize() { final String varda = "varda"; final String yavanna = "yavanna"; final String nessa = "nessa"; final String vaire = "vaire"; new Assertion<>( "Must process negative skipped size", new Skipped<>( -1, varda, yavanna, nessa, vaire ), new IsEqual<>( new IterableOf<>(varda, yavanna, nessa, vaire) ) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/iterable/SlicedTest.java000066400000000000000000000036251400054650300245120ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.iterable; import org.hamcrest.core.IsEqual; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; /** * Test case for {@link Sliced}. * @since 1.0.0 * @checkstyle JavadocMethodCheck (500 lines) * @checkstyle MagicNumberCheck (500 lines) */ final class SlicedTest { @Test @SuppressWarnings("PMD.AvoidDuplicateLiterals") void sliceIterable() throws Exception { new Assertion<>( "Must get sliced iterable of elements", new Sliced<>( 1, 2, "one", "two", "three", "four" ), new IsEqual<>( new IterableOf<>( "two", "three" ) ) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/iterable/SolidTest.java000066400000000000000000000060161400054650300243560ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.iterable; import org.cactoos.Scalar; import org.hamcrest.MatcherAssert; import org.hamcrest.Matchers; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.RunsInThreads; /** * Test Case for {@link Solid}. * @since 0.24 * @checkstyle JavadocMethodCheck (500 lines) * @checkstyle MagicNumber (500 lines) */ final class SolidTest { @Test void makesListFromMappedIterable() { final Iterable list = new Solid<>( new Mapped( i -> i + 1, new IterableOf<>(1, -1, 0, 1) ) ); MatcherAssert.assertThat( "Can't turn a mapped iterable into a list", list, Matchers.iterableWithSize(4) ); MatcherAssert.assertThat( "Can't turn a mapped iterable into a list, again", list, Matchers.iterableWithSize(4) ); } @Test void mapsToSameObjects() { final Iterable> list = new Solid<>( new Mapped>( i -> () -> i, new IterableOf<>(1, -1, 0, 1) ) ); MatcherAssert.assertThat( "Can't map only once", list.iterator().next(), Matchers.equalTo(list.iterator().next()) ); } @Test void worksInThreadsMultipleTimes() { for (int count = 0; count < 10; ++count) { this.worksInThreads(); } } @Test void worksInThreads() { MatcherAssert.assertThat( "Can't behave as an iterable in multiple threads", list -> { MatcherAssert.assertThat( list.iterator().next(), Matchers.equalTo(list.iterator().next()) ); return true; }, new RunsInThreads<>(new Solid<>(1, 0, -1, -1, 2)) ); } } cactoos-0.49/src/test/java/org/cactoos/iterable/SortedTest.java000066400000000000000000000065741400054650300245550ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.iterable; import java.util.Collections; import java.util.Comparator; import org.cactoos.list.ListOf; import org.hamcrest.Matchers; import org.hamcrest.core.IsEqual; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; /** * Test case for {@link Sorted}. * * @since 0.7 * @checkstyle JavadocMethodCheck (500 lines) * @checkstyle MagicNumberCheck (500 lines) */ final class SortedTest { @Test void sortsAnArray() throws Exception { new Assertion<>( "Can't sort an iterable", new Sorted<>( new IterableOf<>( 3, 2, 10, 44, -6, 0 ) ), Matchers.hasItems(-6, 0, 2, 3, 10, 44) ).affirm(); } @Test @SuppressWarnings("PMD.AvoidDuplicateLiterals") void sortsAnArrayWithComparator() throws Exception { new Assertion<>( "Can't sort an iterable with a comparator", new Sorted<>( Comparator.reverseOrder(), new IterableOf<>( "a", "c", "hello", "dude", "Friend" ) ), Matchers.hasItems("hello", "dude", "c", "a", "Friend") ).affirm(); } @Test void sortsAnEmptyArray() throws Exception { new Assertion<>( "Can't sort an empty iterable", new Sorted( Collections.emptyList() ), Matchers.iterableWithSize(0) ).affirm(); } @Test void sortsCollection() { new Assertion<>( "Must sort elements in collection", new Sorted<>( new ListOf<>( "o", "t", "t", "f" ) ), new IsEqual<>(new IterableOf<>("f", "o", "t", "t")) ).affirm(); } @Test void sortsByNymberComprator() throws Exception { new Assertion<>( "Must sort an iterable of numbers", new Sorted<>( (Number fst, Number snd) -> Integer.compare(fst.intValue(), snd.intValue()), new IterableOf(3L, 1f, 2d) ), new IsEqual<>( new IterableOf(1f, 2d, 3L) ) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/iterable/StickyTest.java000066400000000000000000000050771400054650300245600ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.iterable; import java.util.Collections; import java.util.concurrent.atomic.AtomicInteger; import org.cactoos.list.ListOf; import org.cactoos.scalar.LengthOf; import org.hamcrest.collection.IsEmptyIterable; import org.hamcrest.core.IsEqual; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; /** * Test case for {@link Sticky}. * * @since 0.8 * @checkstyle JavadocMethodCheck (500 lines) * @checkstyle ClassDataAbstractionCouplingCheck (500 lines) */ final class StickyTest { @Test void ignoresChangesInIterable() throws Exception { final AtomicInteger size = new AtomicInteger(2); final Iterable list = new Sticky<>( new ListOf<>( () -> Collections.nCopies(size.incrementAndGet(), 0).iterator() ) ); new Assertion<>( "Must ignore the changes in the underlying iterable", new LengthOf(list).intValue(), new IsEqual<>(new LengthOf(list).intValue()) ).affirm(); } @Test void testEmpty() { new Assertion<>( "Must be empty", new Sticky<>(), new IsEmptyIterable<>() ).affirm(); } @Test void testEqualsIterable() { new Assertion<>( "Must be equals to equivalent iterable", new Sticky<>(1, 2), new IsEqual<>(new IterableOf<>(1, 2)) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/iterable/SyncedTest.java000066400000000000000000000036441400054650300245350ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.iterable; import org.hamcrest.MatcherAssert; import org.hamcrest.Matchers; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.RunsInThreads; /** * Test Case for {@link Synced}. * @since 0.24 * @checkstyle JavadocMethodCheck (500 lines) * @checkstyle MagicNumber (500 lines) */ final class SyncedTest { @Test void worksInThreads() { MatcherAssert.assertThat( "Can't behave as an iterable in multiple threads", list -> { MatcherAssert.assertThat( list.iterator().next(), Matchers.equalTo(list.iterator().next()) ); return true; }, new RunsInThreads<>(new Synced<>(1, 0, -1, -1, 2)) ); } } cactoos-0.49/src/test/java/org/cactoos/iterable/TailOfTest.java000066400000000000000000000035401400054650300244610ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.iterable; import org.hamcrest.MatcherAssert; import org.hamcrest.Matchers; import org.junit.jupiter.api.Test; /** * Test case for {@link TailOf}. * @since 0.31 * @checkstyle JavadocMethodCheck (500 lines) * @checkstyle MagicNumberCheck (500 lines) */ final class TailOfTest { @Test @SuppressWarnings("PMD.AvoidDuplicateLiterals") void tailIterable() throws Exception { MatcherAssert.assertThat( "Can't get tail portion of iterable", new TailOf<>( 3, "one", "two", "three", "four" ), Matchers.contains( "two", "three", "four" ) ); } } cactoos-0.49/src/test/java/org/cactoos/iterable/package-info.java000066400000000000000000000023201400054650300247620ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ /** * Iterables, tests. * * @since 0.12 */ package org.cactoos.iterable; cactoos-0.49/src/test/java/org/cactoos/iterator/000077500000000000000000000000001400054650300216405ustar00rootroot00000000000000cactoos-0.49/src/test/java/org/cactoos/iterator/CycledTest.java000066400000000000000000000046551400054650300245600ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.iterator; import java.util.Collections; import java.util.NoSuchElementException; import org.cactoos.iterable.IterableOf; import org.cactoos.iterable.NoNulls; import org.cactoos.scalar.ItemAt; import org.junit.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.ScalarHasValue; /** * Test Case for {@link Cycled}. * @since 0.8 * @checkstyle JavadocMethodCheck (500 lines) */ public final class CycledTest { @Test public void repeatIteratorTest() { final String expected = "two"; new Assertion<>( "must repeat iterator", new ItemAt<>( // @checkstyle MagicNumberCheck (1 line) 7, new IterableOf<>( new Cycled<>( new NoNulls<>( new IterableOf<>( "one", expected, "three" ) ) ) ) ), new ScalarHasValue<>( expected ) ).affirm(); } @Test(expected = NoSuchElementException.class) public void notCycledEmptyTest() { new Cycled<>( Collections::emptyIterator ).next(); } } cactoos-0.49/src/test/java/org/cactoos/iterator/HeadOfTest.java000066400000000000000000000103371400054650300244750ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.iterator; import java.util.ArrayList; import java.util.List; import java.util.NoSuchElementException; import org.cactoos.iterable.IterableOf; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.HasSize; import org.llorllale.cactoos.matchers.HasValues; import org.llorllale.cactoos.matchers.Throws; /** * Test Case for {@link HeadOf}. * @since 0.8 * @checkstyle JavadocMethodCheck (500 lines) * @checkstyle MagicNumberCheck (500 lines) */ final class HeadOfTest { @Test @SuppressWarnings("PMD.AvoidDuplicateLiterals") void headIterator() { new Assertion<>( "Must skip elements in iterator", new IterableOf<>( new HeadOf<>( 2, new IteratorOf<>( "one", "two", "three", "four" ) ) ), new HasValues<>( "one", "two" ) ).affirm(); } @Test void returnsIntactIterator() { new Assertion<>( "Must return an intact iterator", new IterableOf<>( new HeadOf<>( 3, new IteratorOf<>( "one", "two" ) ) ), new HasSize(2) ).affirm(); } @Test void returnsEmptyIterator() { new Assertion<>( "Must throw an exception if empty", () -> new HeadOf<>( 0, new IteratorOf<>( "one", "two" ) ).next(), new Throws<>(NoSuchElementException.class) ).affirm(); } @Test void emptyIteratorForNegativeSize() { new Assertion<>( "Must throw an exception for negative size", () -> new HeadOf<>( -1, new IteratorOf<>( "one", "two" ) ).next(), new Throws<>(NoSuchElementException.class) ).affirm(); } @Test void iteratesForEachRemaining() { final List lst = new ArrayList<>(2); new HeadOf<>( 2, new IteratorOf<>( "one", "two", "three", "four" ) ).forEachRemaining( lst::add ); new Assertion<>( "Should iterate over 2 head elements", lst, new HasValues<>( "one", "two" ) ).affirm(); } @Test void removeNotSupported() { new Assertion<>( "Remove should not be supported", () -> { new HeadOf<>( 1, new IteratorOf<>( "one", "two", "three", "four" ) ).remove(); return "Should have thrown exception"; }, new Throws<>(UnsupportedOperationException.class) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/iterator/ImmutableTest.java000066400000000000000000000072401400054650300252650ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.iterator; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Random; import org.cactoos.text.Randomized; import org.cactoos.text.TextOf; import org.hamcrest.core.IsEqual; import org.junit.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.TextIs; /** * Test Case for {@link Immutable}. * * @since 0.32 * @checkstyle JavadocMethodCheck (500 lines) * @checkstyle ClassDataAbstractionCouplingCheck (500 lines) */ public final class ImmutableTest { @Test(expected = UnsupportedOperationException.class) public void doesNotAllowRemovingOfElements() { final List list = new LinkedList<>(); list.add("one"); final Iterator immutable = new Immutable<>(list.iterator()); immutable.next(); immutable.remove(); } @Test public void decoratesNext() { final int value = new Random().nextInt(); final Iterator immutable = new Immutable<>( new IteratorOf<>(value) ); new Assertion<>( "next must return first value from iterator", immutable.next(), new IsEqual<>(value) ).affirm(); } @Test public void decoratesHasNext() { final int value = new Random().nextInt(); final Iterator immutable = new Immutable<>( new IteratorOf<>(value) ); new Assertion<>( "hasNext must return true for not traversed iterator", immutable.hasNext(), new IsEqual<>(true) ).affirm(); immutable.next(); new Assertion<>( "hasNext must return false for already traversed iterator", immutable.hasNext(), new IsEqual<>(false) ).affirm(); } @Test public void decoratesToString() throws Exception { final String string = new Randomized().asString(); final Iterator iterator = new Iterator() { public Object next() { return new Object(); } public boolean hasNext() { return false; } public String toString() { return string; } }; final Iterator immutable = new Immutable<>(iterator); new Assertion<>( "must delegate toString to decorated iterator", new TextOf(immutable.toString()), new TextIs(iterator.toString()) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/iterator/IteratorOfBooleansTest.java000066400000000000000000000046701400054650300271130ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.iterator; import java.util.NoSuchElementException; import org.hamcrest.core.IsEqual; import org.junit.Test; import org.llorllale.cactoos.matchers.Assertion; /** * Tests for {@link IteratorOfBooleans}. * * @since 0.32 * @checkstyle JavadocMethodCheck (500 lines) */ public final class IteratorOfBooleansTest { @Test public void emptyIteratorDoesNotHaveNext() { new Assertion<>( "hasNext is true for empty iterator", new IteratorOfBooleans().hasNext(), new IsEqual<>(false) ).affirm(); } @Test(expected = NoSuchElementException.class) public void emptyIteratorThrowsException() { new IteratorOfBooleans().next(); } @Test public void nonEmptyIteratorDoesNotHaveNext() { final IteratorOfBooleans iterator = new IteratorOfBooleans(true, false); iterator.next(); iterator.next(); new Assertion<>( "hasNext is true for already traversed iterator", iterator.hasNext(), new IsEqual<>(false) ).affirm(); } @Test(expected = NoSuchElementException.class) public void nonEmptyIteratorThrowsException() { final IteratorOfBooleans iterator = new IteratorOfBooleans(true); iterator.next(); iterator.next(); } } cactoos-0.49/src/test/java/org/cactoos/iterator/IteratorOfBytesTest.java000066400000000000000000000071701400054650300264350ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.iterator; import java.util.Iterator; import java.util.NoSuchElementException; import org.cactoos.list.ListOf; import org.cactoos.text.TextOf; import org.hamcrest.core.IsEqual; import org.junit.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.HasValues; /** * Tests for {@link IteratorOfBytes}. * *

There is no thread-safety guarantee.

* * @since 0.34 * @checkstyle JavadocMethodCheck (500 lines) */ public final class IteratorOfBytesTest { @Test public void canBeConstructedFromString() throws Exception { final Iterator itr = new IteratorOfBytes( "F" ); new Assertion<>( "Must have 1 element", new ListOf<>( itr.next(), itr.hasNext() ), new HasValues( (byte) 'F', false ) ).affirm(); } @Test public void canBeConstructedFromText() throws Exception { final Iterator itr = new IteratorOfBytes( new TextOf("ABC") ); new Assertion<>( "Must have 3 elements", new ListOf<>( itr.next(), itr.next(), itr.next(), itr.hasNext() ), new HasValues( (byte) 'A', (byte) 'B', (byte) 'C', false ) ).affirm(); } @Test public void emptyIteratorDoesNotHaveNext() { new Assertion<>( "hasNext is true for empty iterator.", new IteratorOfBytes().hasNext(), new IsEqual<>(false) ).affirm(); } @Test(expected = NoSuchElementException.class) public void emptyIteratorThrowsException() { new IteratorOfBytes().next(); } @Test public void nonEmptyIteratorDoesNotHaveNext() { new Assertion<>( "hasNext is true for fully traversed iterator.", this.iteratorWithFetchedElements().hasNext(), new IsEqual<>(false) ).affirm(); } @Test(expected = NoSuchElementException.class) public void nonEmptyIteratorThrowsException() { this.iteratorWithFetchedElements().next(); } private IteratorOfBytes iteratorWithFetchedElements() { final IteratorOfBytes iterator = new IteratorOfBytes((byte) 1, (byte) 2, (byte) 3); iterator.next(); iterator.next(); iterator.next(); return iterator; } } cactoos-0.49/src/test/java/org/cactoos/iterator/IteratorOfCharsTest.java000066400000000000000000000057011400054650300264050ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.iterator; import java.util.NoSuchElementException; import org.cactoos.iterable.IterableOf; import org.cactoos.text.TextOf; import org.hamcrest.core.IsEqual; import org.junit.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.HasValues; /** * Tests for {@link IteratorOfChars}. * * @since 0.32 * @checkstyle JavadocMethodCheck (500 lines) */ public final class IteratorOfCharsTest { @Test public void canBeConstructedFromText() { new Assertion<>( "Iterator must contain all characters of the string", new IterableOf<>( new IteratorOfChars( new TextOf("abc") ) ), new HasValues<>('a', 'b', 'c') ).affirm(); } @Test public void emptyIteratorDoesNotHaveNext() { new Assertion<>( "hasNext is true for empty iterator", new IteratorOfChars().hasNext(), new IsEqual<>(false) ).affirm(); } @Test(expected = NoSuchElementException.class) public void emptyIteratorThrowsException() { new IteratorOfChars().next(); } @Test public void nonEmptyIteratorDoesNotHaveNext() { final IteratorOfChars iterator = new IteratorOfChars( 'a', 'b', 'c' ); iterator.next(); iterator.next(); iterator.next(); new Assertion<>( "hasNext is true for already traversed iterator", iterator.hasNext(), new IsEqual<>(false) ).affirm(); } @Test(expected = NoSuchElementException.class) public void nonEmptyIteratorThrowsException() { final IteratorOfChars iterator = new IteratorOfChars( 'a' ); iterator.next(); iterator.next(); } } cactoos-0.49/src/test/java/org/cactoos/iterator/IteratorOfDoublesTest.java000066400000000000000000000050751400054650300267460ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.iterator; import java.util.NoSuchElementException; import org.hamcrest.core.IsEqual; import org.junit.Test; import org.llorllale.cactoos.matchers.Assertion; /** * Tests for {@link IteratorOfDoubles}. * *

There is no thread-safety guarantee.

* * @since 0.34 * @checkstyle JavadocMethodCheck (500 lines) */ public final class IteratorOfDoublesTest { @Test public void emptyIteratorDoesNotHaveNext() { new Assertion<>( "hasNext is true for empty iterator.", new IteratorOfDoubles().hasNext(), new IsEqual<>(false) ).affirm(); } @Test(expected = NoSuchElementException.class) public void emptyIteratorThrowsException() { new IteratorOfDoubles().next(); } @Test public void nonEmptyIteratorDoesNotHaveNext() { new Assertion<>( "hasNext is true for fully traversed iterator.", this.iteratorWithFetchedElements().hasNext(), new IsEqual<>(false) ).affirm(); } @Test(expected = NoSuchElementException.class) public void nonEmptyIteratorThrowsException() { this.iteratorWithFetchedElements().next(); } private IteratorOfDoubles iteratorWithFetchedElements() { final IteratorOfDoubles iterator = new IteratorOfDoubles(1.1D, 2.2D, 3.3D); iterator.next(); iterator.next(); iterator.next(); return iterator; } } cactoos-0.49/src/test/java/org/cactoos/iterator/IteratorOfFloatsTest.java000066400000000000000000000046471400054650300266050ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.iterator; import java.util.NoSuchElementException; import org.hamcrest.core.IsEqual; import org.junit.Test; import org.llorllale.cactoos.matchers.Assertion; /** * Tests for {@link IteratorOfFloats}. * * @since 0.32 * @checkstyle JavadocMethodCheck (500 lines) */ public final class IteratorOfFloatsTest { @Test public void emptyIteratorDoesNotHaveNext() { new Assertion<>( "hasNext is true for empty iterator.", new IteratorOfFloats().hasNext(), new IsEqual<>(false) ).affirm(); } @Test(expected = NoSuchElementException.class) public void emptyIteratorThrowsException() { new IteratorOfFloats().next(); } @Test public void nonEmptyIteratorDoesNotHaveNext() { final IteratorOfFloats iterator = new IteratorOfFloats(1.0f, 2.0f); iterator.next(); iterator.next(); new Assertion<>( "hasNext is true for fully traversed iterator.", iterator.hasNext(), new IsEqual<>(false) ).affirm(); } @Test(expected = NoSuchElementException.class) public void nonEmptyIteratorThrowsException() { final IteratorOfFloats iterator = new IteratorOfFloats(1.0f); iterator.next(); iterator.next(); } } cactoos-0.49/src/test/java/org/cactoos/iterator/IteratorOfIntsTest.java000066400000000000000000000046161400054650300262660ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.iterator; import java.util.NoSuchElementException; import org.hamcrest.core.IsEqual; import org.junit.Test; import org.llorllale.cactoos.matchers.Assertion; /** * Tests for {@link IteratorOfInts}. * * @since 0.32 * @checkstyle JavadocMethodCheck (500 lines) */ public final class IteratorOfIntsTest { @Test public void emptyIteratorDoesNotHaveNext() { new Assertion<>( "hasNext is true for empty iterator.", new IteratorOfInts().hasNext(), new IsEqual<>(false) ).affirm(); } @Test(expected = NoSuchElementException.class) public void emptyIteratorThrowsException() { new IteratorOfInts().next(); } @Test public void nonEmptyIteratorDoesNotHaveNext() { final IteratorOfInts iterator = new IteratorOfInts(1, 2); iterator.next(); iterator.next(); new Assertion<>( "hasNext is true for fully traversed iterator.", iterator.hasNext(), new IsEqual<>(false) ).affirm(); } @Test(expected = NoSuchElementException.class) public void nonEmptyIteratorThrowsException() { final IteratorOfInts iterator = new IteratorOfInts(1); iterator.next(); iterator.next(); } } cactoos-0.49/src/test/java/org/cactoos/iterator/IteratorOfLongsTest.java000066400000000000000000000046261400054650300264340ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.iterator; import java.util.NoSuchElementException; import org.hamcrest.core.IsEqual; import org.junit.Test; import org.llorllale.cactoos.matchers.Assertion; /** * Tests for {@link IteratorOfLongs}. * * @since 0.34 * @checkstyle JavadocMethodCheck (500 lines) */ public final class IteratorOfLongsTest { @Test public void emptyIteratorDoesNotHaveNext() { new Assertion<>( "hasNext is true for empty iterator.", new IteratorOfLongs().hasNext(), new IsEqual<>(false) ).affirm(); } @Test(expected = NoSuchElementException.class) public void emptyIteratorThrowsException() { new IteratorOfLongs().next(); } @Test public void nonEmptyIteratorDoesNotHaveNext() { final IteratorOfLongs iterator = new IteratorOfLongs(1, 2); iterator.next(); iterator.next(); new Assertion<>( "hasNext is true for fully traversed iterator.", iterator.hasNext(), new IsEqual<>(false) ).affirm(); } @Test(expected = NoSuchElementException.class) public void nonEmptyIteratorThrowsException() { final IteratorOfLongs iterator = new IteratorOfLongs(1); iterator.next(); iterator.next(); } } cactoos-0.49/src/test/java/org/cactoos/iterator/IteratorOfShortsTest.java000066400000000000000000000047711400054650300266350ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.iterator; import java.util.NoSuchElementException; import org.hamcrest.core.IsEqual; import org.junit.Test; import org.llorllale.cactoos.matchers.Assertion; /** * Tests for {@link IteratorOfShorts}. * * @since 0.34 * @checkstyle JavadocMethodCheck (500 lines) */ @SuppressWarnings("PMD.AvoidUsingShortType") public final class IteratorOfShortsTest { @Test public void emptyIteratorDoesNotHaveNext() { new Assertion<>( "hasNext is true for empty iterator.", new IteratorOfShorts().hasNext(), new IsEqual<>(false) ).affirm(); } @Test(expected = NoSuchElementException.class) public void emptyIteratorThrowsException() { new IteratorOfShorts().next(); } @Test public void nonEmptyIteratorDoesNotHaveNext() { final IteratorOfShorts iterator = new IteratorOfShorts( (short) 1, (short) 2 ); iterator.next(); iterator.next(); new Assertion<>( "hasNext is true for fully traversed iterator.", iterator.hasNext(), new IsEqual<>(false) ).affirm(); } @Test(expected = NoSuchElementException.class) public void nonEmptyIteratorThrowsException() { final IteratorOfShorts iterator = new IteratorOfShorts((short) 1); iterator.next(); iterator.next(); } } cactoos-0.49/src/test/java/org/cactoos/iterator/IteratorOfTest.java000066400000000000000000000064701400054650300254300ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.iterator; import java.util.Iterator; import java.util.NoSuchElementException; import org.cactoos.iterable.IterableOf; import org.hamcrest.core.IsNot; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.HasValues; import org.llorllale.cactoos.matchers.IsTrue; import org.llorllale.cactoos.matchers.Throws; /** * Test case for {@link IteratorOf}. * @since 0.30 * @checkstyle JavadocMethodCheck (500 lines) * @checkstyle ClassDataAbstractionCouplingCheck (500 lines) */ final class IteratorOfTest { @Test void emptyIteratorDoesNotHaveNext() { new Assertion<>( "Must create empty iterator", new IteratorOf<>().hasNext(), new IsNot<>(new IsTrue()) ).affirm(); } @Test void emptyIteratorThrowsException() { new Assertion<>( "Must throw an exception if empty", () -> new IteratorOf<>().next(), new Throws<>(NoSuchElementException.class) ).affirm(); } @Test void nonEmptyIteratorDoesNotHaveNext() { final Iterator iterator = new IteratorOf<>( 1, 2, 3 ); while (iterator.hasNext()) { iterator.next(); } new Assertion<>( "Must create non empty iterator", iterator.hasNext(), new IsNot<>(new IsTrue()) ).affirm(); } @Test void nonEmptyIteratorThrowsException() { final Iterator iterator = new IteratorOf<>( 'a', 'b' ); while (iterator.hasNext()) { iterator.next(); } new Assertion<>( "Must throw an exception if consumed", iterator::next, new Throws<>(NoSuchElementException.class) ).affirm(); } @Test void convertStringsToIterator() { new Assertion<>( "Must create an iterator of strings", new IterableOf<>( new IteratorOf<>( "a", "b", "c" ) ), new HasValues<>( "a", "b", "c" ) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/iterator/JoinedTest.java000066400000000000000000000067301400054650300245610ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.iterator; import java.util.NoSuchElementException; import org.cactoos.iterable.IterableOf; import org.hamcrest.core.IsEqual; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.Throws; /** * Test case for {@link Joined}. * @since 0.14 * @checkstyle JavadocMethodCheck (500 lines) * @checkstyle ClassDataAbstractionCouplingCheck (500 lines) * @checkstyle MagicNumber (500 lines) */ final class JoinedTest { @Test @SuppressWarnings("unchecked") void joinsIterators() { new Assertion<>( "Must concatenate iterable of iterators together", new IterableOf<>( new Joined<>( new IterableOf<>( new IteratorOf<>("x"), new IteratorOf<>("y") ) ) ), new IsEqual<>(new IterableOf<>("x", "y")) ).affirm(); } @Test void callsNextDirectlyOnNonEmptyIterator() { new Assertion<>( "Must call next method directly on non-empty iterator", new Joined( new IteratorOf<>(1), new IteratorOf<>(2) ).next(), new IsEqual<>(1) ).affirm(); } @Test void throwsExceptionWhenCallNextOnEmptyIterator() { new Assertion<>( "Must throw an exception", () -> new Joined(new IteratorOf<>()).next(), new Throws<>(NoSuchElementException.class) ).affirm(); } @Test @SuppressWarnings("unchecked") void joinItemAndIterable() { new Assertion<>( "Must join item and iterable", new IterableOf<>( new Joined<>( 0, new IteratorOf<>(1, 2, 3) ) ), new IsEqual<>(new IterableOf<>(0, 1, 2, 3)) ).affirm(); } @Test @SuppressWarnings("unchecked") void joinIterableAndItem() { new Assertion<>( "Must join iterable and item", new IterableOf<>( new Joined<>( new IteratorOf<>(1, 2, 3), 0 ) ), new IsEqual<>(new IterableOf<>(1, 2, 3, 0)) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/iterator/MappedTest.java000066400000000000000000000044051400054650300245540ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.iterator; import java.util.Iterator; import java.util.NoSuchElementException; import org.cactoos.iterable.IterableOf; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.HasValues; import org.llorllale.cactoos.matchers.Throws; /** * Tests for {@link org.cactoos.iterator.Mapped}. * * @since 0.47 */ final class MappedTest { @Test void iteratatesOver() { new Assertion<>( "must map values of iterator", new IterableOf<>( new Mapped<>( Number::toString, new IteratorOf(1L, 2, 0) ) ), new HasValues<>("1", "2", "0") ).affirm(); } @Test void failsIfIteratorExhausted() { final Iterator iterator = new Mapped<>( Number::toString, new IteratorOf(1) ); iterator.next(); new Assertion<>( "must throw NSEE", iterator::next, new Throws<>(NoSuchElementException.class) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/iterator/MatchedTest.java000066400000000000000000000061331400054650300247130ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.iterator; import java.util.Objects; import org.cactoos.list.ListOf; import org.hamcrest.core.IsEqual; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.HasValues; import org.llorllale.cactoos.matchers.Throws; /** * Test case for {@link Mapped}. * @since 0.47 * @checkstyle MagicNumberCheck (500 lines) */ final class MatchedTest { @Test void failsWhenElementsNotMatch() { new Assertion<>( "All elements have correlation function 'equals'", () -> new ListOf<>( new Matched<>( Objects::equals, new IteratorOf<>(1), new IteratorOf<>(0) ) ), new Throws<>( new IsEqual<>( "There is no correlation between `1` and `0`." ), IllegalStateException.class ) ).affirm(); } @Test void failsOnSizeMismatch() { new Assertion<>( "must fail if sizes of iterators are different", () -> new ListOf<>( new Matched<>( Objects::equals, new IteratorOf<>(1), new IteratorOf<>() ) ), new Throws<>( new IsEqual<>("Size mismatch of iterators"), IllegalStateException.class ) ).affirm(); } @Test void shouldProduceValuesOfFirstIterator() { new Assertion<>( "must match all items of first iterator", new ListOf<>( new Matched<>( (Number first, Number second) -> first.intValue() == second.intValue(), new IteratorOf<>(1f, 2f, 3f), new IteratorOf<>(1L, 2L, 3L) ) ), new HasValues<>(1f, 2f, 3f) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/iterator/NoNullsTest.java000066400000000000000000000050061400054650300247360ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.iterator; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.MatcherOf; import org.llorllale.cactoos.matchers.Throws; /** * Test cases for {@link NoNulls}. * *

There is no thread-safety guarantee. * @checkstyle JavadocMethodCheck (500 lines) * @since 0.35 */ @SuppressWarnings("PMD.AvoidDuplicateLiterals") final class NoNullsTest { @Test void nextThrowsErrorIfNull() { new Assertion<>( "Must throw exception", () -> new NoNulls<>( new IteratorOf<>(new String[]{null}) ).next(), new Throws<>( new MatcherOf<>( (String msg) -> msg.matches("^Item #0 of .*? is NULL") ), IllegalStateException.class ) ).affirm(); } @Test void nthThrowsErrorIfNull() { new Assertion<>( "Must throw exception", () -> new TailOf<>( 1, new NoNulls<>( new IteratorOf<>("a", "b", null, "c") ) ).next(), new Throws<>( new MatcherOf<>( (String msg) -> msg.matches("^Item #2 of .*? is NULL") ), IllegalStateException.class ) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/iterator/PartitionedTest.java000066400000000000000000000102331400054650300256240ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.iterator; import java.util.ArrayList; import java.util.Collections; import java.util.NoSuchElementException; import org.cactoos.iterable.IterableOf; import org.cactoos.list.ListOf; import org.cactoos.scalar.LengthOf; import org.hamcrest.Matchers; import org.hamcrest.core.IsEqual; import org.junit.Test; import org.llorllale.cactoos.matchers.Assertion; /** * Test case for {@link Partitioned}. * * @since 0.29 * @checkstyle JavadocMethodCheck (500 lines) * @checkstyle MagicNumber (500 lines) */ public final class PartitionedTest { @Test public void emptyPartitioned() { new Assertion<>( "Can't generate an empty Partitioned.", new LengthOf( new IterableOf<>( new Partitioned<>(1, Collections.emptyIterator()) ) ).intValue(), Matchers.equalTo(0) ).affirm(); } @Test @SuppressWarnings("unchecked") public void partitionedOne() { new Assertion<>( "Can't generate a Partitioned of partition size 1.", new ArrayList<>( new ListOf<>( new Partitioned<>(1, new ListOf<>(1, 2, 3).iterator()) ) ), Matchers.equalTo( new ListOf<>( Collections.singletonList(1), Collections.singletonList(2), Collections.singletonList(3) ) ) ).affirm(); } @Test @SuppressWarnings("unchecked") public void partitionedEqualSize() { new Assertion<>( "Can't generate a Partitioned of partition size 2.", new ArrayList<>( new ListOf<>( new Partitioned<>(2, new ListOf<>(1, 2, 3, 4).iterator()) ) ), Matchers.equalTo( new ListOf<>(new ListOf<>(1, 2), new ListOf<>(3, 4)) ) ).affirm(); } @Test @SuppressWarnings("unchecked") public void partitionedLastPartitionSmaller() { new Assertion<>( "Can't generate a Partitioned of size 2 last partition smaller.", new ListOf<>( new Partitioned<>(2, new ListOf<>(1, 2, 3).iterator()) ), new IsEqual<>( new ListOf<>( new ListOf<>(1, 2), new ListOf<>(3) ) ) ).affirm(); } @Test(expected = IllegalArgumentException.class) public void partitionedWithPartitionSizeSmallerOne() { new Partitioned<>(0, new ListOf<>(1).iterator()).next(); } @Test(expected = UnsupportedOperationException.class) public void partitionedListsAreUnmodifiable() { new Partitioned<>( 2, new ListOf<>(1, 2).iterator() ).next().clear(); } @Test(expected = NoSuchElementException.class) public void emptyPartitionedNextThrowsException() { new Partitioned<>( 2, Collections.emptyIterator() ).next(); } } cactoos-0.49/src/test/java/org/cactoos/iterator/RepeatedTest.java000066400000000000000000000040231400054650300250730ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.iterator; import org.cactoos.iterable.IterableOf; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.HasSize; /** * Test case for {@link Repeated}. * * @since 0.4 * @checkstyle JavadocMethodCheck (500 lines) */ final class RepeatedTest { @Test void allSameTest() { final int size = 42; final int element = 11; new Assertion<>( "Must generate an iterable with fixed size", new IterableOf<>( new Repeated<>( size, element ) ), new HasSize(size) ).affirm(); } @Test void emptyTest() { new Assertion<>( "Must generate an empty iterator", new IterableOf<>(new Repeated<>(0, 0)), new HasSize(0) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/iterator/ReversedTest.java000066400000000000000000000051301400054650300251210ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.iterator; import org.cactoos.list.ListOf; import org.hamcrest.collection.IsEmptyCollection; import org.hamcrest.core.IsEqual; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.HasSize; /** * Test case for {@link Reversed}. * * @since 0.45 * @checkstyle MagicNumberCheck (500 lines) */ final class ReversedTest { @Test void reversesIterator() { new Assertion<>( "Must reverse the iterator", new ListOf<>( new Reversed<>( new IteratorOf<>("c", "a", "c", "t", "o", "o", "s") ) ), new IsEqual<>( new ListOf<>( new IteratorOf<>("s", "o", "o", "t", "c", "a", "c") ) ) ).affirm(); } @Test void reversesEmptyList() { new Assertion<>( "Must reverse empty list", new ListOf<>( new Reversed<>( new IteratorOf<>() ) ), new IsEmptyCollection<>() ).affirm(); } @Test void iteratorSizeReversed() { new Assertion<>( "Must be the same size", new ListOf<>( new Reversed<>( new IteratorOf<>("c", "a", "c", "t", "o", "o", "s") ) ), new HasSize(7) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/iterator/ShuffledTest.java000066400000000000000000000035411400054650300251060ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.iterator; import org.cactoos.iterable.IterableOf; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.HasValues; /** * Test Case for {@link Shuffled}. * @since 0.20 * @checkstyle JavadocMethodCheck (500 lines) */ final class ShuffledTest { @Test void shuffleIterable() { new Assertion<>( "Must shuffle elements in iterator", new IterableOf<>( new Shuffled<>( new IteratorOf<>( "a", "b" ) ) ), new HasValues<>( "a", "b" ) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/iterator/SkippedTest.java000066400000000000000000000046131400054650300247460ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.iterator; import java.util.NoSuchElementException; import org.cactoos.iterable.IterableOf; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.HasValues; import org.llorllale.cactoos.matchers.Throws; /** * Test Case for {@link Skipped}. * * @since 0.34 * @checkstyle JavadocMethodCheck (500 lines) */ final class SkippedTest { @Test @SuppressWarnings("PMD.AvoidDuplicateLiterals") void skipIterator() { new Assertion<>( "Must skip elements in iterator", new IterableOf<>( new Skipped<>( 2, new IteratorOf<>( "one", "two", "three", "four" ) ) ), new HasValues<>( "three", "four" ) ).affirm(); } @Test void errorSkippedMoreThanExists() { new Assertion<>( "Must throw an exception", () -> new Skipped<>( 2, new IteratorOf<>( "one", "two" ) ).next(), new Throws<>(NoSuchElementException.class) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/iterator/SlicedTest.java000066400000000000000000000071151400054650300245520ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.iterator; import java.util.NoSuchElementException; import org.cactoos.iterable.IterableOf; import org.cactoos.scalar.Constant; import org.hamcrest.core.IsEqual; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.Throws; /** * Test for {@link Sliced}. * @since 1.0 * @checkstyle JavadocMethodCheck (500 lines) * @checkstyle MagicNumberCheck (500 lines) */ final class SlicedTest { @Test void sliceTheMiddle() { new Assertion<>( "Must return sliced iterator", new IterableOf<>( new Sliced<>( 3, 2, new IteratorOf<>( 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 ) ) ), new IsEqual<>( new IterableOf<>( 4, 5 ) ) ).affirm(); } @Test void sliceTheHead() { new Assertion<>( "Must return iterator with the head elements", new IterableOf<>( new Sliced<>( 0, 5, new IteratorOf<>( 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 ) ) ), new IsEqual<>( new IterableOf<>( 1, 2, 3, 4, 5 ) ) ).affirm(); } @Test void sliceTheWholeTail() { new Assertion<>( "Must return the iterator of tail elements", new IterableOf<>( new Sliced<>( 5, new IteratorOf<>( 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 ) ) ), new IsEqual<>( new IterableOf<>( 6, 7, 8, 9, 0 ) ) ).affirm(); } @Test void failSlicing() { new Assertion<>( "Must fail on slicing", () -> new Constant<>( new Sliced<>( 0, 0, new IteratorOf<>( 1 ) ).next() ).value(), new Throws<>( "The iterator doesn't have items any more", NoSuchElementException.class ) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/iterator/SortedTest.java000066400000000000000000000036641400054650300246140ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.iterator; import org.cactoos.iterable.IterableOf; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.HasValues; /** * Test Case for {@link Sorted}. * @since 0.19 * @checkstyle JavadocMethodCheck (500 lines) */ final class SortedTest { @Test @SuppressWarnings("PMD.AvoidDuplicateLiterals") void sortsIterable() { new Assertion<>( "Must sort elements in iterator", new IterableOf<>( new Sorted<>( new IteratorOf<>( "one", "two", "three", "four" ) ) ), new HasValues<>( "four", "one", "three", "two" ) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/iterator/SyncedTest.java000066400000000000000000000112511400054650300245700ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.iterator; import java.util.concurrent.locks.ReentrantReadWriteLock; import org.cactoos.list.ListOf; import org.hamcrest.Matchers; import org.hamcrest.core.IsEqual; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.RunsInThreads; /** * Test for {@link Synced}. * * @since 1.0 * @checkstyle JavadocMethodCheck (500 lines) * @checkstyle MagicNumberCheck (500 lines) * @checkstyle TodoCommentCheck (500 lines) */ @SuppressWarnings("PMD.AvoidDuplicateLiterals") final class SyncedTest { @Test void syncIteratorReturnsCorrectValuesWithExternalLock() { final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); new Assertion<>( "Unexpected value found.", new ListOf<>( new Synced<>( lock, new IteratorOf<>("a", "b") ) ).toArray(), new IsEqual<>(new Object[]{"a", "b"}) ).affirm(); } @Test void syncIteratorReturnsCorrectValuesWithInternalLock() { new Assertion<>( "Unexpected value found.", new ListOf<>( new Synced<>( new IteratorOf<>("a", "b") ) ).toArray(), new IsEqual<>(new Object[]{"a", "b"}) ).affirm(); } @Test @SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops") void correctValuesForConcurrentNextNext() { for (int iter = 0; iter < 5000; iter += 1) { new Assertion<>( "", map -> { new Assertion<>( "", map.next(), Matchers.anyOf( new IsEqual<>("a"), new IsEqual<>("b") ) ).affirm(); return true; }, new RunsInThreads<>( new Synced<>( new IteratorOf<>("a", "b") ), 2 ) ).affirm(); } } @Test @SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops") void correctValuesForConcurrentNextHasNext() { for (int iter = 0; iter < 5000; iter += 1) { new Assertion<>( "", map -> { new Assertion<>( "", map.hasNext(), Matchers.anyOf( new IsEqual<>(true), new IsEqual<>(true) ) ).affirm(); new Assertion<>( "", map.next(), Matchers.anyOf( new IsEqual<>("a"), new IsEqual<>("b") ) ).affirm(); new Assertion<>( "", map.hasNext(), Matchers.anyOf( new IsEqual<>(true), new IsEqual<>(false) ) ).affirm(); return true; }, new RunsInThreads<>( new Synced<>( new IteratorOf<>("a", "b") ), 2 ) ).affirm(); } } } cactoos-0.49/src/test/java/org/cactoos/iterator/TailOfTest.java000066400000000000000000000064061400054650300245270ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.iterator; import java.util.NoSuchElementException; import org.cactoos.iterable.IterableOf; import org.hamcrest.core.IsEqual; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.HasSize; import org.llorllale.cactoos.matchers.Throws; /** * Test case for {@link TailOf}. * @since 0.31 * @checkstyle JavadocMethodCheck (500 lines) * @checkstyle MagicNumberCheck (500 lines) */ final class TailOfTest { @Test @SuppressWarnings("PMD.AvoidDuplicateLiterals") void tailIterator() { new Assertion<>( "Must get tail portion of iterator", new IterableOf<>( new TailOf<>( 2, new IteratorOf<>( "one", "two", "three", "four" ) ) ), new IsEqual<>( new IterableOf<>( "three", "four" ) ) ).affirm(); } @Test void returnsIntactIterator() { new Assertion<>( "Must return an intact iterator", new IterableOf<>( new TailOf<>( 3, new IteratorOf<>( "one", "two" ) ) ), new HasSize(2) ).affirm(); } @Test void returnsEmptyIterator() { new Assertion<>( "Must throw an exception if empty", () -> new TailOf<>( 0, new IteratorOf<>( "one", "two" ) ).next(), new Throws<>(NoSuchElementException.class) ).affirm(); } @Test void emptyIteratorForNegativeSize() { new Assertion<>( "Must throw an exception for negative size", () -> new TailOf<>( -1, new IteratorOf<>( "one", "two" ) ).next(), new Throws<>(NoSuchElementException.class) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/iterator/package-info.java000066400000000000000000000023171400054650300250320ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ /** * Iterator, tests. * * @since 0.12 */ package org.cactoos.iterator; cactoos-0.49/src/test/java/org/cactoos/list/000077500000000000000000000000001400054650300207625ustar00rootroot00000000000000cactoos-0.49/src/test/java/org/cactoos/list/BehavesAsList.java000066400000000000000000000060671400054650300243330ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.list; import java.util.List; import org.cactoos.collection.BehavesAsCollection; import org.hamcrest.Description; import org.hamcrest.TypeSafeMatcher; import org.hamcrest.core.IsNot; import org.hamcrest.core.IsNull; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.IsTrue; import org.llorllale.cactoos.matchers.MatcherOf; /** * Matcher for collection. * @param Type of source item * @since 0.23 * @checkstyle JavadocMethodCheck (500 lines) */ public final class BehavesAsList extends TypeSafeMatcher> { /** * Sample item. */ private final E sample; /** * Ctor. * @param item Sample item */ public BehavesAsList(final E item) { super(); this.sample = item; } @Override public boolean matchesSafely(final List list) { new Assertion<>( "must contain at least one non-null element", list.get(0), new IsNot<>(new IsNull<>()) ).affirm(); new Assertion<>( "must have an index for the sample item", list.indexOf(this.sample), new MatcherOf<>(i -> i >= 0) ).affirm(); new Assertion<>( "must have a last index for the sample item", list.lastIndexOf(this.sample), new MatcherOf<>(i -> i >= 0) ).affirm(); new Assertion<>( "must have at least one element in list iterator", list.listIterator().hasNext(), new IsTrue() ).affirm(); new Assertion<>( "must have at least one element in sublist iterator", list.subList(0, 1).iterator().hasNext(), new IsTrue() ).affirm(); return new BehavesAsCollection(this.sample).matchesSafely(list); } @Override public void describeTo(final Description desc) { desc.appendText("not a valid list"); } } cactoos-0.49/src/test/java/org/cactoos/list/ImmutableListIteratorTest.java000066400000000000000000000104621400054650300267550ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.list; import org.hamcrest.core.IsEqual; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.Throws; /** * Test case for {@link ImmutableListIterator}. * @since 1.0 * @checkstyle JavadocMethodCheck (500 lines) * @checkstyle JavadocTypeCheck (500 lines) * @checkstyle MagicNumberCheck (500 lines) */ @SuppressWarnings({"PMD.TooManyMethods", "PMD.AvoidDuplicateLiterals"}) final class ImmutableListIteratorTest { @Test void mustReturnPreviousIndex() { new Assertion<>( "Must return next previous index", new ImmutableListIterator<>( new ListOf<>(1).listIterator() ).previousIndex(), new IsEqual<>(-1) ).affirm(); } @Test void mustReturnPreviousElement() { new Assertion<>( "Must return previous element", new ImmutableListIterator<>( new ListOf<>(3, 7).listIterator(1) ).previous(), new IsEqual<>(3) ).affirm(); } @Test void mustReturnNextIndex() { new Assertion<>( "Must return next index", new ImmutableListIterator<>( new ListOf<>(1).listIterator() ).nextIndex(), new IsEqual<>(0) ).affirm(); } @Test void mustReturnNextElement() { new Assertion<>( "Must return next element", new ImmutableListIterator<>( new ListOf<>(5, 11, 13).listIterator(1) ).next(), new IsEqual<>(11) ).affirm(); } @Test void mustRaiseErrorOnListIteratorRemove() { new Assertion<>( "Must throw error if modified with remove operation", () -> { new ImmutableListIterator<>( new ListOf<>(1, 2).listIterator() ).remove(); return 0; }, new Throws<>( "List Iterator is read-only and doesn't allow removing items", UnsupportedOperationException.class ) ).affirm(); } @Test void mustRaiseErrorOnListIteratorAdd() { new Assertion<>( "Must throw error if modified with add operation", () -> { new ImmutableListIterator<>( new ListOf<>(1, 2).listIterator() ).add(1); return 0; }, new Throws<>( "List Iterator is read-only and doesn't allow adding items", UnsupportedOperationException.class ) ).affirm(); } @Test void mustRaiseErrorOnListIteratorSet() { new Assertion<>( "Must throw error if modified with set operation", () -> { new ImmutableListIterator<>( new ListOf<>(1, 2).listIterator() ).set(1); return 0; }, new Throws<>( "List Iterator is read-only and doesn't allow rewriting items", UnsupportedOperationException.class ) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/list/ImmutableTest.java000066400000000000000000000426721400054650300244170ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.list; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.ListIterator; import org.hamcrest.core.IsEqual; import org.hamcrest.core.IsNot; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.HasValues; import org.llorllale.cactoos.matchers.MatcherOf; import org.llorllale.cactoos.matchers.Throws; /** * Test case for {@link Immutable}. * * @since 1.16 * @checkstyle MagicNumberCheck (500 lines) * @checkstyle ClassDataAbstractionCouplingCheck (500 lines) */ @SuppressWarnings({"PMD.TooManyMethods", "PMD.AvoidDuplicateLiterals"}) public class ImmutableTest { @Test void innerListIsDecorated() { final List strings = new ArrayList<>(Arrays.asList("a", "b", "c")); final List immutable = new Immutable<>(strings); strings.add("d"); new Assertion<>( "Must reflect inner list in the decorator", immutable, new IsEqual<>(strings) ).affirm(); } @Test void returnsListIteratorWithUnsupportedRemove() { new Assertion<>( "Must return a list iterator that does not support remove()", () -> { final List list = new Immutable<>(new ListOf<>("one")); final ListIterator iterator = list.listIterator(); iterator.next(); iterator.remove(); return true; }, new Throws<>(UnsupportedOperationException.class) ).affirm(); } @Test void returnsListIteratorWithUnsupportedAdd() { new Assertion<>( "Must return a list iterator that does not support add()", () -> { final List list = new Immutable<>(new ListOf<>("one")); final ListIterator iterator = list.listIterator(); iterator.next(); iterator.add("two"); return true; }, new Throws<>(UnsupportedOperationException.class) ).affirm(); } @Test void subListReturnsListIteratorWithUnsupportedRemove() { new Assertion<>( "Must return a subtlist with a list iterator that does not support remove()", () -> { final List list = new Immutable<>(new ListOf<>("one")); final ListIterator iterator = list.subList(0, 1).listIterator(); iterator.next(); iterator.remove(); return true; }, new Throws<>(UnsupportedOperationException.class) ).affirm(); } @Test void subListReturnsListIteratorWithUnsupportedAdd() { new Assertion<>( "Must return a subtlist with a list iterator that does not support add()", () -> { final List list = new Immutable<>(new ListOf<>("one")); final ListIterator iterator = list.subList(0, 1).listIterator(); iterator.next(); iterator.add("two"); return true; }, new Throws<>(UnsupportedOperationException.class) ).affirm(); } @Test() void subListReturnsListIteratorWithUnsupportedSet() { new Assertion<>( "subList.listIterator().set() must throw exception", () -> { final ListIterator iterator = new Immutable<>( new ListOf<>("one", "two", "three") ).subList(0, 2).listIterator(0); iterator.next(); iterator.set("zero"); return new Object(); }, new Throws<>( "List Iterator is read-only and doesn't allow rewriting items", UnsupportedOperationException.class ) ).affirm(); } @Test() void returnsSubListWithUnsupportedSet() { new Assertion<>( "subList.set() must throw exception", () -> new Immutable<>(new ListOf<>("one")).subList(0, 1).set(0, "zero"), new Throws<>( "#set(): the list is read-only", UnsupportedOperationException.class ) ).affirm(); } @Test void size() { new Assertion<>( "size() must be equals to original", new Immutable<>( new ListOf<>(1, 2) ).size(), new IsEqual<>( new ListOf<>(1, 2).size() ) ).affirm(); } @Test void isEmpty() { new Assertion<>( "isEmpty() must be equals to original", new Immutable<>( new ListOf<>(1, 2) ).isEmpty(), new IsEqual<>( new ListOf<>(1, 2).isEmpty() ) ).affirm(); } @Test void contains() { new Assertion<>( "contains() must be equals to original", new Immutable<>( new ListOf<>("a", "b") ).contains("b"), new IsEqual<>( new ListOf<>("a", "b").contains("b") ) ).affirm(); } @Test void iterator() { new Assertion<>( "iterator() is equal to original", () -> new Immutable<>( new ListOf<>(1, 2) ).iterator(), new HasValues<>(1, 2) ).affirm(); } @Test void toArray() { new Assertion<>( "toArray() must be equals to original", new Immutable<>( new ListOf<>("a", "b") ).toArray(), new IsEqual<>( new ListOf<>("a", "b").toArray() ) ).affirm(); } @Test void testToArray() { new Assertion<>( "toArray(T[]) must be equals to original", new Immutable<>( new ListOf<>("a", "b") ).toArray(new String[3]), new IsEqual<>( new ListOf<>("a", "b").toArray(new String[3]) ) ).affirm(); } @Test void add() { new Assertion<>( "add(T) must throw exception", () -> new Immutable<>( new ListOf<>(1, 2) ).add(3), new Throws<>( new MatcherOf<>( (String msg) -> msg.equals("#add(T): the list is read-only") ), UnsupportedOperationException.class ) ).affirm(); } @Test void remove() { new Assertion<>( "remove(Object) must throw exception", () -> new Immutable<>( new ListOf<>("1", "2") ).remove("1"), new Throws<>( new MatcherOf<>( (String msg) -> msg.equals("#remove(Object): the list is read-only") ), UnsupportedOperationException.class ) ).affirm(); } @Test void containsAll() { new Assertion<>( "containsAll() must be equals to original", new Immutable<>( new ListOf<>("a", "b", "c") ).containsAll(new ListOf<>("a", "c")), new IsEqual<>( new ListOf<>("a", "b", "c").containsAll( new ListOf<>("a", "c") ) ) ).affirm(); } @Test void addAll() { new Assertion<>( "addAll(Collection) must throw exception", () -> new Immutable<>( new ListOf<>(1, 2) ).addAll(new ListOf<>(3, 4)), new Throws<>( new MatcherOf<>( (String msg) -> msg.equals("#addAll(Collection): the list is read-only") ), UnsupportedOperationException.class ) ).affirm(); } @Test void testAddAll() { new Assertion<>( "addAll(int, Collection) must throw exception", () -> new Immutable<>( new ListOf<>(1, 2) ).addAll(2, new ListOf<>(3, 4)), new Throws<>( new MatcherOf<>( (String msg) -> msg.equals("#addAll(int, Collection): the list is read-only") ), UnsupportedOperationException.class ) ).affirm(); } @Test void removeAll() { new Assertion<>( "removeAll() must throw exception", () -> new Immutable<>( new ListOf<>(1, 2, 3) ).removeAll(new ListOf<>(1, 3)), new Throws<>( new MatcherOf<>( (String msg) -> msg.equals("#removeAll(): the list is read-only") ), UnsupportedOperationException.class ) ).affirm(); } @Test void retainAll() { new Assertion<>( "retainAll() must throw exception", () -> new Immutable<>( new ListOf<>(1, 2, 3) ).retainAll(new ListOf<>(1, 3)), new Throws<>( new MatcherOf<>( (String msg) -> msg.equals("#retainAll(): the list is read-only") ), UnsupportedOperationException.class ) ).affirm(); } @Test void clear() { new Assertion<>( "clear() must throw exception", () -> { new Immutable<>( new ListOf<>(1, 2, 3) ).clear(); return new Object(); }, new Throws<>( new MatcherOf<>( (String msg) -> msg.equals("#clear(): the list is read-only") ), UnsupportedOperationException.class ) ).affirm(); } @Test void get() { new Assertion<>( "get() must be equals to original", new Immutable<>( new ListOf<>("a", "b", "c") ).get(2), new IsEqual<>( new ListOf<>("a", "b", "c").get(2) ) ).affirm(); } @Test void set() { new Assertion<>( "set() must throw exception", () -> new Immutable<>( new ListOf<>("a", "b") ).set(3, "c"), new Throws<>( new MatcherOf<>( (String msg) -> msg.equals("#set(): the list is read-only") ), UnsupportedOperationException.class ) ).affirm(); } @Test void testAdd() { new Assertion<>( "add(int, T) must throw exception", () -> { new Immutable<>( new ListOf<>("a", "b") ).add(3, "c"); return new Object(); }, new Throws<>( new MatcherOf<>( (String msg) -> msg.equals("#add(int, T): the list is read-only") ), UnsupportedOperationException.class ) ).affirm(); } @Test void testRemove() { new Assertion<>( "remove(int) must throw exception", () -> new Immutable<>( new ListOf<>("a", "b") ).remove(2), new Throws<>( new MatcherOf<>( (String msg) -> msg.equals("#remove(int): the list is read-only") ), UnsupportedOperationException.class ) ).affirm(); } @Test void indexOf() { new Assertion<>( "indexOf() must be equals to original", new Immutable<>( new ListOf<>("a", "b", "c") ).indexOf("b"), new IsEqual<>( new ListOf<>("a", "b", "c").indexOf("b") ) ).affirm(); } @Test void lastIndexOf() { new Assertion<>( "lastIndexOf() must be equals to original", new Immutable<>( new ListOf<>("a", "b", "c", "b") ).lastIndexOf("b"), new IsEqual<>( new ListOf<>("a", "b", "c", "b").lastIndexOf("b") ) ).affirm(); } @Test void listIterator() { new Assertion<>( "listIterator() is equal to original", () -> new Immutable<>( new ListOf<>("a", "b", "c", "b") ).listIterator(), new HasValues<>("a", "b", "c", "b") ).affirm(); } @Test void testListIterator() { new Assertion<>( "listIterator(int) is equal to original", () -> new Immutable<>( new ListOf<>("a", "b", "c", "b") ).listIterator(2), new HasValues<>("c", "b") ).affirm(); } @Test void subList() { new Assertion<>( "subList() must be equals to original", new Immutable<>( new ListOf<>("a", "b", "c") ).subList(1, 2), new IsEqual<>( new ListOf<>("a", "b", "c").subList(1, 2) ) ).affirm(); } @Test void immutableSubList() { new Assertion<>( "subList() result must be immutable", () -> new Immutable<>( new ListOf<>("a", "b", "c") ).subList(0, 2).add("d"), new Throws<>( new MatcherOf<>( (String msg) -> msg.equals("#add(T): the list is read-only") ), UnsupportedOperationException.class ) ).affirm(); } @Test void notEqualsToObjectOfAnotherType() { new Assertion<>( "must not equal to object of another type", new Immutable<>(new ListOf<>()), new IsNot<>(new IsEqual<>(new Object())) ).affirm(); } @Test void notEqualsToListWithDifferentElements() { new Assertion<>( "must not equal to List with different elements", new Immutable<>(new ListOf<>(1, 2)), new IsNot<>(new IsEqual<>(new ListOf<>(1, 0))) ).affirm(); } @Test void isEqualToItself() { final List list = new Immutable<>(new ListOf<>(1, 2)); new Assertion<>( "must be equal to itself", list, new IsEqual<>(list) ).affirm(); } @Test void isEqualToListWithTheSameElements() { new Assertion<>( "must be equal to List with the same elements", new Immutable<>(new ListOf<>(1, 2)), new IsEqual<>(new ListOf<>(1, 2)) ).affirm(); } @Test void equalToEmptyImmutable() { new Assertion<>( "empty Immutable must be equal to empty Immutable", new Immutable<>(new ListOf<>()), new IsEqual<>(new Immutable<>(new ListOf<>())) ).affirm(); } @Test void testHashCode() { new Assertion<>( "hashCode() must be equal to hashCode of the corresponding List", new Immutable<>(new ListOf<>(1, 2)).hashCode(), new IsEqual<>( new ListOf<>(1, 2).hashCode() ) ).affirm(); } @Test void testToString() { new Assertion<>( "toString() must be equal to toString of the corresponding List", new Immutable<>(new ListOf<>("a", "b", "c")).toString(), new IsEqual<>(new ListOf<>("a", "b", "c").toString()) ).affirm(); } @Test void subListReturnsListIteratorWithSupportedSet() { new Assertion<>( "subList's iterator must be immutable", () -> { final ListIterator iterator = new Immutable<>( new ListOf("one", "two", "three") ) .subList(0, 2) .listIterator(0); iterator.next(); iterator.set("zero"); return new Object(); }, new Throws<>( new MatcherOf<>( (String msg) -> msg.equals( "List Iterator is read-only and doesn't allow rewriting items" ) ), UnsupportedOperationException.class ) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/list/JoinedTest.java000066400000000000000000000327631400054650300237100ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.list; import java.util.List; import org.hamcrest.Matcher; import org.hamcrest.collection.IsIterableContainingInOrder; import org.hamcrest.core.IsEqual; import org.hamcrest.core.IsInstanceOf; import org.hamcrest.core.IsNot; import org.junit.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.IsTrue; /** * Test case for {@link org.cactoos.list.Joined}. * * @since 0.20 * @checkstyle JavadocMethodCheck (500 lines) * @checkstyle MagicNumber (500 line) * @checkstyle DiamondOperatorCheck (500 lines) * @checkstyle ClassDataAbstractionCouplingCheck (500 lines) */ @SuppressWarnings("PMD.TooManyMethods") public final class JoinedTest { /** * Literal ONE value. */ private static final String LITERAL_ONE = "ONE"; /** * Literal TWO value. */ private static final String LITERAL_TWO = "TWO"; /** * Literal THREE value. */ private static final String LITERAL_THREE = "THREE"; /** * Literal FOUR value. */ private static final String LITERAL_FOUR = "FOUR"; @Test public void behavesAsCollection() { new Assertion<>( "Can't behave as a list", new Joined( new ListOf<>( JoinedTest.LITERAL_ONE, JoinedTest.LITERAL_TWO ), new ListOf<>( JoinedTest.LITERAL_THREE, JoinedTest.LITERAL_FOUR ) ), new BehavesAsList<>(JoinedTest.LITERAL_TWO) ).affirm(); } @Test public void size() { new Assertion<>( "Must evaluate the size of the joined list", new Joined( new ListOf<>( JoinedTest.LITERAL_ONE, JoinedTest.LITERAL_TWO ), new ListOf<>( JoinedTest.LITERAL_THREE, JoinedTest.LITERAL_FOUR ) ).size(), new IsEqual<>(4) ).affirm(); } @Test public void isEmpty() { new Assertion<>( "Must be evaluated as an empty list", new Joined( new ListOf<>( JoinedTest.LITERAL_ONE, JoinedTest.LITERAL_TWO ), new ListOf<>( JoinedTest.LITERAL_THREE, JoinedTest.LITERAL_FOUR ) ).isEmpty(), new IsNot<>(new IsTrue()) ).affirm(); } @Test public void contains() { new Assertion<>( "Must contain element specified", new Joined( new ListOf<>( JoinedTest.LITERAL_ONE, JoinedTest.LITERAL_TWO ), new ListOf<>( JoinedTest.LITERAL_THREE, JoinedTest.LITERAL_FOUR ) ).contains(JoinedTest.LITERAL_THREE), new IsTrue() ).affirm(); } @Test public void iterator() { new Assertion<>( "Joined Iterator Must return next element equal to the first added", new Joined( new ListOf<>( JoinedTest.LITERAL_ONE, JoinedTest.LITERAL_TWO ), new ListOf<>( JoinedTest.LITERAL_THREE, JoinedTest.LITERAL_FOUR ) ).iterator().next(), new IsEqual<>( JoinedTest.LITERAL_ONE ) ).affirm(); } @Test public void add() { final List joined = new Joined( new ListOf<>(JoinedTest.LITERAL_ONE), new ListOf<>(JoinedTest.LITERAL_TWO) ); joined.add(JoinedTest.LITERAL_THREE); new Assertion<>( "Must be able to add element specified", joined, new IsEqual<>( new ListOf<>( JoinedTest.LITERAL_ONE, JoinedTest.LITERAL_TWO, JoinedTest.LITERAL_THREE ) ) ).affirm(); } @Test public void remove() { final List joined = new Joined( new ListOf<>(JoinedTest.LITERAL_ONE), new ListOf<>(JoinedTest.LITERAL_TWO) ); joined.remove(JoinedTest.LITERAL_TWO); new Assertion<>( "Must be able to remove element specified", joined, new IsEqual<>( new ListOf<>( JoinedTest.LITERAL_ONE ) ) ).affirm(); } @Test public void containsAll() { new Assertion<>( "Must contain all elements", new Joined( new ListOf<>(JoinedTest.LITERAL_ONE, JoinedTest.LITERAL_THREE), new ListOf<>(JoinedTest.LITERAL_TWO, JoinedTest.LITERAL_FOUR) ).containsAll( new ListOf<>( JoinedTest.LITERAL_ONE, JoinedTest.LITERAL_TWO ) ), new IsTrue() ).affirm(); } @Test public void addAll() { final List joined = new Joined( new ListOf<>(JoinedTest.LITERAL_ONE), new ListOf<>(JoinedTest.LITERAL_TWO) ); joined.addAll( new ListOf<>( JoinedTest.LITERAL_THREE, JoinedTest.LITERAL_FOUR ) ); new Assertion<>( "Must be able to addAll elements specified", joined, new IsEqual<>( new ListOf<>( JoinedTest.LITERAL_ONE, JoinedTest.LITERAL_TWO, JoinedTest.LITERAL_THREE, JoinedTest.LITERAL_FOUR ) ) ).affirm(); } @Test public void addAllInFront() { final List joined = new Joined( new ListOf<>(JoinedTest.LITERAL_ONE), new ListOf<>(JoinedTest.LITERAL_TWO) ); joined.addAll( 0, new ListOf<>( JoinedTest.LITERAL_THREE, JoinedTest.LITERAL_FOUR ) ); new Assertion<>( "Must be able to addAll elements in front", joined, new IsEqual<>( new ListOf<>( JoinedTest.LITERAL_THREE, JoinedTest.LITERAL_FOUR, JoinedTest.LITERAL_ONE, JoinedTest.LITERAL_TWO ) ) ).affirm(); } @Test public void removeAll() { final List joined = new Joined( new ListOf<>( JoinedTest.LITERAL_ONE, JoinedTest.LITERAL_TWO ), new ListOf<>(JoinedTest.LITERAL_THREE) ); joined.removeAll( new ListOf<>( JoinedTest.LITERAL_TWO, JoinedTest.LITERAL_THREE ) ); new Assertion<>( "Must be able to removeAll elements specified", joined, new IsEqual<>( new ListOf<>( JoinedTest.LITERAL_ONE ) ) ).affirm(); } @Test public void retainAll() { final List joined = new Joined( new ListOf<>(JoinedTest.LITERAL_ONE), new ListOf<>( JoinedTest.LITERAL_TWO, JoinedTest.LITERAL_THREE ) ); joined.retainAll( new ListOf<>( JoinedTest.LITERAL_TWO, JoinedTest.LITERAL_THREE ) ); new Assertion<>( "Must be able to retain all", joined, new IsEqual<>( new ListOf<>( JoinedTest.LITERAL_TWO, JoinedTest.LITERAL_THREE ) ) ).affirm(); } @Test public void clear() { final List joined = new Joined( new ListOf<>( JoinedTest.LITERAL_TWO, JoinedTest.LITERAL_THREE ), new ListOf<>( JoinedTest.LITERAL_ONE ) ); joined.clear(); new Assertion<>( "Must be able to clear", joined.size(), new IsEqual<>(0) ).affirm(); } @Test public void get() { new Assertion<>( "Must get element", new Joined( new ListOf<>( JoinedTest.LITERAL_TWO, JoinedTest.LITERAL_THREE ), new ListOf<>( JoinedTest.LITERAL_ONE ) ).get(1), new IsEqual<>(JoinedTest.LITERAL_THREE) ).affirm(); } @Test public void set() { final List joined = new Joined( new ListOf<>(JoinedTest.LITERAL_ONE), new ListOf<>(JoinedTest.LITERAL_TWO) ); joined.set(0, JoinedTest.LITERAL_THREE); new Assertion<>( "Must be able to set element by specified index", joined.get(0), new IsEqual<>(JoinedTest.LITERAL_THREE) ).affirm(); } @Test public void addByIndex() { final List joined = new Joined( new ListOf<>(JoinedTest.LITERAL_ONE), new ListOf<>(JoinedTest.LITERAL_TWO) ); joined.add(0, JoinedTest.LITERAL_THREE); new Assertion<>( "Must be able to add element by specified index", joined.get(0), new IsEqual<>(JoinedTest.LITERAL_THREE) ).affirm(); } @Test public void removeByIndex() { final List joined = new Joined( new ListOf<>(JoinedTest.LITERAL_ONE), new ListOf<>(JoinedTest.LITERAL_TWO) ); joined.remove(0); new Assertion<>( "Must be able to remove element by specified index", joined.get(0), new IsEqual<>(JoinedTest.LITERAL_TWO) ).affirm(); } @Test public void removeByElement() { final List joined = new Joined( new ListOf<>(JoinedTest.LITERAL_ONE), new ListOf<>(JoinedTest.LITERAL_TWO) ); joined.remove(JoinedTest.LITERAL_ONE); new Assertion<>( "Must be able to remove element by specified element", joined.get(0), new IsEqual<>(JoinedTest.LITERAL_TWO) ).affirm(); } @Test(expected = IndexOutOfBoundsException.class) public void listIteratorSecond() { new Joined().listIterator(66); } @Test public void subList() { new Assertion<>( "Must be able to to get sub list", new Joined( new ListOf<>(JoinedTest.LITERAL_ONE), new ListOf<>(JoinedTest.LITERAL_TWO, JoinedTest.LITERAL_THREE) ).subList(1, 3), new IsEqual<>( new ListOf<>( JoinedTest.LITERAL_TWO, JoinedTest.LITERAL_THREE ) ) ).affirm(); } @Test public void itemAndList() { new Assertion<>( "Must be able to join element with a list", new Joined<>( JoinedTest.LITERAL_ONE, new ListOf<>(JoinedTest.LITERAL_TWO, JoinedTest.LITERAL_THREE) ), new IsEqual<>( new ListOf<>( JoinedTest.LITERAL_ONE, JoinedTest.LITERAL_TWO, JoinedTest.LITERAL_THREE ) ) ).affirm(); } @Test public void infersCorrectly() { new Assertion<>( "Must be able to infer type of elements", new Joined<>( Integer.valueOf(1), new ListOf<>( Double.valueOf(2), Double.valueOf(3) ) ), new IsIterableContainingInOrder<>( new ListOf>( new IsInstanceOf(Integer.class), new IsInstanceOf(Double.class), new IsInstanceOf(Double.class) ) ) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/list/ListEnvelopeTest.java000066400000000000000000000145761400054650300251130ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.list; import java.util.List; import java.util.ListIterator; import org.hamcrest.MatcherAssert; import org.hamcrest.Matchers; import org.hamcrest.collection.IsEmptyCollection; import org.hamcrest.core.IsEqual; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.HasValues; /** * Test case for {@link ListEnvelope}. * * @since 0.32 * @checkstyle JavadocMethodCheck (500 lines) * @checkstyle JavadocTypeCheck (500 lines) * @checkstyle MagicNumberCheck (500 lines) * @checkstyle ClassDataAbstractionCouplingCheck (500 lines) */ @SuppressWarnings({"PMD.TooManyMethods", "PMD.AvoidDuplicateLiterals"}) final class ListEnvelopeTest { @Test void returnsListIteratorWithSupportedSet() { final ListEnvelope list = new StringList("one", "two"); final ListIterator iterator = list.listIterator(1); iterator.next(); iterator.set("zero"); iterator.previous(); MatcherAssert.assertThat( "iterator is not equal to expected", () -> iterator, Matchers.contains( "zero" ) ); } @Test void removeIsDelegated() { final ListEnvelope list = new StringList("one"); list.remove(0); new Assertion<>( "must be empty after removal of 0th element", list, new IsEmptyCollection<>() ).affirm(); } @Test void indexOfIsDelegated() { final ListEnvelope list = new StringList("one"); new Assertion<>( "must return correct index of element", list.indexOf("one"), new IsEqual<>(0) ).affirm(); } @Test void addAllIsDelegated() { final ListEnvelope list = new StringList("one"); list.addAll(0, new StringList("two")); new Assertion<>( "element must be added at 0th position", list, new IsEqual<>(new ListOf<>("two", "one")) ).affirm(); } @Test void setIsDelegatedToTheOriginal() { final ListEnvelope list = new StringList("one"); list.set(0, "zero"); new Assertion<>( "value must be changed", list, new HasValues<>("zero") ).affirm(); } @Test void addIsDelegated() { final ListEnvelope list = new StringList("one"); list.add("two"); new Assertion<>( "value must be added", list, new HasValues<>("one", "two") ).affirm(); } void returnsSubListWithRemove() { final ListEnvelope list = new StringList("one"); list.subList(0, 1).remove(0); new Assertion<>( "must be empty after removal of 0th element via subList", list, new IsEmptyCollection<>() ).affirm(); } @Test void returnsSubListWithSupportedSet() { final List list = new StringList("one"); list.subList(0, 1).set(0, "zero"); new Assertion<>( "ListEnvelope().subList(...).set() must change the original list", list, new HasValues<>( "zero" ) ).affirm(); } @Test void addsAtGivenIndex() { final ListEnvelope list = new StringList("one"); list.add(0, "two"); new Assertion<>( "must add value at given index", list, new HasValues<>("two") ).affirm(); } @Test void getsAtGivenIndex() { final ListEnvelope list = new StringList("one"); new Assertion<>( "must get 0th value", list.get(0), new IsEqual<>("one") ).affirm(); } @Test void getsLastIndexOfValue() { final ListEnvelope list = new StringList("one"); list.add(1, "one"); new Assertion<>( "must return correct last index of element", list.lastIndexOf("one"), new IsEqual<>(1) ).affirm(); } @Test void mustReturnPreviousIndex() { new Assertion<>( "List iterator must return previous index", new StringList("1").listIterator().previousIndex(), new IsEqual<>(-1) ).affirm(); } @Test void mustReturnPreviousElement() { new Assertion<>( "List iterator must return previous element", new StringList("3", "7").listIterator(1).previous(), new IsEqual<>("3") ).affirm(); } @Test void mustReturnNextIndex() { new Assertion<>( "List iterator must return next index", new StringList("1").listIterator().nextIndex(), new IsEqual<>(0) ).affirm(); } @Test void mustReturnNextElement() { new Assertion<>( "List iterator must return next item", new StringList("5", "11", "13").listIterator(1).next(), new IsEqual<>("11") ).affirm(); } private static final class StringList extends ListEnvelope { StringList(final String... elements) { super(new ListOf<>(elements)); } } } cactoos-0.49/src/test/java/org/cactoos/list/ListIteratorEnvelopeTest.java000066400000000000000000000057251400054650300266210ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.list; import org.hamcrest.core.IsEqual; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; /** * Test cases for {@link ListIteratorEnvelope}. * * @since 0.35 * @checkstyle JavadocMethodCheck (500 lines) * @checkstyle JavadocTypeCheck (500 lines) * @checkstyle MagicNumberCheck (500 lines) */ final class ListIteratorEnvelopeTest { @Test void mustReturnPreviousIndex() { new Assertion<>( "List Iterator must return previous index", new StringListIterator( "1" ).previousIndex(), new IsEqual<>(-1) ).affirm(); } @Test void mustReturnPreviousElement() { new Assertion<>( "List Iterator must return previous element", new StringListIterator( 1, "3", "7" ).previous(), new IsEqual<>("3") ).affirm(); } @Test void mustReturnNextIndex() { new Assertion<>( "List iterator must return next index", new StringListIterator( "1" ).nextIndex(), new IsEqual<>(0) ).affirm(); } @Test void mustReturnNextElement() { new Assertion<>( "List iterator must return next item", new StringListIterator( 1, "5", "11", "13" ).next(), new IsEqual<>("11") ).affirm(); } private static final class StringListIterator extends ListIteratorEnvelope { StringListIterator(final int index, final String... elements) { super(new ListOf<>(elements).listIterator(index)); } StringListIterator(final String... elements) { super(new ListOf<>(elements).listIterator()); } } } cactoos-0.49/src/test/java/org/cactoos/list/ListIteratorNoNullsTest.java000066400000000000000000000126061400054650300264320ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.list; import java.util.ArrayList; import java.util.List; import java.util.ListIterator; import java.util.NoSuchElementException; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.ScalarHasValue; import org.llorllale.cactoos.matchers.Throws; /** * Test cases for {@link ListIteratorNoNulls}. * * @since 0.35 * @checkstyle JavadocMethodCheck (500 lines) * @checkstyle MagicNumberCheck (500 lines) */ final class ListIteratorNoNullsTest { @Test void mustThrowsErrorIfListIteratorNextValueIsNull() { new Assertion<>( "must throw error next item is null", () -> { new ListIteratorNoNulls<>( new ListOf<>(null, 2, 3).listIterator() ).next(); return 0; }, new Throws<>( "Next item is NULL", IllegalStateException.class ) ).affirm(); } @Test void mustThrowsErrorIfListIteratorPreviousValueIsNull() { new Assertion<>( "must throw error if previous value is null", () -> { new ListIteratorNoNulls<>( new ListOf<>( null, 2, 3 ).listIterator(1) ).previous(); return 0; }, new Throws<>( "Previous item is NULL", IllegalStateException.class ) ).affirm(); } @Test void mustAddToListIterator() { new Assertion<>( "must add to list iterator", () -> { final List list = new ArrayList<>(2); list.add(1); list.add(2); final ListIterator iterator = new ListIteratorNoNulls<>( list.listIterator() ); iterator.next(); iterator.add(4); return iterator.previous(); }, new ScalarHasValue<>(4) ).affirm(); } @Test void mustRemoveFromListIterator() { new Assertion<>( "must remove element from list iterator", () -> { final List list = new ArrayList<>(2); list.add(1); list.add(2); final ListIterator iterator = new ListIteratorNoNulls<>( list.listIterator() ); iterator.next(); iterator.remove(); return iterator.previous(); }, new Throws<>( NoSuchElementException.class ) ).affirm(); } @Test void mustSetValueListIterator() { new Assertion<>( "must set element into list iterator", () -> { final List list = new ArrayList<>(2); list.add(1); list.add(2); final ListIterator iterator = new ListIteratorNoNulls<>( list.listIterator() ); iterator.next(); iterator.set(4); return iterator.previous(); }, new ScalarHasValue<>(4) ).affirm(); } @Test void mustThrowsErrorIfAddANullItem() { new Assertion<>( "must throw error if add a null item", () -> { new ListIteratorNoNulls<>( new ListOf<>(1, 2, 3).listIterator() ).add(null); return 0; }, new Throws<>( "Item can't be NULL in #add(T)", IllegalArgumentException.class ) ).affirm(); } @Test void mustThrowsErrorIfSetANullItem() { new Assertion<>( "must throw error if set a null item", () -> { new ListIteratorNoNulls<>( new ListOf<>(1, 2, 3).listIterator() ).set(null); return 0; }, new Throws<>( "Item can't be NULL in #set(T)", IllegalArgumentException.class ) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/list/ListOfTest.java000066400000000000000000000116711400054650300236730ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.list; import java.util.Collections; import java.util.List; import org.cactoos.iterable.IterableOf; import org.cactoos.iterable.Mapped; import org.hamcrest.MatcherAssert; import org.hamcrest.core.IsEqual; import org.junit.Test; import org.llorllale.cactoos.matchers.HasSize; /** * Test case for {@link ListOf}. * * @since 0.1 * @checkstyle ClassDataAbstractionCouplingCheck (500 lines) * @checkstyle JavadocMethodCheck (500 lines) * @checkstyle MagicNumberCheck (500 lines) */ @SuppressWarnings( { "PMD.TooManyMethods", "PMD.AvoidDuplicateLiterals" } ) public final class ListOfTest { @Test public void behavesAsCollection() throws Exception { MatcherAssert.assertThat( "Can't behave as a list", new ListOf<>(1, 2), new BehavesAsList<>(2) ); } @Test public void elementAtIndexTest() throws Exception { final int num = 345; MatcherAssert.assertThat( "Can't convert an iterable to a list", new ListOf<>(-1, num, 0, 1).get(1), new IsEqual<>(num) ); } @Test public void sizeTest() throws Exception { final int size = 42; MatcherAssert.assertThat( "Can't build a list with a certain size", new ListOf<>( Collections.nCopies(size, 0) ), new HasSize(size) ); } @Test public void emptyTest() throws Exception { MatcherAssert.assertThat( "Can't convert an empty iterable to an empty list", new ListOf<>( new IterableOf<>() ), new HasSize(0) ); } @Test(expected = IndexOutOfBoundsException.class) public void lowBoundTest() throws Exception { // @checkstyle MagicNumber (1 line) new ListOf<>(Collections.nCopies(10, 0)).get(-1); } @Test(expected = IndexOutOfBoundsException.class) public void highBoundTest() throws Exception { // @checkstyle MagicNumber (1 line) new ListOf<>(Collections.nCopies(10, 0)).get(11); } @Test public void makesListFromMappedIterable() throws Exception { final List list = new ListOf<>( new Mapped( i -> i + 1, new IterableOf<>(1, -1, 0, 1) ) ); MatcherAssert.assertThat( "Can't turn a mapped iterable into a list", list, new HasSize(4) ); MatcherAssert.assertThat( "Can't turn a mapped iterable into a list, again", list, new HasSize(4) ); } @Test public void equalsComparesContentBothListEnvelopes() { MatcherAssert.assertThat( "Can't compare using equals.", new ListOf<>(1, 2), new IsEqual<>(new ListOf<>(1, 2)) ); } @Test public void equalsComparesContentListEnvelopeWithNormalList() { MatcherAssert.assertThat( "Can't compare using equals.", new ListOf<>(1, 2), new IsEqual<>(new ListOf<>(1, 2)) ); } @Test public void equalsComparesEmptyLists() { MatcherAssert.assertThat( "Can't compare using equals.", new ListOf<>(), new IsEqual<>(new ListOf<>()) ); } @Test public void toStringUsesListContent() { MatcherAssert.assertThat( "Can't print content using toString.", new ListOf<>(1, 2).toString(), new IsEqual<>("[1, 2]") ); } @Test public void hashCodesListContent() { MatcherAssert.assertThat( "Can't create hashcode.", new ListOf<>(1, 2).hashCode(), new IsEqual<>(new ListOf<>(1, 2).hashCode()) ); } } cactoos-0.49/src/test/java/org/cactoos/list/NoNullsTest.java000066400000000000000000000110571400054650300240630ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.list; import java.util.ArrayList; import java.util.List; import java.util.ListIterator; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.Throws; /** * Test cases for {@link NoNulls}. * @since 0.35 * @checkstyle JavadocMethodCheck (500 lines) * @checkstyle MagicNumberCheck (500 lines) */ final class NoNullsTest { @Test void getThrowsErrorIfNull() { new Assertion<>( "must throw error if contains null", () -> new NoNulls<>( new ListOf<>(1, null, 3) ).get(1), new Throws<>( "Item #1 of [1, null, 3] is NULL", IllegalStateException.class ) ).affirm(); } @Test void setThrowsErrorIfArgumentNull() { new Assertion<>( "must throw error if set null", () -> new NoNulls<>( new ListOf<>(1, null, 3) ).set(2, null), new Throws<>( "Item can't be NULL in #set(2,T)", IllegalArgumentException.class ) ).affirm(); } @Test void setThrowsErrorIfPreviousValueNull() { final ArrayList list = new ArrayList<>(1); list.add(null); new Assertion<>( "must throw error if previous value is null", () -> new NoNulls<>(list).set(0, 2), new Throws<>( "Result of #set(0,T) is NULL", IllegalStateException.class ) ).affirm(); } @Test void addThrowsErrorIfArgumentNull() { new Assertion<>( "must throw error if add null", () -> { new NoNulls<>(new ArrayList<>(1)).add(0, null); return 0; }, new Throws<>( "Item can't be NULL in #add(0,T)", IllegalArgumentException.class ) ).affirm(); } @Test void removeThrowsErrorIfValueNull() { final ArrayList list = new ArrayList<>(1); list.add(null); new Assertion<>( "must throw error if removed value is null", () -> new NoNulls<>(list).remove(0), new Throws<>( "Result of #remove(0) is NULL", IllegalStateException.class ) ).affirm(); } @Test void getThrowsErrorIfListIteratorNextValueIsNullValue() { new Assertion<>( "must throw error if removed value in iterator is null", () -> new NoNulls<>( new ListOf<>(null, 2, 3) ).listIterator().next(), new Throws<>( "Next item is NULL", IllegalStateException.class ) ).affirm(); } @Test void getThrowsErrorIfListIteratorPreviousValueIsNullValue() { final List list = new ArrayList<>(2); list.add(1); list.add(2); final ListIterator listiterator = new NoNulls<>( list ).listIterator(); listiterator.next(); list.set(0, null); new Assertion<>( "must throw error if previous value in iterator is null", () -> listiterator.previous(), new Throws<>( "Previous item is NULL", IllegalStateException.class ) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/list/SyncedTest.java000066400000000000000000000043411400054650300237140ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.list; import java.util.Collections; import org.hamcrest.MatcherAssert; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.RunsInThreads; /** * Test case for {@link Synced}. * @since 0.24 * @checkstyle JavadocMethodCheck (500 lines) */ @SuppressWarnings("PMD.TooManyMethods") final class SyncedTest { @Test void behavesAsCollection() throws Exception { MatcherAssert.assertThat( "Can't behave as a list", new Synced<>(new ListOf<>(1, 0, -1, -1, 2)), new BehavesAsList<>(0) ); } @Test void worksInThreads() { MatcherAssert.assertThat( list -> !list.iterator().hasNext(), new RunsInThreads<>(new Synced<>(Collections.emptyList())) ); MatcherAssert.assertThat( list -> { MatcherAssert.assertThat( list, new BehavesAsList<>(0) ); return true; }, new RunsInThreads<>(new Synced<>(new ListOf<>(1, 0, -1, -1, 2))) ); } } cactoos-0.49/src/test/java/org/cactoos/list/package-info.java000066400000000000000000000023011400054650300241450ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ /** * Lists. * * @since 0.14 */ package org.cactoos.list; cactoos-0.49/src/test/java/org/cactoos/map/000077500000000000000000000000001400054650300205645ustar00rootroot00000000000000cactoos-0.49/src/test/java/org/cactoos/map/BehavesAsMap.java000066400000000000000000000054321400054650300237320ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.map; import java.util.Map; import org.hamcrest.Description; import org.hamcrest.MatcherAssert; import org.hamcrest.TypeSafeMatcher; import org.hamcrest.collection.IsMapContaining; import org.hamcrest.core.IsCollectionContaining; import org.hamcrest.core.IsEqual; /** * Matcher for collection. * @param Type of key * @param Type of value * @since 0.24 * @checkstyle JavadocMethodCheck (500 lines) */ public final class BehavesAsMap extends TypeSafeMatcher> { /** * Sample key. */ private final K key; /** * Sample value. */ private final V value; /** * Ctor. * @param akey Sample key * @param val Sample value */ public BehavesAsMap(final K akey, final V val) { super(); this.key = akey; this.value = val; } @Override public boolean matchesSafely(final Map map) { MatcherAssert.assertThat( "Doesn't contain the key", map, new IsMapContaining<>( new IsEqual<>(this.key), new IsEqual<>(this.value) ) ); MatcherAssert.assertThat( "Doesn't contain the key in #keySet()", map.keySet(), new IsCollectionContaining<>(new IsEqual<>(this.key)) ); MatcherAssert.assertThat( "Doesn't contain the value in #values()", map.values(), new IsCollectionContaining<>(new IsEqual<>(this.value)) ); return true; } @Override public void describeTo(final Description desc) { desc.appendText("not a valid map"); } } cactoos-0.49/src/test/java/org/cactoos/map/ClearDeletesAllValues.java000066400000000000000000000036261400054650300256030ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.map; import java.util.Map; import org.hamcrest.Description; import org.hamcrest.MatcherAssert; import org.hamcrest.TypeSafeMatcher; import org.hamcrest.core.IsEqual; /** * Check a clear method. * @param Type of key * @param Type of value * @since 0.30 * @checkstyle JavadocMethodCheck (500 lines) */ public final class ClearDeletesAllValues extends TypeSafeMatcher> { @Override public boolean matchesSafely(final Map map) { map.clear(); MatcherAssert.assertThat( "Can't be cleared", map.isEmpty(), new IsEqual<>(true) ); return true; } @Override public void describeTo(final Description desc) { desc.appendText("not a valid map"); } } cactoos-0.49/src/test/java/org/cactoos/map/GroupedTest.java000066400000000000000000000066501400054650300237030ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.map; import java.util.HashSet; import org.cactoos.iterable.IterableOf; import org.cactoos.list.ListOf; import org.hamcrest.collection.IsMapContaining; import org.hamcrest.core.IsEqual; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; /** * Test case for {@link Grouped}. * * @since 0.30 * @checkstyle JavadocMethodCheck (500 lines) * @checkstyle ClassDataAbstractionCouplingCheck (500 lines) */ final class GroupedTest { @Test void groupedByNumber() throws Exception { new Assertion<>( "Can't behave as a map", new Grouped<>( // @checkstyle MagicNumberCheck (1 line) new IterableOf<>(1, 1, 1, 4, 5, 6, 7, 8, 9), number -> number, Object::toString ), new BehavesAsMap<>(1, new ListOf<>("1", "1", "1")) ).affirm(); } @Test void emptyIterable() throws Exception { new Assertion<>( "Can't build grouped by empty iterable", new Grouped<>( new IterableOf(), number -> number, Object::toString ).entrySet(), new IsEqual<>(new HashSet<>()) ).affirm(); } @Test void groupedByOneHasEntries() throws Exception { new Assertion<>( "Can't group int values", new Grouped<>( // @checkstyle MagicNumberCheck (1 line) new IterableOf<>(1, 1, 1, 4, 5, 6, 7, 8, 9), number -> number, Object::toString ), new IsMapContaining<>( new IsEqual<>(1), new IsEqual<>(new ListOf<>("1", "1", "1")) ) ).affirm(); } @Test void groupedBySuperType() throws Exception { new Assertion<>( "Must group Number values", new Grouped<>( // @checkstyle MagicNumberCheck (1 line) new IterableOf(1, 1f, 1L, 4f, 5, 6f, 7, 8f, 9), Number::intValue, Object::toString ), new IsMapContaining<>( new IsEqual<>(1), new IsEqual<>(new ListOf<>("1", "1.0", "1")) ) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/map/MapEntryTest.java000066400000000000000000000057001400054650300240300ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.map; import org.hamcrest.MatcherAssert; import org.hamcrest.core.IsEqual; import org.junit.Test; /** * Test case for {@link MapEntry}. * * @since 0.9 * @checkstyle JavadocMethodCheck (500 lines) */ public final class MapEntryTest { @Test public void getKey() { final String key = "hello"; final String value = "world"; MatcherAssert.assertThat( "Can't get key in the map entry", new MapEntry<>(key, value).getKey(), new IsEqual<>(key) ); } @Test public void getValue() { final String key = "foo"; final String value = "bar"; MatcherAssert.assertThat( "Can't get value in the map entry", new MapEntry<>(key, value).getValue(), new IsEqual<>(value) ); } @Test(expected = UnsupportedOperationException.class) public void cantSetValue() { new MapEntry<>("one", "two").setValue("three"); } @Test public void equalsTo() { final String key = "eo"; final String value = "book"; MatcherAssert.assertThat( "MapEntries are not equals", new MapEntry<>(key, value).equals(new MapEntry<>(key, value)), new IsEqual<>(true) ); } @Test public void compareHash() { MatcherAssert.assertThat( "the hash code are not equals", new MapEntry<>("elegant", "objects").hashCode(), // @checkstyle MagicNumber (1 line) new IsEqual<>(32_739_498) ); } @Test public void toStringMethod() { MatcherAssert.assertThat( "ToString method returns unexpected value", new MapEntry<>("somekey", "somevalue").toString(), new IsEqual<>("somekey=somevalue") ); } } cactoos-0.49/src/test/java/org/cactoos/map/MapEnvelopeTest.java000066400000000000000000000235031400054650300245050ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.map; import java.util.HashMap; import java.util.Map; import org.hamcrest.MatcherAssert; import org.hamcrest.collection.IsMapWithSize; import org.hamcrest.core.IsEqual; import org.hamcrest.core.IsNot; import org.junit.Test; import org.llorllale.cactoos.matchers.Assertion; /** * Test case for {@link MapEnvelope}. * * @since 0.4 * @checkstyle JavadocMethodCheck (500 lines) * @checkstyle ClassDataAbstractionCouplingCheck (500 lines) * @checkstyle DiamondOperatorCheck (500 lines) */ @SuppressWarnings("PMD.TooManyMethods") public final class MapEnvelopeTest { @Test public void mapIsEmptyTrue() { MatcherAssert.assertThat( "#isEmpty() returns false for empty map", new NoNulls<>( new MapOf() ).isEmpty(), new IsEqual<>(true) ); } @Test public void mapIsEmptyFalse() { MatcherAssert.assertThat( "#isEmpty() returns true for not empty map", new NoNulls<>( new MapOf( new MapEntry<>(1, 0) ) ).isEmpty(), new IsEqual<>(false) ); } @Test public void mapContainsKeyTrue() { MatcherAssert.assertThat( "contains key returns false with exist key", new NoNulls<>( new MapOf( new MapEntry<>(1, 0) ) ).containsKey(1), new IsEqual<>(true) ); } @Test public void mapContainsKeyFalse() { MatcherAssert.assertThat( "contains key returns true with absent key", new NoNulls<>( new MapOf( new MapEntry<>(1, 0) ) ).containsKey(0), new IsEqual<>(false) ); } @Test public void mapContainsValueTrue() { MatcherAssert.assertThat( "contains value returns false with exist value", new NoNulls<>( new MapOf( new MapEntry<>(1, 0) ) ).containsValue(0), new IsEqual<>(true) ); } @Test public void mapContainsValueFalse() { MatcherAssert.assertThat( "contains value returns true with absent value", new NoNulls<>( new MapOf( new MapEntry<>(1, 0) ) ).containsValue(1), new IsEqual<>(false) ); } @Test public void mapEqualsToItself() { final MapOf map = new MapOf(new MapEntry<>("key", "value")); MatcherAssert.assertThat( "Map doesn't equal to itself", map, new IsEqual<>(map) ); } @Test public void mapNotEqualsToAnotherClass() { final MapOf map = new MapOf(new MapEntry<>("key1", "value1")); MatcherAssert.assertThat( "Map equals to an instance of another type", map, new IsNot<>( new IsEqual<>("Totally different type") ) ); } @Test public void mapEqualsToMapWithSameEntries() { final String key = "key2"; final String value = "value2"; final MapEntry input = new MapEntry<>(key, value); final MapEntry expected = new MapEntry<>(key, value); MatcherAssert.assertThat( "Map doesn't equal to another map with same entries", new MapOf(input), new IsEqual<>(new MapOf(expected)) ); } @Test public void equalsDoesNotFailOnNulls() { final MapEntry first = new MapEntry<>("key3", "value3"); final MapEntry second = new MapEntry<>("key4", null); MatcherAssert.assertThat( "Map must allow null values", new MapOf(first, second), new IsEqual<>(new MapOf(first, second)) ); } @Test public void mapNotEqualsToOtherWithDifferentKeys() { final String value = "value5"; MatcherAssert.assertThat( "Map equals to another map with different keys", new MapOf(new MapEntry<>("key5", value)), new IsNot<>( new IsEqual<>( new MapOf( new MapEntry<>("key6", value) ) ) ) ); } @Test public void mapNotEqualsToOtherWithDifferentValues() { final String key = "key7"; MatcherAssert.assertThat( "Map equals to another map with different values", new MapOf(new MapEntry<>(key, "value7")), new IsNot<>( new IsEqual<>( new MapOf( new MapEntry<>(key, "value8") ) ) ) ); } @Test public void hashCodeDependsOnItems() { final String key = "key9"; final String value = "value9"; final MapEntry input = new MapEntry<>(key, value); final MapEntry expected = new MapEntry<>(key, value); MatcherAssert.assertThat( "hashCode returns different results for same entries", new MapOf(input).hashCode(), new IsEqual<>(new MapOf(expected).hashCode()) ); } @Test public void hashCodeDoesNotFailOnNulls() { final MapEntry first = new MapEntry<>("key10", "value10"); final MapEntry second = new MapEntry<>("key11", null); new MapOf(first, second).hashCode(); } @Test @SuppressWarnings("unchecked") public void emptyMapEnvelopeShouldBeEqualToEmptyDerivedMap() { final MapEnvelope base = new MapOf<>(); final DerivedMapEnvelope derived = new DerivedMapEnvelope<>(new HashMap<>()); new Assertion<>( "EmpBase and derived MapEnvelope which are empty should be equal.", base, new IsEqual<>(derived) ).affirm(); } @Test @SuppressWarnings("unchecked") public void mapEnvelopeShouldCompareDerivedClasses() { final int key = 1; final String value = "one"; final MapEntry entry = new MapEntry<>(key, value); final MapEnvelope base = new MapOf<>(entry); final Map hashmap = new HashMap<>(); hashmap.put(key, value); final DerivedMapEnvelope derived = new DerivedMapEnvelope<>(hashmap); new Assertion<>( "Base and derived MapEnvelope of same content should be equal.", base, new IsEqual<>(derived) ).affirm(); } @Test public void putIsDelegated() { final Map map = new DerivedMapEnvelope<>( new HashMap<>() ); map.put(0, 1); new Assertion<>( "must contain element after #put()", map, new IsEqual<>( new MapOf( new MapEntry<>(0, 1) ) ) ).affirm(); } @Test public void clearIsDelegated() { final Map map = new DerivedMapEnvelope<>( new MapOf( new MapEntry<>(0, 1) ) ); map.clear(); new Assertion<>( "must be empty after #clear()", map, new IsMapWithSize<>(new IsEqual<>(0)) ).affirm(); } @Test public void removeIsDelegated() { final Map map = new DerivedMapEnvelope<>( new MapOf( new MapEntry<>(0, 1) ) ); map.remove(0); new Assertion<>( "must be empty after #remove()", map, new IsMapWithSize<>(new IsEqual<>(0)) ).affirm(); } /** * Class derived from MapEnvelope to use in some tests. * @param - key type * @param - value type * @since 0.4 */ private static class DerivedMapEnvelope extends MapEnvelope { DerivedMapEnvelope(final Map content) { super(content); } } } cactoos-0.49/src/test/java/org/cactoos/map/MapOfTest.java000066400000000000000000000146761400054650300233070ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.map; import java.io.IOException; import java.util.Map; import org.cactoos.Scalar; import org.cactoos.func.FuncOf; import org.cactoos.iterable.IterableOf; import org.cactoos.scalar.Constant; import org.hamcrest.MatcherAssert; import org.hamcrest.collection.IsMapContaining; import org.hamcrest.core.AllOf; import org.hamcrest.core.IsAnything; import org.hamcrest.core.IsEqual; import org.hamcrest.core.StringStartsWith; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; /** * Test case for {@link MapOf}. * * @since 0.4 * @checkstyle JavadocMethodCheck (500 lines) * @checkstyle ClassDataAbstractionCouplingCheck (500 lines) */ final class MapOfTest { @Test void behavesAsMap() { MatcherAssert.assertThat( "Can't behave as a map", new NoNulls<>( new MapOf( new MapEntry<>(0, -1), new MapEntry<>(1, 1) ) ), new BehavesAsMap<>(1, 1) ); } @Test void convertsIterableToMap() { MatcherAssert.assertThat( "Can't convert iterable to map", new MapOf( new MapEntry<>(0, "hello, "), new MapEntry<>(1, "world!") ), new IsMapContaining<>( new IsEqual<>(0), new StringStartsWith("hello") ) ); } @Test void createsMapWithFunctions() { MatcherAssert.assertThat( "Can't create a map with functions as values", new MapOf>( new MapEntry<>(0, () -> true), new MapEntry<>( 1, () -> { throw new IOException("oops"); } ) ), new IsMapContaining<>(new IsEqual<>(0), new IsAnything<>()) ); } @Test void integersToString() { MatcherAssert.assertThat( "Can't convert map of integers to string", new MapOf( new MapEntry<>(-1, 0), new MapEntry<>(1, 2) ).toString(), new IsEqual<>("{-1=0, 1=2}") ); } @Test void mapsToString() { MatcherAssert.assertThat( "Can't convert map op maps to string", new MapOf>( new MapEntry>( -1, new MapOf( new MapEntry("first", "second"), new MapEntry("4", "7") ) ), new MapEntry>( 1, new MapOf( new MapEntry("green", "red"), new MapEntry("2.7", "3.1") ) ) ).toString(), new IsEqual<>("{-1={4=7, first=second}, 1={green=red, 2.7=3.1}}") ); } @Test void emptyToString() { MatcherAssert.assertThat( "Can't convert empty map to string", new MapOf>().toString(), new IsEqual<>("{}") ); } @Test @SuppressWarnings("unchecked") void createsMapFromMapAndMapEntries() { MatcherAssert.assertThat( "Can't create a map from map and map entries", new MapOf( new MapOf( new MapEntry(0, 0) ), new MapEntry(1, 1) ), new AllOf<>( new IterableOf<>( new IsMapContaining<>(new IsEqual<>(0), new IsEqual<>(0)), new IsMapContaining<>(new IsEqual<>(1), new IsEqual<>(1)) ) ) ); } @Test void createsMapFromFunctionsAndIterable() { new Assertion<>( "Must create a map from functions and iterable.", new MapOf( new FuncOf(new Constant<>(0)), new FuncOf(new Constant<>(0)), new IterableOf(0) ), new IsMapContaining<>(new IsEqual<>(0), new IsEqual<>(0)) ).affirm(); } @Test @SuppressWarnings("unchecked") void createsMapFromMapFunctionsAndIterable() { new Assertion<>( "Can't create a map from map, functions and iterable.", new MapOf( new FuncOf(new Constant<>(0)), new FuncOf(new Constant<>(0)), new MapOf( new MapEntry(1, 1) ), new IterableOf<>(0) ), new AllOf<>( new IterableOf<>( new IsMapContaining<>(new IsEqual<>(0), new IsEqual<>(0)), new IsMapContaining<>(new IsEqual<>(1), new IsEqual<>(1)) ) ) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/map/MergedTest.java000066400000000000000000000100471400054650300234740ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.map; import org.hamcrest.core.IsEqual; import org.junit.Test; import org.llorllale.cactoos.matchers.Assertion; /** * Test case for {@link Merged}. * * @since 1.0 * @checkstyle JavadocMethodCheck (500 lines) */ public final class MergedTest { @Test public void behavesAsMap() { new Assertion<>( "Must behave as a map", new Merged( new MapOf( new MapEntry<>(0, -1), new MapEntry<>(1, 1) ) ), new BehavesAsMap<>(1, 1) ).affirm(); } @Test public void createsMapFromMaps() { new Assertion<>( "Must merge a few maps", new Merged( new MapOf( new MapEntry<>(0, 0) ), new MapOf( new MapEntry<>(1, 1) ) ), new IsEqual<>( new MapOf( new MapEntry<>(0, 0), new MapEntry<>(1, 1) ) ) ).affirm(); } @Test public void overridesValues() { new Assertion<>( "Must override values", new Merged( new MapOf( new MapEntry<>(0, -1) ), new MapOf( new MapEntry<>(0, 1) ) ), new IsEqual<>( new MapOf( new MapEntry<>(0, 1) ) ) ).affirm(); } @Test public void mergesEmptyMaps() { new Assertion<>( "Must merge empty maps", new Merged( new MapOf(), new MapOf() ), new IsEqual<>( new MapOf() ) ).affirm(); } @Test(expected = NullPointerException.class) public void throwsNullPointerForNullMap() { new Merged( new MapOf(), null ).size(); } @Test public void behavesAsMapWithWildCards() { new Assertion<>( "Must behave as a map with common type", new Merged( new MapOf( new MapEntry<>(1, 1) ), new MapOf( new MapEntry<>(2L, 1L) ) ), new IsEqual<>( new MapOf( new MapEntry<>(1, 1), new MapEntry<>(2L, 1L) ) ) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/map/NoNullsTest.java000066400000000000000000000262561400054650300236740ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.map; import java.util.HashMap; import org.cactoos.iterable.IterableOf; import org.hamcrest.MatcherAssert; import org.hamcrest.collection.IsMapContaining; import org.hamcrest.core.AllOf; import org.hamcrest.core.IsEqual; import org.junit.Ignore; import org.junit.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.Throws; /** * Test case for {@link NoNulls}. * * @since 0.30 * @checkstyle JavadocMethodCheck (500 lines) * @checkstyle ClassDataAbstractionCouplingCheck (500 lines) */ @SuppressWarnings( { "PMD.TooManyMethods", "PMD.NonStaticInitializer", "serial" } ) public final class NoNullsTest { @Test public void getSize() { MatcherAssert.assertThat( "Can't calculate size", new NoNulls<>( new MapOf( new MapEntry<>(0, -1), new MapEntry<>(1, 1) ) ).size(), new IsEqual<>(2) ); } @Test public void isEmptyTrue() { MatcherAssert.assertThat( "Can't get is empty true", new NoNulls<>( new MapOf() ).isEmpty(), new IsEqual<>(true) ); } @Test public void isEmptyFalse() { MatcherAssert.assertThat( "Can't get is empty false", new NoNulls<>( new MapOf( new MapEntry<>(0, -1) ) ).isEmpty(), new IsEqual<>(false) ); } @Test public void containsKeyTrue() { MatcherAssert.assertThat( "Can't get #containsKey() true", new NoNulls<>( new MapOf( new MapEntry<>(0, -1) ) ).containsKey(0), new IsEqual<>(true) ); } @Test public void containsKeyFalse() { MatcherAssert.assertThat( "Can't get #containsKey() false", new NoNulls<>( new MapOf( new MapEntry<>(0, -1) ) ).containsKey(-1), new IsEqual<>(false) ); } @Test(expected = IllegalStateException.class) public void containsKeyException() { MatcherAssert.assertThat( "Could no throw an IllegalStateException for null key", new NoNulls<>( new MapOf( new MapEntry<>(0, -1) ) ).containsKey(null), new IsEqual<>(true) ); } @Test public void containsValueFalse() { MatcherAssert.assertThat( "Can't get #containsValue() false", new NoNulls<>( new MapOf( new MapEntry<>(0, -1) ) ).containsValue(0), new IsEqual<>(false) ); } @Test public void containsValueTrue() { MatcherAssert.assertThat( "Can't get #containsValue() true", new NoNulls<>( new MapOf( new MapEntry<>(0, -1) ) ).containsValue(-1), new IsEqual<>(true) ); } @Test(expected = IllegalStateException.class) public void containsValueException() { MatcherAssert.assertThat( "Can't get #containsValue() exception", new NoNulls<>( new MapOf( new MapEntry<>(0, -1) ) ).containsValue(null), new IsEqual<>(true) ); } @Test public void getValue() { MatcherAssert.assertThat( "Can't call #get()", new NoNulls<>( new MapOf( new MapEntry<>(0, -1) ) ).get(0), new IsEqual<>(-1) ); } @Test(expected = IllegalStateException.class) public void getValueByNullKey() { MatcherAssert.assertThat( "Can't call #get() with key null", new NoNulls<>( new MapOf( new MapEntry<>(0, -1) ) ).get(null), new IsEqual<>(-1) ); } @Test(expected = IllegalStateException.class) public void getValueByNullValue() { MatcherAssert.assertThat( "Can't call #get() with null value", new NoNulls<>( new MapOf( new MapEntry<>(0, null) ) ).get(0), new IsEqual<>(-1) ); } @Test public void put() { MatcherAssert.assertThat( "Can't call #put()", new NoNulls( new HashMap() { { put(0, 0); } } ), new PutUpdatesValues(0, 1) ); } @Test(expected = IllegalStateException.class) public void putWithNullKey() { MatcherAssert.assertThat( "Can't call #put() with Null key", new NoNulls( new HashMap() { { put(0, 0); } } ), new PutUpdatesValues(null, 1) ); } @Test(expected = IllegalStateException.class) public void putWithNullValue() { MatcherAssert.assertThat( "Can't call #put() with Null value", new NoNulls( new HashMap() { { put(0, 0); } } ), new PutUpdatesValues(0, null) ); } @Test @Ignore public void putWithNoMapping() { MatcherAssert.assertThat( "Can't call #put() with no mapping", new NoNulls( new HashMap() { { put(0, 0); } } ), new PutUpdatesValues(1, 1) ); } @Test public void remove() { MatcherAssert.assertThat( "Can't call #remove()", new NoNulls( new HashMap() { { put(0, 0); } } ), new RemoveDeletesValues(0, 0) ); } @Test(expected = IllegalStateException.class) public void removeWithNullKey() { MatcherAssert.assertThat( "Can't call #remove() with Null key", new NoNulls( new HashMap() { { put(0, 0); } } ), new RemoveDeletesValues(null, 0) ); } @Test @Ignore public void removeWithNoMapping() { MatcherAssert.assertThat( "Can't call #remove() with no mapping", new NoNulls( new HashMap() { { put(0, 0); } } ), new RemoveDeletesValues(1, 0) ); } @Test public void putAll() { MatcherAssert.assertThat( "Can't call #putAll()", new NoNulls( new HashMap() { { put(0, 0); } } ), new PutAllUpdatesValues(0, 1) ); } @Test public void clear() { MatcherAssert.assertThat( "Can't call #clear()", new NoNulls( new HashMap() { { put(0, 0); put(1, 1); put(2, 2); } } ), new ClearDeletesAllValues() ); } @Test @SuppressWarnings("unchecked") public void entrySet() { MatcherAssert.assertThat( "Can't call #entrySet()", new NoNulls( new HashMap() { { put(1, 1); put(0, 0); } } ), new AllOf<>( new IterableOf<>( new IsMapContaining<>(new IsEqual<>(1), new IsEqual<>(1)), new IsMapContaining<>(new IsEqual<>(0), new IsEqual<>(0)) ) ) ); } @Test public void putThrowsErrorIfValueNull() { new Assertion<>( "Should throws an error if value is null", () -> new NoNulls( new HashMap<>() ).put(1, null), new Throws<>( "Value at #put(1,V) is NULL", IllegalStateException.class ) ).affirm(); } @Test public void putThrowsErrorIfPreviousValueNull() { new Assertion<>( "Should throws an error if previous value is null", () -> new NoNulls<>( new HashMap() { { put(1, null); } } ).put(1, 2), new Throws<>( "Value returned by #put(1,2) is NULL", IllegalStateException.class ) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/map/PutAllUpdatesValues.java000066400000000000000000000045511400054650300253430ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.map; import java.util.Map; import org.hamcrest.Description; import org.hamcrest.MatcherAssert; import org.hamcrest.TypeSafeMatcher; /** * Check a putAll method. * @param Type of key * @param Type of value * @since 0.30 * @checkstyle JavadocMethodCheck (500 lines) */ public final class PutAllUpdatesValues extends TypeSafeMatcher> { /** * Sample key. */ private final K key; /** * Sample value. */ private final V value; /** * Ctor. * @param akey Sample key * @param val Sample value */ public PutAllUpdatesValues(final K akey, final V val) { super(); this.key = akey; this.value = val; } @Override public boolean matchesSafely(final Map map) { map.putAll( new MapOf( new MapEntry<>(this.key, this.value) ) ); MatcherAssert.assertThat( "Can't behave as a map after putAll", map, new BehavesAsMap(this.key, this.value) ); return true; } @Override public void describeTo(final Description desc) { desc.appendText("not a valid map"); } } cactoos-0.49/src/test/java/org/cactoos/map/PutUpdatesValues.java000066400000000000000000000044051400054650300247100ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.map; import java.util.Map; import org.hamcrest.Description; import org.hamcrest.MatcherAssert; import org.hamcrest.TypeSafeMatcher; /** * Check a put method. * @param Type of key * @param Type of value * @since 0.30 * @checkstyle JavadocMethodCheck (500 lines) */ public final class PutUpdatesValues extends TypeSafeMatcher> { /** * Sample key. */ private final K key; /** * Sample value. */ private final V value; /** * Ctor. * @param akey Sample key * @param val Sample value */ public PutUpdatesValues(final K akey, final V val) { super(); this.key = akey; this.value = val; } @Override public boolean matchesSafely(final Map map) { map.put(this.key, this.value); MatcherAssert.assertThat( "Can't behave as a map after put", map, new BehavesAsMap(this.key, this.value) ); return true; } @Override public void describeTo(final Description desc) { desc.appendText("not a valid map"); } } cactoos-0.49/src/test/java/org/cactoos/map/RemoveDeletesValues.java000066400000000000000000000060161400054650300253550ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.map; import java.util.Map; import org.hamcrest.Description; import org.hamcrest.MatcherAssert; import org.hamcrest.TypeSafeMatcher; import org.hamcrest.collection.IsMapContaining; import org.hamcrest.core.IsCollectionContaining; import org.hamcrest.core.IsEqual; import org.hamcrest.core.IsNot; /** * Check a remove method. * @param Type of key * @param Type of value * @since 0.30 * @checkstyle JavadocMethodCheck (500 lines) */ public final class RemoveDeletesValues extends TypeSafeMatcher> { /** * Sample key. */ private final K key; /** * Sample value. */ private final V value; /** * Ctor. * @param akey Sample key * @param val Sample value */ public RemoveDeletesValues(final K akey, final V val) { super(); this.key = akey; this.value = val; } @Override public boolean matchesSafely(final Map map) { map.remove(this.key); MatcherAssert.assertThat( "Contains the key/value after remove", map, new IsNot<>( new IsMapContaining<>( new IsEqual<>(this.key), new IsEqual<>(this.value) ) ) ); MatcherAssert.assertThat( "Contains the key in #keySet() after remove", map.keySet(), new IsNot<>( new IsCollectionContaining<>(new IsEqual<>(this.key)) ) ); MatcherAssert.assertThat( "Contains the value in #values() after remove", map.values(), new IsNot<>( new IsCollectionContaining<>(new IsEqual<>(this.value)) ) ); return true; } @Override public void describeTo(final Description desc) { desc.appendText("not a valid map"); } } cactoos-0.49/src/test/java/org/cactoos/map/SyncedTest.java000066400000000000000000000045221400054650300235170ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.map; import org.hamcrest.MatcherAssert; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.RunsInThreads; /** * Test case for {@link Synced}. * * @since 0.24 * @checkstyle JavadocMethodCheck (500 lines) * @checkstyle ClassDataAbstractionCouplingCheck (500 lines) */ final class SyncedTest { @Test void behavesAsMap() { MatcherAssert.assertThat( "Can't behave as a map", new Synced( new MapEntry<>(0, -1), new MapEntry<>(1, 1) ), new BehavesAsMap<>(1, 1) ); } @Test void worksInThreads() { MatcherAssert.assertThat( "Can't behave as a map in multiple threads", map -> { MatcherAssert.assertThat( "Can't behave as a map in thread", map, new BehavesAsMap<>(1, 1) ); return true; }, new RunsInThreads<>( new Synced( new MapEntry<>(0, -1), new MapEntry<>(1, 1) ) ) ); } } cactoos-0.49/src/test/java/org/cactoos/map/package-info.java000066400000000000000000000023061400054650300237540ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ /** * Maps, tests. * * @since 0.14 */ package org.cactoos.map; cactoos-0.49/src/test/java/org/cactoos/package-info.java000066400000000000000000000027371400054650300232070ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ /** * Tests. * * @todo #1420:30min Continue replacing usage of MatcherAssert.assertThat with * Assertion from cactoos-matchers. Keep PR short and limit the changes to * single package. Update this puzzle for the next package. * After all packages are done, add MatcherAssert to forbidden-apis.txt * * @since 0.9 */ package org.cactoos; cactoos-0.49/src/test/java/org/cactoos/proc/000077500000000000000000000000001400054650300207525ustar00rootroot00000000000000cactoos-0.49/src/test/java/org/cactoos/proc/BiProcNoNullsTest.java000066400000000000000000000047771400054650300251650ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.proc; import java.util.concurrent.atomic.AtomicInteger; import org.hamcrest.core.IsEqual; import org.junit.Test; import org.llorllale.cactoos.matchers.Assertion; /** * Test case for {@link BiProcNoNulls}. * @since 0.11 * @checkstyle JavadocMethodCheck (500 lines) */ public final class BiProcNoNullsTest { @Test(expected = IllegalArgumentException.class) public void failForNullProc() throws Exception { new BiProcNoNulls<>(null).exec(new Object(), new Object()); } @Test(expected = IllegalArgumentException.class) public void failForNullFirstArg() throws Exception { new BiProcNoNulls<>( (first, second) -> { } ).exec(null, new Object()); } @Test(expected = IllegalArgumentException.class) public void failForNullSecondArg() throws Exception { new BiProcNoNulls<>( (first, second) -> { } ).exec(new Object(), null); } @Test public void okForNoNulls() throws Exception { final AtomicInteger counter = new AtomicInteger(); new BiProcNoNulls<>( (AtomicInteger ctr, Object second) -> { ctr.incrementAndGet(); } ).exec(counter, new Object()); new Assertion<>( "Can't invoke the \"BiProc.exec\" method", counter.get(), new IsEqual<>(1) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/proc/CheckedBiProcTest.java000066400000000000000000000060611400054650300251050ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.proc; import java.io.EOFException; import java.io.IOException; import java.util.concurrent.atomic.AtomicInteger; import org.hamcrest.core.IsEqual; import org.hamcrest.core.IsNull; import org.junit.Test; import org.llorllale.cactoos.matchers.Assertion; /** * Test case for {@link CheckedBiProc}. * * @since 0.32 * @checkstyle JavadocMethodCheck (500 lines) */ public final class CheckedBiProcTest { @Test(expected = IllegalStateException.class) public void runtimeExceptionIsNotWrapped() throws Exception { new CheckedBiProc<>( (first, second) -> { throw new IllegalStateException("runtime1"); }, IOException::new ).exec(true, true); } @Test(expected = IOException.class) public void checkedExceptionIsWrapped() throws Exception { new CheckedBiProc<>( (first, second) -> { throw new EOFException("runtime2"); }, IOException::new ).exec(true, true); } @Test public void extraWrappingIgnored() { try { new CheckedBiProc<>( (first, second) -> { throw new IOException("runtime3"); }, IOException::new ).exec(true, true); } catch (final IOException exp) { new Assertion<>( "Extra wrapping of IOException has been added", exp.getCause(), new IsNull<>() ).affirm(); } } @Test public void noExceptionThrown() throws Exception { final AtomicInteger counter = new AtomicInteger(); new CheckedBiProc<>( (first, second) -> counter.incrementAndGet(), exp -> exp ).exec(true, true); new Assertion<>( "Must not throw an exception", counter.get(), new IsEqual<>(1) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/proc/CheckedProcTest.java000066400000000000000000000057461400054650300246430ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.proc; import java.io.EOFException; import java.io.IOException; import java.util.concurrent.atomic.AtomicInteger; import org.hamcrest.core.IsEqual; import org.hamcrest.core.IsNull; import org.junit.Test; import org.llorllale.cactoos.matchers.Assertion; /** * Test case for {@link CheckedProc}. * * @since 0.32 * @checkstyle JavadocMethodCheck (500 lines) */ public final class CheckedProcTest { @Test(expected = IllegalStateException.class) public void runtimeExceptionIsNotWrapped() throws Exception { new CheckedProc<>( input -> { throw new IllegalStateException("runtime1"); }, IOException::new ).exec(true); } @Test(expected = IOException.class) public void checkedExceptionIsWrapped() throws Exception { new CheckedProc<>( input -> { throw new EOFException("runtime2"); }, IOException::new ).exec(true); } @Test public void extraWrappingIgnored() { try { new CheckedProc<>( input -> { throw new IOException("runtime3"); }, IOException::new ).exec(true); } catch (final IOException exp) { new Assertion<>( "Extra wrapping of IOException has been added", exp.getCause(), new IsNull<>() ).affirm(); } } @Test public void noExceptionThrown() throws Exception { final AtomicInteger counter = new AtomicInteger(); new CheckedProc<>( input -> counter.incrementAndGet(), exp -> exp ).exec(false); new Assertion<>( "Must not throw an exception", counter.get(), new IsEqual<>(1) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/proc/ForEachInThreadsTest.java000066400000000000000000000052751400054650300255770ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.proc; import java.util.List; import org.cactoos.list.ListOf; import org.cactoos.list.Synced; import org.hamcrest.collection.IsIterableContainingInAnyOrder; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.MatcherOf; /** * Test case for {@link ForEachInThreads}. * * @since 1.0 * @checkstyle JavadocMethodCheck (500 lines) * @checkstyle ClassDataAbstractionCouplingCheck (500 lines) */ public class ForEachInThreadsTest { @Test @SuppressWarnings("unchecked") void testProcIterable() throws Exception { final List list = new Synced<>( new ListOf<>() ); new ForEachInThreads( new ProcNoNulls<>( list::add ) ).exec( new ListOf<>( 1, 2 ) ); new Assertion<>( "List does not contain mapped Iterable elements", list, new IsIterableContainingInAnyOrder<>( new ListOf<>( new MatcherOf<>( value -> { return value.equals( 1 ); } ), new MatcherOf<>( value -> { return value.equals( 2 ); } ) ) ) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/proc/ForEachTest.java000066400000000000000000000040151400054650300237640ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.proc; import java.util.LinkedList; import java.util.List; import org.cactoos.iterable.IterableOf; import org.cactoos.list.ListOf; import org.hamcrest.core.IsEqual; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; /** * Test case for {@link ForEach}. * * @since 1.0 * @checkstyle JavadocMethodCheck (500 lines) */ public class ForEachTest { @Test void testProcIterable() throws Exception { final List list = new LinkedList<>(); new ForEach( list::add ).exec( new IterableOf<>( 1, 1 ) ); new Assertion<>( "List does not contain mapped Iterable elements", list, new IsEqual<>( new ListOf<>( 1, 1 ) ) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/proc/ForEachWithIndexTest.java000066400000000000000000000040711400054650300256120ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.proc; import org.cactoos.iterable.IterableOf; import org.hamcrest.core.IsEqual; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; /** * Test case for {@link ForEachWithIndex}. * * @since 1.0 * @checkstyle JavadocMethodCheck (500 lines) */ final class ForEachWithIndexTest { @Test void testBiProcIterable() throws Exception { final StringBuilder builder = new StringBuilder(); new ForEachWithIndex<>( (input, index) -> builder.append(String.format("%d: '%s' ", index + 1, input)) ).exec( new IterableOf<>( "Mary", "John", "William", "Napkin" ) ); new Assertion<>( "String must contain mapped Iterable elements", builder.toString(), new IsEqual<>( "1: 'Mary' 2: 'John' 3: 'William' 4: 'Napkin' " ) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/proc/IoCheckedBiProcTest.java000066400000000000000000000070151400054650300253750ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.proc; import java.io.IOException; import java.util.concurrent.atomic.AtomicInteger; import org.cactoos.func.IoCheckedBiFunc; import org.hamcrest.core.IsEqual; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.Throws; /** * Test case for {@link IoCheckedBiFunc}. * @since 1.0 * @checkstyle JavadocMethodCheck (500 lines) */ final class IoCheckedBiProcTest { @Test void executesWrappedProc() throws Exception { final AtomicInteger counter = new AtomicInteger(); new IoCheckedBiProc<>( (first, second) -> counter.incrementAndGet() ).exec(true, true); new Assertion<>( "Must execute wrapped proc", counter.get(), new IsEqual<>(1) ).affirm(); } @Test void wrapsExceptions() { final IoCheckedBiProc proc = new IoCheckedBiProc<>( (first, second) -> { throw new IOException(); } ); new Assertion<>( "Must wrap with IOException", () -> { proc.exec(true, true); return true; }, new Throws<>( "java.io.IOException", IOException.class ) ).affirm(); } @Test void rethrowsIoException() { final IOException exception = new IOException("intended"); try { new IoCheckedBiProc<>( (fst, scd) -> { throw exception; } ).exec(1, 2); } catch (final IOException ex) { new Assertion<>( "Must re-throw IOException", ex, new IsEqual<>(exception) ).affirm(); } } @Test void runtimeExceptionGoesOut() { final String msg = "intended to fail here"; final IoCheckedBiProc proc = new IoCheckedBiProc<>( (fst, scd) -> { throw new IllegalStateException(msg); } ); new Assertion<>( "Must re-throw runtime exceptions", () -> { proc.exec(true, true); return true; }, new Throws<>( msg, IllegalStateException.class ) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/proc/IoCheckedProcTest.java000066400000000000000000000056111400054650300251220ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.proc; import java.io.IOException; import org.cactoos.Proc; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.Throws; /** * Test case for {@link IoCheckedProc}. * * @since 0.4 * @checkstyle JavadocMethodCheck (500 lines) */ final class IoCheckedProcTest { @Test void rethrowsIoException() { final IOException exception = new IOException("intended"); new Assertion<>( "Must rethrow original IOException", () -> { new IoCheckedProc<>( (Proc) i -> { throw exception; } ).exec(1); return null; }, new Throws<>(exception.getMessage(), exception.getClass()) ).affirm(); } @Test void rethrowsCheckedToIoException() { new Assertion<>( "Must wrap and throw IOException", () -> { new IoCheckedProc<>( (Proc) i -> { throw new InterruptedException("intended to fail"); } ).exec(1); return null; }, new Throws<>(IOException.class) ).affirm(); } @Test void runtimeExceptionGoesOut() { new Assertion<>( "Must throw runtime exceptions as is", () -> { new IoCheckedProc<>( i -> { throw new IllegalStateException("intended to fail here"); } ).exec(1); return null; }, new Throws<>(IllegalStateException.class) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/proc/ProcNoNullsTest.java000066400000000000000000000042171400054650300246770ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.proc; import java.util.concurrent.atomic.AtomicInteger; import org.hamcrest.core.IsEqual; import org.junit.Test; import org.llorllale.cactoos.matchers.Assertion; /** * Test case for {@link ProcNoNulls}. * @since 0.11 * @checkstyle JavadocMethodCheck (500 lines) */ public final class ProcNoNullsTest { @Test(expected = IllegalArgumentException.class) public void failForNullProc() throws Exception { new ProcNoNulls<>(null).exec(new Object()); } @Test(expected = IllegalArgumentException.class) public void failForNullInput() throws Exception { new ProcNoNulls<>(input -> { }).exec(null); } @Test public void okForNoNulls() throws Exception { final AtomicInteger counter = new AtomicInteger(); new ProcNoNulls<>(AtomicInteger::incrementAndGet) .exec(counter); new Assertion<>( "Can't involve the \"Proc.exec(X input)\" method", counter.get(), new IsEqual<>(1) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/proc/ProcOfTest.java000066400000000000000000000052441400054650300236520ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.proc; import java.util.concurrent.atomic.AtomicReference; import org.cactoos.func.FuncOf; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.MatcherOf; /** * Test case for {@link ProcOf}. * * @since 0.3 */ final class ProcOfTest { @Test void worksWithFunc() throws Exception { final AtomicReference done = new AtomicReference<>(); new Assertion<>( "Must execute Proc with Func", new ProcOf<>( new FuncOf<>( input -> { done.set(input); return true; } ) ), new MatcherOf<>( proc -> { final Object input = new Object(); proc.exec(input); return done.get() == input; } ) ).affirm(); } @Test void worksWithLambda() throws Exception { final AtomicReference done = new AtomicReference<>(); new Assertion<>( "Must execute Proc with Lambda", new ProcOf<>( input -> { done.set(input); } ), new MatcherOf<>( proc -> { final Object input = new Object(); proc.exec(input); return done.get() == input; } ) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/proc/RepeatedProcTest.java000066400000000000000000000043311400054650300250330ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.proc; import java.util.concurrent.atomic.AtomicInteger; import org.cactoos.Proc; import org.hamcrest.core.IsEqual; import org.junit.Assert; import org.junit.Test; import org.llorllale.cactoos.matchers.Assertion; /** * Test case for {@link RepeatedProc}. * * @since 0.49.2 * @checkstyle MagicNumberCheck (100 line) * @checkstyle JavadocMethodCheck (100 lines) */ public final class RepeatedProcTest { @Test public void runsProcMultipleTimes() throws Exception { final AtomicInteger atom = new AtomicInteger(); final Proc func = new RepeatedProc<>( AtomicInteger::getAndIncrement, 3 ); func.exec(atom); new Assertion<>( "must run proc 3 times", atom.get(), new IsEqual<>(3) ); } @Test(expected = IllegalArgumentException.class) public void throwsIfZero() throws Exception { final Proc func = new RepeatedProc<>( obj -> Assert.fail("unexpected"), 0 ); func.exec(new Object()); } } cactoos-0.49/src/test/java/org/cactoos/proc/RunnableOfTest.java000066400000000000000000000064551400054650300245220ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.proc; import java.util.concurrent.atomic.AtomicReference; import org.cactoos.scalar.ScalarOf; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.MatcherOf; /** * Test case for {@link RunnableOf}. * * @since 0.2 */ final class RunnableOfTest { @Test void convertsProcIntoRunnable() { final AtomicReference done = new AtomicReference<>(); final Object obj = new Object(); new Assertion<>( "Must execute Runnable with Proc", new RunnableOf( new ProcOf<>( input -> { done.set(input); } ), obj ), new MatcherOf<>( runnable -> { runnable.run(); return done.get().equals(obj); } ) ).affirm(); } @Test void convertsScalarIntoRunnable() { final AtomicReference done = new AtomicReference<>(); final Object obj = new Object(); new Assertion<>( "Must execute Runnable with Scalar", new RunnableOf( new ScalarOf<>( () -> { done.set(obj); return "discarded"; } ) ), new MatcherOf<>( runnable -> { runnable.run(); return done.get().equals(obj); } ) ).affirm(); } @Test void convertsLambdaIntoRunnable() { final AtomicReference done = new AtomicReference<>(); final Object obj = new Object(); new Assertion<>( "Must execute Runnable with Lambda", new RunnableOf( () -> { done.set(obj); } ), new MatcherOf( runnable -> { runnable.run(); return done.get().equals(obj); } ) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/proc/UncheckedProcTest.java000066400000000000000000000036021400054650300251730ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.proc; import java.io.IOException; import java.io.UncheckedIOException; import org.junit.Test; /** * Test case for {@link UncheckedProc}. * * @since 0.2 * @checkstyle JavadocMethodCheck (500 lines) */ public final class UncheckedProcTest { @Test(expected = UncheckedIOException.class) public void rethrowsCheckedToUncheckedException() { new UncheckedProc<>( input -> { throw new IOException("intended"); } ).exec(1); } @Test(expected = IllegalStateException.class) public void runtimeExceptionGoesOut() { new UncheckedProc<>( i -> { throw new IllegalStateException("intended to fail"); } ).exec(1); } } cactoos-0.49/src/test/java/org/cactoos/proc/package-info.java000066400000000000000000000023151400054650300241420ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ /** * Procedures, tests. * * @since 0.47 */ package org.cactoos.proc; cactoos-0.49/src/test/java/org/cactoos/scalar/000077500000000000000000000000001400054650300212545ustar00rootroot00000000000000cactoos-0.49/src/test/java/org/cactoos/scalar/AndInThreadsTest.java000066400000000000000000000175031400054650300252710ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.scalar; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.cactoos.Scalar; import org.cactoos.func.FuncOf; import org.cactoos.iterable.IterableOf; import org.cactoos.iterable.Mapped; import org.cactoos.list.ListOf; import org.cactoos.list.Synced; import org.cactoos.proc.ProcNoNulls; import org.hamcrest.Matcher; import org.hamcrest.MatcherAssert; import org.hamcrest.Matchers; import org.hamcrest.collection.IsIterableContainingInAnyOrder; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.MatcherOf; import org.llorllale.cactoos.matchers.ScalarHasValue; /** * Test case for {@link AndInThreads}. * @since 0.25 * @checkstyle JavadocMethodCheck (500 lines) * @checkstyle ClassDataAbstractionCouplingCheck (500 lines) */ @SuppressWarnings({"PMD.TooManyMethods", "PMD.AvoidDuplicateLiterals"}) final class AndInThreadsTest { @Test void allTrue() throws Exception { new Assertion<>( "Each object must be True", new AndInThreads( new True(), new True(), new True() ), new ScalarHasValue<>(true) ).affirm(); } @Test void oneFalse() throws Exception { new Assertion<>( "One object must be False", new AndInThreads( new True(), new False(), new True() ), new ScalarHasValue<>(false) ).affirm(); } @Test void allFalse() throws Exception { new Assertion<>( "Each object must be False", new AndInThreads( new IterableOf>( new False(), new False(), new False() ) ), new ScalarHasValue<>(false) ).affirm(); } @Test void emptyIterable() throws Exception { new Assertion<>( "Must iterate over empty iterable", new AndInThreads(new IterableOf>()), new ScalarHasValue<>(true) ).affirm(); } @Test void iteratesList() { final List list = new Synced<>(new ListOf<>()); new Assertion<>( "Must iterate a list with a function", new AndInThreads( new Mapped<>( new FuncOf>(list::add, new True()), new IterableOf<>("hello", "world") ) ), new ScalarHasValue<>(true) ).affirm(); new Assertion<>( "Iterable must contain elements in any order", list, new IsIterableContainingInAnyOrder( new ListOf>( new MatcherOf<>( text -> { return "hello".equals(text); } ), new MatcherOf<>( text -> { return "world".equals(text); } ) ) ) ).affirm(); } @Test void worksWithFunc() throws Exception { MatcherAssert.assertThat( new AndInThreads( input -> input > 0, 1, -1, 0 ), new ScalarHasValue<>(false) ); } @Test void worksWithIterableScalarBoolean() throws Exception { MatcherAssert.assertThat( new AndInThreads( new ListOf>( new Constant(true), new Constant(true) ) ).value(), Matchers.equalTo(true) ); } @Test void worksWithExecServiceProcValues() throws Exception { final List list = new Synced<>(new ListOf<>()); final ExecutorService service = Executors.newSingleThreadExecutor(); new AndInThreads( service, new ProcNoNulls(list::add), 1, 2 ).value(); MatcherAssert.assertThat( list, new IsIterableContainingInAnyOrder( new ListOf>( new MatcherOf<>( value -> { return value.equals(1); } ), new MatcherOf<>( value -> { return value.equals(2); } ) ) ) ); } @Test void worksWithExecServiceProcIterable() throws Exception { final List list = new Synced<>(new ListOf<>()); final ExecutorService service = Executors.newSingleThreadExecutor(); new AndInThreads( service, new ProcNoNulls(list::add), new ListOf<>(1, 2) ).value(); MatcherAssert.assertThat( list, new IsIterableContainingInAnyOrder( new ListOf>( new MatcherOf<>( value -> { return value.equals(1); } ), new MatcherOf<>( value -> { return value.equals(2); } ) ) ) ); } @Test void worksWithExecServiceScalarBooleans() throws Exception { MatcherAssert.assertThat( new AndInThreads( Executors.newSingleThreadExecutor(), new Constant(false), new Constant(false) ).value(), Matchers.equalTo(false) ); } @Test void worksWithExecServiceIterableScalarBoolean() throws Exception { MatcherAssert.assertThat( new AndInThreads( Executors.newSingleThreadExecutor(), new ListOf>( new Constant(true), new Constant(false) ) ).value(), Matchers.equalTo(false) ); } @Test void worksWithEmptyIterableScalarBoolean() throws Exception { MatcherAssert.assertThat( new AndInThreads( new ListOf>() ).value(), Matchers.equalTo(true) ); } } cactoos-0.49/src/test/java/org/cactoos/scalar/AndTest.java000066400000000000000000000104461400054650300234660ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.scalar; import org.cactoos.Scalar; import org.cactoos.iterable.IterableOf; import org.hamcrest.MatcherAssert; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.ScalarHasValue; /** * Test case for {@link And}. * @since 0.8 * @checkstyle JavadocMethodCheck (500 lines) * @checkstyle MagicNumber (500 line) */ @SuppressWarnings("PMD.TooManyMethods") final class AndTest { @Test void allTrue() throws Exception { new Assertion<>( "Each object must be True", new And( new True(), new True(), new True() ), new ScalarHasValue<>(true) ).affirm(); } @Test void oneFalse() throws Exception { new Assertion<>( "One object must be False", new And( new True(), new False(), new True() ), new ScalarHasValue<>(false) ).affirm(); } @Test void allFalse() throws Exception { new Assertion<>( "Each object must be False", new And( new IterableOf>( new False(), new False(), new False() ) ), new ScalarHasValue<>(false) ).affirm(); } @Test void emptyIterator() throws Exception { new Assertion<>( "Iterator must be empty", new And(new IterableOf>()), new ScalarHasValue<>(true) ).affirm(); } @Test void testFuncIterable() throws Exception { MatcherAssert.assertThat( new And( input -> input > 0, new IterableOf<>(1, -1, 0) ), new ScalarHasValue<>(false) ); } @Test void testFuncIterator() throws Exception { MatcherAssert.assertThat( new And( input -> input > 0, new IterableOf<>(1, -1, 0) ), new ScalarHasValue<>(false) ); } @Test void testFuncVarargs() throws Exception { MatcherAssert.assertThat( new And( input -> input > 0, -1, -2, 0 ), new ScalarHasValue<>(false) ); } @Test void testMultipleFuncConditionTrue() throws Exception { MatcherAssert.assertThat( "Can't compare subject with true conditions", new And( 3, input -> input > 0, input -> input > 5, input -> input > 4 ), new ScalarHasValue<>(false) ); } @Test void testMultipleFuncConditionFalse() throws Exception { MatcherAssert.assertThat( "Can't compare subject with false conditions", new And( "cactoos", input -> input.contains("singleton"), input -> input.contains("static") ), new ScalarHasValue<>(false) ); } } cactoos-0.49/src/test/java/org/cactoos/scalar/AndWithIndexTest.java000066400000000000000000000044671400054650300253200ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.scalar; import java.util.LinkedList; import java.util.List; import org.cactoos.func.BiFuncOf; import org.hamcrest.Matchers; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.MatcherOf; import org.llorllale.cactoos.matchers.ScalarHasValue; /** * Test case for {@link AndWithIndex}. * * @since 0.8 * @checkstyle JavadocMethodCheck (500 lines) * @checkstyle ClassDataAbstractionCouplingCheck (500 lines) */ final class AndWithIndexTest { @Test void iteratesListWithIndex() { final List list = new LinkedList<>(); new Assertion<>( "Must iterate a list with a procedure", new AndWithIndex( new BiFuncOf<>( (text, index) -> list.add(index, text), true ), "hello", "world" ), new ScalarHasValue<>( Matchers.allOf( Matchers.equalTo(true), new MatcherOf<>( value -> list.size() == 2 ) ) ) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/scalar/AvgOfTest.java000066400000000000000000000273521400054650300237720ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.scalar; import java.util.Collections; import org.cactoos.Scalar; import org.cactoos.iterable.IterableOf; import org.hamcrest.Matchers; import org.junit.Test; import org.llorllale.cactoos.matchers.Assertion; /** * Test case for {@link AvgOf}. * * @since 0.24 * @checkstyle JavadocMethodCheck (500 lines) * @checkstyle MagicNumberCheck (500 lines) */ @SuppressWarnings("PMD.TooManyMethods") public final class AvgOfTest { @Test public void withEmptyCollection() { new Assertion<>( "Average of elements in empty collection must be zero", new AvgOf(Collections.emptyList()).longValue(), Matchers.equalTo(0L) ).affirm(); } @Test public void withIntCollectionIntValue() { new Assertion<>( "Average of values in int collection must be int value", new AvgOf( 1, 2, 3, 4 ).intValue(), Matchers.equalTo(2) ).affirm(); } @Test public void withIntCollectionIntValueMaxValues() { new Assertion<>( "Average of values in MAX int collection must be MAX int value", new AvgOf( Integer.MAX_VALUE, Integer.MAX_VALUE ).intValue(), Matchers.equalTo(Integer.MAX_VALUE) ).affirm(); } @Test public void withIntCollectionLongValue() { new Assertion<>( "Average of values in int collection must be long value", new AvgOf( 1, 2, 3, 4 ).longValue(), Matchers.equalTo(2L) ).affirm(); } @Test public void withIntCollectionDoubleValue() { new Assertion<>( "Average of values in int collection must be double value", new AvgOf( 1, 2, 3, 4 ).doubleValue(), Matchers.equalTo(2.5d) ).affirm(); } @Test public void withIntCollectionFloatValue() { new Assertion<>( "Average of values in int collection must be float value", new AvgOf( 1, 2, 3, 4 ).floatValue(), Matchers.equalTo(2.5f) ).affirm(); } @Test public void withLongCollectionIntValue() { new Assertion<>( "Average of values in long collection must be int value", new AvgOf( 1L, 2L, 3L, 4L ).intValue(), Matchers.equalTo(2) ).affirm(); } @Test public void withLongCollectionLongValue() { new Assertion<>( "Average of values in long collection must be long value", new AvgOf( 1L, 2L, 3L, 4L ).longValue(), Matchers.equalTo(2L) ).affirm(); } @Test public void withLongCollectionMaxValue() { new Assertion<>( "Average of values in MAX long collection must be MAX long value", new AvgOf( Long.MAX_VALUE, Long.MAX_VALUE ).longValue(), Matchers.equalTo(Long.MAX_VALUE) ).affirm(); } @Test public void withLongCollectionDoubleValue() { new Assertion<>( "Average of values in long collection must be double value", new AvgOf( 1L, 2L, 3L, 4L ).doubleValue(), Matchers.equalTo(2.5d) ).affirm(); } @Test public void withLongCollectionFloatValue() { new Assertion<>( "Average of values in long collection must be float value", new AvgOf( 1L, 2L, 3L, 4L ).floatValue(), Matchers.equalTo(2.5f) ).affirm(); } @Test public void withDoubleCollectionIntValue() { new Assertion<>( "Average of values in double collection must be int value", new AvgOf( 1.0d, 2.0d, 3.0d, 4.0d ).intValue(), Matchers.equalTo(2) ).affirm(); } @Test public void withDoubleCollectionLongValue() { new Assertion<>( "Average of values in double collection must be long value", new AvgOf( 1.0d, 2.0d, 3.0d, 4.0d ).longValue(), Matchers.equalTo(2L) ).affirm(); } @Test public void withDoubleCollectionDoubleValue() { new Assertion<>( "Average of values in double collection must be double value", new AvgOf( 1.0d, 2.0d, 3.0d, 4.0d ).doubleValue(), Matchers.equalTo(2.5d) ).affirm(); } @Test public void withDoubleCollectionMaxValue() { new Assertion<>( "Average of values in MAX double collection must be MAX double value", new AvgOf( Double.MAX_VALUE, Double.MAX_VALUE ).doubleValue(), Matchers.equalTo(Double.MAX_VALUE) ).affirm(); } @Test public void withDoubleCollectionMinValue() { new Assertion<>( "Average of values in MIN double collection must be MIN double value", new AvgOf( Double.MIN_VALUE, Double.MIN_VALUE ).doubleValue(), Matchers.equalTo(Double.MIN_VALUE) ).affirm(); } @Test(expected = NumberFormatException.class) public void withDoubleCollectionPositiveInfinity() { new AvgOf( Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY ).doubleValue(); } @Test(expected = NumberFormatException.class) public void withDoubleCollectionNegativeInfinity() { new AvgOf( Double.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY ).doubleValue(); } @Test(expected = NumberFormatException.class) public void withDoubleCollectionNaN() { new AvgOf( Double.NaN, Double.NaN ).doubleValue(); } @Test public void withDoubleCollectionNegativeNumbersDoubleValue() { new Assertion<>( "Average of values in negative double collection must be negative double value", new AvgOf( -1.0d, -2.0d, -3.0d, -4.0d ).doubleValue(), Matchers.equalTo(-2.5d) ).affirm(); } @Test public void withDecimalCollectionPrecisionProblem() { new Assertion<>( "Average of decimal values must have precision problem", new AvgOf( 100.0, 100.666, 100.0 ).floatValue(), Matchers.equalTo(100.222f) ).affirm(); } @Test public void withDecimalCollectionPrecisionProblemExtraDecimalRange() { new Assertion<>( "Average of decimal values with extra decimal range must have precision problem", new AvgOf( 100.266, 100.267 ).floatValue(), Matchers.equalTo(100.2665f) ).affirm(); } @Test public void withFloatCollectionIntValue() { new Assertion<>( "Average of float values in float collection must be int value", new AvgOf( 1.0f, 2.0f, 3.0f, 4.0f ).intValue(), Matchers.equalTo(2) ).affirm(); } @Test public void withFloatCollectionLongValue() { new Assertion<>( "Average of values in float collection must be long value", new AvgOf( 1.0f, 2.0f, 3.0f, 4.0f ).longValue(), Matchers.equalTo(2L) ).affirm(); } @Test public void withFloatCollectionDoubleValue() { new Assertion<>( "Average of values in float collection must be double value", new AvgOf( 1.0f, 2.0f, 3.0f, 4.0f ).doubleValue(), Matchers.equalTo(2.5d) ).affirm(); } @Test public void withFloatCollectionFloatValue() { new Assertion<>( "Average of values in float collection must be float value", new AvgOf( 1.0f, 2.0f, 3.0f, 4.0f ).floatValue(), Matchers.equalTo(2.5f) ).affirm(); } @Test public void withFloatCollectionMaxValue() { new Assertion<>( "Average of values in MAX float collection must be MAX float value", new AvgOf( Float.MAX_VALUE, Float.MAX_VALUE ).floatValue(), Matchers.equalTo(Float.MAX_VALUE) ).affirm(); } @Test public void withFloatCollectionMinValue() { new Assertion<>( "Average of values in MIN float collection must be MIN float value", new AvgOf( Float.MIN_VALUE, Float.MIN_VALUE ).floatValue(), Matchers.equalTo(Float.MIN_VALUE) ).affirm(); } @Test public void withIntScalarsIntValue() { new Assertion<>( "Average of int scalars must be int value", new AvgOf( () -> 1, () -> 2, () -> 10 ).intValue(), Matchers.equalTo(4) ).affirm(); } @Test public void withLongScalarsIntValue() { new Assertion<>( "Average of long scalars must be int value", new AvgOf( () -> 1L, () -> 2L, () -> 10L ).intValue(), Matchers.equalTo(4) ).affirm(); } @Test public void withFloatScalarsIntValue() { new Assertion<>( "Average of float scalars must be int value", new AvgOf( () -> 1.0f, () -> 2.0f, () -> 10.0f ).longValue(), Matchers.equalTo(4L) ).affirm(); } @Test public void withDoubleScalarsIntValue() { new Assertion<>( "Average of double scalars must be int value", new AvgOf( () -> 1.0d, () -> 2.0d, () -> 10.0d ).intValue(), Matchers.equalTo(4) ).affirm(); } @Test public void withIterableOfScalars() { new Assertion<>( "Average of iterable scalars must be long value", new AvgOf( new IterableOf>(() -> 1L, () -> 2L, () -> 10L) ).longValue(), Matchers.equalTo(4L) ).affirm(); } @Test public void withCompositionOfScalars() { new Assertion<>( "Average of composition of scalars must be int value", new AvgOf( () -> new MinOf(1.0d, 2.0d), () -> new MaxOf(2.0d, 4.0d), () -> new SumOf(1.0d, 2.0d, 2.0d), new Ternary<>(true, 5.0d, 1.0d) ).intValue(), Matchers.equalTo(3) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/scalar/BinaryTest.java000066400000000000000000000062231400054650300242060ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.scalar; import java.util.concurrent.atomic.AtomicInteger; import org.hamcrest.core.IsEqual; import org.junit.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.ScalarHasValue; import org.llorllale.cactoos.matchers.Throws; /** * Test case for {@link Binary}. * @since 1.0 * @checkstyle JavadocMethodCheck (500 lines) * @checkstyle ClassDataAbstractionCouplingCheck (500 lines) */ public final class BinaryTest { @Test public void conditionTrue() { final int expected = 1; final AtomicInteger counter = new AtomicInteger(0); final Binary binary = new Binary( new True(), counter::incrementAndGet ); new Assertion<>( "Binary has to return true", binary, new ScalarHasValue<>(true) ).affirm(); new Assertion<>( "Binary has to invoke increment method", counter.get(), new IsEqual<>(expected) ).affirm(); } @Test public void conditionFalse() { final int expected = 0; final AtomicInteger counter = new AtomicInteger(0); final Binary binary = new Binary( new False(), counter::incrementAndGet ); new Assertion<>( "Binary has to return false", binary, new ScalarHasValue<>(false) ).affirm(); new Assertion<>( "Binary must not to invoke increment method", counter.get(), new IsEqual<>(expected) ).affirm(); } @Test public void throwsException() { final String msg = "Custom exception message"; final Binary binary = new Binary( new True(), () -> { throw new IllegalArgumentException(msg); } ); new Assertion<>( "Binary has to throw exception", binary, new Throws<>(msg, IllegalArgumentException.class) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/scalar/BoolOfTest.java000066400000000000000000000041351400054650300241420ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.scalar; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.ScalarHasValue; /** * Test case for {@link BoolOf}. * * @since 0.2 * @checkstyle JavadocMethodCheck (500 lines) */ final class BoolOfTest { @Test void trueTest() throws Exception { new Assertion<>( "Must be parsed string 'true'", new BoolOf("true"), new ScalarHasValue<>(true) ).affirm(); } @Test void falseTest() throws Exception { new Assertion<>( "Must be parsed string 'false'", new BoolOf("false"), new ScalarHasValue<>(false) ).affirm(); } @Test void isFalseIfTextDoesNotRepresentABoolean() throws Exception { new Assertion<>( "Must be parsed a non-boolean string", new BoolOf("abc"), new ScalarHasValue<>(false) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/scalar/CallableOfTest.java000066400000000000000000000032561400054650300247510ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.scalar; import org.hamcrest.core.IsEqual; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; /** * Test case for {@link CallableOf}. * * @since 0.2 * @checkstyle JavadocMethodCheck (500 lines) */ final class CallableOfTest { @Test void convertsScalar() throws Exception { new Assertion<>( "must return the value of scalar", new CallableOf<>( new Constant<>(1) ).call(), new IsEqual<>(1) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/scalar/CheckedTest.java000066400000000000000000000066231400054650300243140ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.scalar; import java.io.FileNotFoundException; import java.io.IOException; import org.hamcrest.MatcherAssert; import org.hamcrest.Matchers; import org.junit.Test; /** * Test case for {@link Checked}. * @since 0.30 * @checkstyle JavadocMethodCheck (500 lines) */ public final class CheckedTest { @Test(expected = IllegalStateException.class) public void runtimeExceptionGoesOut() throws Exception { new Checked<>( () -> { throw new IllegalStateException("runtime"); }, IOException::new ).value(); } @Test(expected = IOException.class) public void throwsIoException() throws Exception { new Checked<>( () -> { throw new InterruptedException("interrupt"); }, IOException::new ).value(); } @Test public void ioExceptionGoesOut() throws Exception { try { new Checked<>( () -> { throw new IOException("io"); }, IOException::new ).value(); } catch (final IOException exp) { MatcherAssert.assertThat( exp.getCause(), Matchers.nullValue() ); } } @Test public void fileNotFoundExceptionGoesOut() throws Exception { try { new Checked<>( () -> { throw new FileNotFoundException("file not found"); }, IOException::new ).value(); } catch (final FileNotFoundException exp) { MatcherAssert.assertThat( exp.getCause(), Matchers.nullValue() ); } } @Test public void throwsIoExceptionWithModifiedMessage() throws Exception { final String message = "error msg"; try { new Checked<>( () -> { throw new IOException("io"); }, exp -> new IOException(message, exp) ).value(); } catch (final IOException exp) { MatcherAssert.assertThat( exp.getMessage(), Matchers.containsString(message) ); } } } cactoos-0.49/src/test/java/org/cactoos/scalar/ConstantTest.java000066400000000000000000000037441400054650300245600ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.scalar; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.ScalarHasValue; /** * Test case for {@link Constant}. * @since 0.30 * @checkstyle JavadocMethodCheck (500 lines) */ final class ConstantTest { @Test void returnsGivenValue() throws Exception { final String value = "Hello World"; new Assertion<>( "Must return given value", new Constant<>(value), new ScalarHasValue<>(value) ).affirm(); } @Test void alwaysReturnsSameValue() throws Exception { final Constant constant = new Constant<>("Good Bye!"); new Assertion<>( "Must return same value", constant, new ScalarHasValue<>(constant.value()) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/scalar/DivisionOfTest.java000066400000000000000000000051031400054650300250270ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.scalar; import org.hamcrest.core.IsEqual; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; /** * Test case for {@link DivisionOf}. * * @since 0.49.2 * @checkstyle MagicNumberCheck (500 lines) */ final class DivisionOfTest { /** * Ensures that division of int numbers return proper value. */ @Test void dividesIntNumbers() { new Assertion<>( "Must divide int numbers", new DivisionOf(4, 2).intValue(), new IsEqual<>(2) ).affirm(); } /** * Ensures that division of long numbers return proper value. */ @Test void dividesLongNumbers() { new Assertion<>( "Must divide long numbers", new DivisionOf(4L, 2L).longValue(), new IsEqual<>(2L) ).affirm(); } /** * Ensures that division of float numbers return proper value. */ @Test void dividesFloatNumbers() { new Assertion<>( "Must divide float numbers", new DivisionOf(2f, 4f).floatValue(), new IsEqual<>(0.5f) ).affirm(); } /** * Ensures that division of double numbers return proper value. */ @Test void dividesDoubleNumbers() { new Assertion<>( "Must divide double numbers", new DivisionOf(2d, 4d).doubleValue(), new IsEqual<>(0.5d) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/scalar/EqualityTest.java000066400000000000000000000074061400054650300245630ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.scalar; import org.cactoos.Bytes; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.ScalarHasValue; /** * Test case for {@link Equality}. * @since 0.31 * @checkstyle JavadocMethodCheck (500 lines) * @checkstyle MagicNumberCheck (500 lines) */ final class EqualityTest { @Test void notEqualLeft() throws Exception { new Assertion<>( "Must compare smaller to greater", new Equality<>( new EqualityTest.Letters("A"), new EqualityTest.Letters("AB") ), new ScalarHasValue<>(-1) ).affirm(); } @Test void notEqualRight() throws Exception { new Assertion<>( "Must compare greater to smaller", new Equality<>( new EqualityTest.Letters("AB"), new EqualityTest.Letters("A") ), new ScalarHasValue<>(1) ).affirm(); } @Test void notEqualLeftWithSameSize() throws Exception { new Assertion<>( "Must compare smaller to smaller with same size", new Equality<>( new EqualityTest.Letters("A"), new EqualityTest.Letters("B") ), new ScalarHasValue<>(-1) ).affirm(); } @Test void notEqualRightWithSameSize() throws Exception { new Assertion<>( "Must compare greater to smaller with same size", new Equality<>( new EqualityTest.Letters("B"), new EqualityTest.Letters("A") ), new ScalarHasValue<>(1) ).affirm(); } @Test void equal() throws Exception { new Assertion<>( "Must compare equals", new Equality<>( new EqualityTest.Letters("A"), new EqualityTest.Letters("A") ), new ScalarHasValue<>(0) ).affirm(); } @Test void compareEmptyArrays() throws Exception { new Assertion<>( "Must compare empty", new Equality<>( new EqualityTest.Letters(""), new EqualityTest.Letters("") ), new ScalarHasValue<>(0) ).affirm(); } /** * Weight. * @since 0.31 */ private static final class Letters implements Bytes { /** * Bytes. */ private final String text; /** * Ctor. * @param txt Text */ Letters(final String txt) { this.text = txt; } @Override public byte[] asBytes() { return this.text.getBytes(); } } } cactoos-0.49/src/test/java/org/cactoos/scalar/EqualsNullableTest.java000066400000000000000000000053341400054650300256750ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.scalar; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.ScalarHasValue; /** * Test case for {@link EqualsNullable}. * * @since 1.0 * @checkstyle JavadocMethodCheck (500 lines) */ @SuppressWarnings("PMD.SuspiciousEqualsMethodName") final class EqualsNullableTest { @Test void nullEqualsNull() throws Exception { new Assertion<>( "Must return true for both null objects", new EqualsNullable(() -> null, () -> null), new ScalarHasValue<>(true) ).affirm(); } @Test void equals() throws Exception { new Assertion<>( "Must return true for equal objects", new EqualsNullable(1, 1), new ScalarHasValue<>(true) ).affirm(); } @Test void notEquals() throws Exception { new Assertion<>( "Must return false for non equal objects", new EqualsNullable(1, 2), new ScalarHasValue<>(false) ).affirm(); } @Test void equalsObjectAndScalar() throws Exception { new Assertion<>( "Must return true for object and scalar with the same value", new EqualsNullable(1, () -> 1), new ScalarHasValue<>(true) ).affirm(); } @Test void equalsScalarAndObject() throws Exception { new Assertion<>( "Must return true for scalar and object with the same value", new EqualsNullable(() -> 1, 1), new ScalarHasValue<>(true) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/scalar/EqualsTest.java000066400000000000000000000053031400054650300242120ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.scalar; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.ScalarHasValue; /** * Test case for {@link Equals}. * * @since 0.9 * @checkstyle JavadocMethodCheck (500 lines) */ final class EqualsTest { @Test void compareEquals() throws Exception { new Assertion<>( "Must compare if two integers are equals", new Equals<>( () -> Integer.valueOf(1), () -> Integer.valueOf(1) ), new ScalarHasValue<>(true) ).affirm(); } @Test void compareNotEquals() throws Exception { new Assertion<>( "Must compare if two integers are not equals", new Equals<>( () -> Integer.valueOf(1), () -> Integer.valueOf(2) ), new ScalarHasValue<>(false) ).affirm(); } @Test void compareEqualsText() throws Exception { final String str = "hello"; new Assertion<>( "Must compare if two strings are equals", new Equals<>( () -> str, () -> str ), new ScalarHasValue<>(true) ).affirm(); } @Test void compareNotEqualsText() throws Exception { new Assertion<>( "Must compare if two strings are not equals", new Equals<>( () -> "world", () -> "worle" ), new ScalarHasValue<>(false) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/scalar/FalseTest.java000066400000000000000000000035271400054650300240200ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.scalar; import org.hamcrest.core.IsEqual; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.ScalarHasValue; /** * Test case for {@link False}. * * @since 0.7 * @checkstyle JavadocMethodCheck (500 lines) */ final class FalseTest { @Test void asValue() throws Exception { new Assertion<>( "Must return false", new False().value(), new IsEqual<>(false) ).affirm(); } @Test void asScalar() throws Exception { new Assertion<>( "Must be false", new False(), new ScalarHasValue<>(false) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/scalar/FirstOfTest.java000066400000000000000000000112771400054650300243430ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.scalar; import org.cactoos.iterable.IterableOf; import org.cactoos.iterable.IterableOfInts; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.ScalarHasValue; import org.llorllale.cactoos.matchers.Throws; /** * Tests for {@link FirstOf}. * * @since 0.32 * @checkstyle JavadocMethodCheck (500 lines) */ final class FirstOfTest { @Test void returnsMatchingValue() { final int value = 1; new Assertion<>( "Must return the only matching element", new FirstOf<>( i -> i >= value, new IterableOfInts(0, value), () -> -1 ), new ScalarHasValue<>(value) ).affirm(); } @Test void returnsMatchingValueWithExceptionalFallback() { final int value = 2; new Assertion<>( "Exception was not thrown", new FirstOf<>( i -> i >= value, new IterableOfInts(0, value), () -> { throw new IllegalArgumentException( "This exception should not be thrown" ); } ), new ScalarHasValue<>(value) ).affirm(); } @Test void returnsFirstValueForMultipleMatchingOnes() { final String value = "1"; new Assertion<>( "Must return first matching element", new FirstOf<>( i -> !i.isEmpty(), new IterableOf<>("1", "2"), () -> "" ), new ScalarHasValue<>(value) ).affirm(); } @Test void returnsFallbackIfNothingMatches() { final String value = "abc"; new Assertion<>( "Must return fallback", new FirstOf<>( i -> i.length() > 2, new IterableOf<>("ab", "cd"), () -> value ), new ScalarHasValue<>(value) ).affirm(); } @Test void throwsFallbackIfNothingMatches() { new Assertion<>( "Fallback was not thrown", new FirstOf<>( num -> num.equals(0), // @checkstyle MagicNumber (10 lines) new IterableOf<>( 1, 2, 3, 4, 5 ), () -> { throw new IllegalArgumentException( String.format("Unable to found element with id %d", 0) ); } ), new Throws<>(IllegalArgumentException.class) ).affirm(); } @Test void returnsFirstValueWithScalarFallback() { new Assertion<>( "Returns first value with scalar fallback", new FirstOf( new IterableOfInts(2, 1, 0), () -> -1 ), new ScalarHasValue<>(2) ).affirm(); } @Test void returnsFirstValueWithIntegerFallback() { new Assertion<>( "Returns first value with Integer fallback", new FirstOf<>( new IterableOfInts(2, 1, 0), -1 ), new ScalarHasValue<>(2) ).affirm(); } @Test void returnsFallbackWhenIterableEmpty() { new Assertion<>( "Returns fallback when iterable empty", new FirstOf( new IterableOf<>(), () -> -1 ), new ScalarHasValue<>(-1) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/scalar/FlattenedTest.java000066400000000000000000000036271400054650300246750ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.scalar; import org.cactoos.Scalar; import org.cactoos.Text; import org.cactoos.text.TextOf; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.ScalarHasValue; import org.llorllale.cactoos.matchers.TextIs; /** * Tests for {@link Flattened}. * * @since 0.49 * @checkstyle ClassDataAbstractionCouplingCheck (500 lines) */ final class FlattenedTest { @Test void flattens() { final Text txt = new TextOf("txt"); final Scalar sclr = new Constant<>(txt); new Assertion<>( "must flatten", new Flattened<>( new ScalarOf<>(() -> sclr) ), new ScalarHasValue<>(new TextIs(txt)) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/scalar/FoldedTest.java000066400000000000000000000045111400054650300241550ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.scalar; import org.cactoos.iterable.HeadOf; import org.cactoos.iterable.RangeOf; import org.hamcrest.core.IsEqual; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.ScalarHasValue; /** * Test case for {@link Folded}. * @since 0.30 * @checkstyle JavadocMethodCheck (500 lines) * @checkstyle MagicNumberCheck (500 lines) */ final class FoldedTest { @Test void skipIterable() throws Exception { new Assertion<>( "Must fold elements in iterable", new Folded<>( 0L, (first, second) -> first + second, new HeadOf<>( 10, new RangeOf<>(0L, Long.MAX_VALUE, value -> ++value) ) ), new ScalarHasValue<>(45L) ).affirm(); } @Test void constructedFromVarargs() throws Exception { new Assertion<>( "Must fold elements in vararg array", new Folded<>( 0L, (first, second) -> first + second, 1, 2, 3, 4, 5 ).value(), new IsEqual<>(15L) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/scalar/HashCodeTest.java000066400000000000000000000065701400054650300244450ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.scalar; import java.util.Objects; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.ScalarHasValue; /** * Tests for {@link HashCode}. * @since 1.0 */ final class HashCodeTest { /** * {@link HashCode} must compute the exact same hashCode as produced * by Joshua Block's "Item 9: Always override hashCode when you override * equals" in Effective Java, 2nd edition. */ @Test void computeHashCode() { final int initial = 5; final int multiplier = 31; final Object[] attributes = {5, 31, "abc", 5, 50f, "xyz"}; new Assertion<>( "Value must be equal to Josh Block's implementation of hashCode()", new HashCode(initial, multiplier, attributes), new ScalarHasValue<>( joshBloch(initial, multiplier, attributes) ) ).affirm(); } /** * {@link HashCode} must assume an {@code initial} values of 17 and a * {@code multiplier} value of 31 when these are not provided. */ @Test void computeHashCodeWithDefaultValues() { final int initial = 17; final int multiplier = 31; final Object[] attributes = {494, 43, "test", 190, 298f, "joshua"}; new Assertion<>( // @checkstyle LineLength (1 line) "Value must be equal to Josh Block's implementation of hashCode() with initial=17 and multiplier=31", new HashCode(attributes), new ScalarHasValue<>( joshBloch(initial, multiplier, attributes) ) ).affirm(); } /** * Joshua Bloch's implementation of hashCode() as per Effective Java, * 2nd Edition, Item 9: "Always override hashCode when you override equals". * @param initial Initial value * @param multiplier Step multiplier * @param attributes The object's attributes * @return Hashcode value */ private static int joshBloch( final int initial, final int multiplier, final Object... attributes ) { int hash = initial; for (final Object attr : attributes) { hash = hash * multiplier + Objects.hashCode(attr); } return hash; } } cactoos-0.49/src/test/java/org/cactoos/scalar/HighestOfTest.java000066400000000000000000000204271400054650300246440ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.scalar; import java.util.Collections; import java.util.Date; import java.util.NoSuchElementException; import org.cactoos.time.DateOf; import org.hamcrest.MatcherAssert; import org.hamcrest.Matchers; import org.junit.Test; /** * Test case for {@link HighestOf}. * * @since 0.29 * @checkstyle JavadocMethodCheck (500 lines) * @checkstyle MagicNumberCheck (500 lines) */ @SuppressWarnings("PMD.AvoidDuplicateLiterals") public final class HighestOfTest { @Test(expected = NoSuchElementException.class) public void failsForEmptyIterable() throws Exception { new HighestOf<>(() -> Collections.emptyIterator()).value(); } @Test public void singleAtSingleIterable() throws Exception { MatcherAssert.assertThat( "Can't find the highest among one by scalars", new HighestOf(() -> 10).value(), Matchers.equalTo(10) ); MatcherAssert.assertThat( "Can't find the highest among one", new HighestOf<>(10).value(), Matchers.equalTo(10) ); } @Test public void highestIntegerAtIterable() throws Exception { MatcherAssert.assertThat( "Can't find the highest integer among many by scalars", new HighestOf( () -> 10, () -> 0, () -> -1, () -> 2 ).value(), Matchers.equalTo(10) ); MatcherAssert.assertThat( "Can't find the highest integer among many", new HighestOf<>(10, 0, -1, 2).value(), Matchers.equalTo(10) ); MatcherAssert.assertThat( "Can't find the highest negative integer among many", new HighestOf<>(-272, -10, -134, -101).value(), Matchers.equalTo(-10) ); MatcherAssert.assertThat( "Can't find the highest max integer among many", new HighestOf<>(Integer.MIN_VALUE, Integer.MAX_VALUE).value(), Matchers.equalTo(Integer.MAX_VALUE) ); } @Test public void highestLongAtIterable() throws Exception { MatcherAssert.assertThat( "Can't find the highest long among many by scalars", new HighestOf( () -> 10L, () -> 0L, () -> -1L, () -> 2L ).value(), Matchers.equalTo(10L) ); MatcherAssert.assertThat( "Can't find the highest long among many", new HighestOf<>(10L, 0L, -1L, 2L).value(), Matchers.equalTo(10L) ); MatcherAssert.assertThat( "Can't find the highest negative long among many", new HighestOf<>(-272L, -10L, -134L, -101L).value(), Matchers.equalTo(-10L) ); MatcherAssert.assertThat( "Can't find the highest max integer long many", new HighestOf<>(Long.MIN_VALUE, Long.MAX_VALUE).value(), Matchers.equalTo(Long.MAX_VALUE) ); } @Test public void highestDoubleAtIterable() throws Exception { MatcherAssert.assertThat( "Can't find the highest double among many by scalars", new HighestOf( () -> 10.9, () -> 0.8, () -> -1.5, () -> 10.8 ).value(), Matchers.equalTo(10.9) ); MatcherAssert.assertThat( "Can't find the highest double among many", new HighestOf<>(10., 0., -1., 2.).value(), Matchers.equalTo(10.) ); MatcherAssert.assertThat( "Can't find the highest negative double among many", new HighestOf<>(-272., -10., -134., -101.).value(), Matchers.equalTo(-10.) ); MatcherAssert.assertThat( "Can't find the highest max double among many", new HighestOf<>(Double.MIN_VALUE, Double.MAX_VALUE).value(), Matchers.equalTo(Double.MAX_VALUE) ); MatcherAssert.assertThat( "Can't find the highest min double among many", new HighestOf<>(Double.MIN_VALUE, -10.).value(), Matchers.equalTo(Double.MIN_VALUE) ); MatcherAssert.assertThat( "Can't find the highest NaN double among many", new HighestOf<>(Double.NaN, Double.MAX_VALUE).value(), Matchers.equalTo(Double.NaN) ); MatcherAssert.assertThat( "Can't find the highest positive infinity among many", new HighestOf<>(Double.POSITIVE_INFINITY, Double.MAX_VALUE).value(), Matchers.equalTo(Double.POSITIVE_INFINITY) ); MatcherAssert.assertThat( "Can't find the highest negative infinity among many", new HighestOf<>(Double.NEGATIVE_INFINITY, Double.MAX_VALUE).value(), Matchers.equalTo(Double.MAX_VALUE) ); } @Test public void highestStringAtIterable() throws Exception { MatcherAssert.assertThat( "Can't find the highest string among many by scalars", new HighestOf(() -> "Apple", () -> "Orange").value(), Matchers.equalTo("Orange") ); MatcherAssert.assertThat( "Can't find the highest string among many", new HighestOf<>("Apple", "Orange").value(), Matchers.equalTo("Orange") ); } @Test public void highestCharAtIterable() throws Exception { MatcherAssert.assertThat( "Can't find the highest char among many by scalars", new HighestOf(() -> 'A', () -> 'B').value(), Matchers.equalTo('B') ); MatcherAssert.assertThat( "Can't find the highest char among many", new HighestOf<>('A', 'B').value(), Matchers.equalTo('B') ); } @Test public void highestSumAtIterable() throws Exception { MatcherAssert.assertThat( "Can't find the highest double sum among many", new HighestOf( new SumOf(1.0d), new SumOf(1.0d, 2.0d), new SumOf(1.0d, 2.0d, 3.0d) ).value(), Matchers.equalTo(new SumOf(1.0d, 2.0d, 3.0d).value()) ); } @Test public void highestDateAtIterable() throws Exception { MatcherAssert.assertThat( "Can't find the highest date among many", new HighestOf( new DateOf("2007-12-26T14:20:16.000000017Z"), new DateOf("2017-12-13T14:15:16.000000017Z"), new DateOf("2017-12-13T14:15:16.000000018Z") ).value(), Matchers.equalTo( new DateOf("2017-12-13T14:15:16.000000018Z").value() ) ); } @Test public void highestBooleanAtIterable() throws Exception { MatcherAssert.assertThat( "Can't find the highest boolean among many", new HighestOf( new BoolOf("false"), new BoolOf("true") ).value(), Matchers.equalTo(new BoolOf("true").value()) ); } } cactoos-0.49/src/test/java/org/cactoos/scalar/InheritanceLevelTest.java000066400000000000000000000044201400054650300262000ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.scalar; import java.io.FileNotFoundException; import org.hamcrest.MatcherAssert; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.ScalarHasValue; /** * Test case for {@link InheritanceLevel}. * * @since 0.30 * @checkstyle JavadocMethodCheck (500 lines) */ final class InheritanceLevelTest { @Test void twoInheritanceLevelsBetweenClasses() { MatcherAssert.assertThat( new InheritanceLevel( FileNotFoundException.class, Exception.class ), new ScalarHasValue<>(2) ); } @Test void classesAreNotRelated() { MatcherAssert.assertThat( new InheritanceLevel( FileNotFoundException.class, RuntimeException.class ), new ScalarHasValue<>(Integer.MIN_VALUE) ); } @Test void classesAreIdentical() { MatcherAssert.assertThat( new InheritanceLevel( FileNotFoundException.class, FileNotFoundException.class ), new ScalarHasValue<>(0) ); } } cactoos-0.49/src/test/java/org/cactoos/scalar/IoCheckedTest.java000066400000000000000000000052711400054650300246020ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.scalar; import java.io.IOException; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.Throws; /** * Test case for {@link IoChecked}. * * @since 0.4 * @checkstyle JavadocMethodCheck (500 lines) */ final class IoCheckedTest { @Test void rethrowsIoException() { final IOException exception = new IOException("intended"); new Assertion<>( "Must rethrow IOException", () -> new IoChecked<>( () -> { throw exception; } ).value(), new Throws<>(exception.getMessage(), exception.getClass()) ).affirm(); } @Test @SuppressWarnings("PMD.AvoidThrowingRawExceptionTypes") void throwsException() { new Assertion<>( "Must throw IOException from Exception", () -> new IoChecked<>( () -> { throw new Exception("intended to fail"); } ).value(), new Throws<>(IOException.class) ).affirm(); } @Test void runtimeExceptionGoesOut() { final RuntimeException exception = new IllegalStateException("intended to fail here"); new Assertion<>( "Must rethrow RuntimeExcepion", () -> new IoChecked<>( () -> { throw exception; } ).value(), new Throws<>(exception.getMessage(), exception.getClass()) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/scalar/ItemAtTest.java000066400000000000000000000102701400054650300241420ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.scalar; import java.io.IOException; import org.cactoos.iterable.IterableOf; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.ScalarHasValue; import org.llorllale.cactoos.matchers.Throws; /** * Test Case for {@link ItemAt}. * * @since 0.7 * @checkstyle JavadocMethodCheck (500 lines) */ @SuppressWarnings({ "PMD.TooManyMethods", "PMD.AvoidDuplicateLiterals" }) final class ItemAtTest { @Test void elementByPosIterableTest() { new Assertion<>( "must take the item by position from the iterable", new ItemAt<>( // @checkstyle MagicNumber (1 line) 1, new IterableOf<>(1, 2, 3) ), new ScalarHasValue<>(2) ).affirm(); } @Test void elementByPosFallbackIterableTest() { final int fallback = 5; new Assertion<>( "must fallback to default one", new ItemAt<>( 1, fallback, new IterableOf<>() ), new ScalarHasValue<>(fallback) ).affirm(); } @Test void elementByPosNoFallbackIterableTest() { new Assertion<>( "must take the item by position from the iterable", new ItemAt<>( // @checkstyle MagicNumber (1 line) 1, 5, new IterableOf<>(0, 1) ), new ScalarHasValue<>(1) ).affirm(); } @Test void elementByPosTest() { new Assertion<>( "must take the item by position from the iterator", new ItemAt<>( 1, // @checkstyle MagicNumber (1 line) new IterableOf<>(1, 2, 3) ), new ScalarHasValue<>(2) ).affirm(); } @Test void failForNegativePositionTest() { new Assertion<>( "Must fail for negative position", () -> new ItemAt<>( -1, // @checkstyle MagicNumber (1 line) new IterableOf<>(1, 2, 3) ).value(), new Throws<>( "The position must be non-negative: -1", IOException.class ) ).affirm(); } @Test void failForPosMoreLengthTest() { new Assertion<>( "Must fail for greater than length position", () -> new ItemAt<>( // @checkstyle MagicNumberCheck (2 lines) 3, new IterableOf<>(1, 2, 3) ).value(), new Throws<>( "The iterable doesn't have the position #3", IOException.class ) ).affirm(); } @Test void sameValueTest() throws Exception { final ItemAt item = new ItemAt<>( 1, // @checkstyle MagicNumberCheck (1 lines) new IterableOf<>(1, 2, 3) ); new Assertion<>( "Not the same value", item, new ScalarHasValue<>(item.value()) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/scalar/LengthOfTest.java000066400000000000000000000152461400054650300244750ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.scalar; import org.cactoos.io.InputOf; import org.cactoos.iterable.IterableOf; import org.cactoos.list.ListOf; import org.cactoos.text.TextOf; import org.hamcrest.core.IsEqual; import org.junit.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.HasValues; /** * Test case for {@link LengthOf}. * * @since 0.1.0 * @checkstyle MagicNumberCheck (500 lines) * @checkstyle JavadocMethodCheck (500 lines) * @checkstyle ClassDataAbstractionCouplingCheck (500 lines) */ @SuppressWarnings("PMD.TooManyMethods") public final class LengthOfTest { @Test public void lengthOfInputWithIntegerValue() { new Assertion<>( "Must calculate length of input with integer value", new LengthOf( new InputOf("Hello1") ).intValue(), new IsEqual<>(6) ).affirm(); } @Test public void lengthOfInputWithDoubleValue() { new Assertion<>( "Must calculate length of input with double value", new LengthOf( new InputOf("Hello2") ).doubleValue(), new IsEqual<>(6.0) ).affirm(); } @Test public void lengthOfInputWithFloatValue() { new Assertion<>( "Must calculate length of input with float value", new LengthOf( new InputOf("Hello3") ).floatValue(), new IsEqual<>(6.0f) ).affirm(); } @Test public void lengthOfInputWithCustomBuffer() { new Assertion<>( "Must calculate length with custom buffer", new LengthOf( new InputOf("test buffer1"), 1 ).intValue(), new IsEqual<>(12) ).affirm(); } @Test(expected = IllegalArgumentException.class) public void lengthOfZeroBuffer() { new Assertion<>( "Must calculate length with buffer of 0", new LengthOf( new InputOf("test buffer2"), 0 ).intValue(), new IsEqual<>(12) ).affirm(); } @Test public void lengthOfWithIntegerValue() { new Assertion<>( "Must calculate length of iterable for integer", new LengthOf( new IterableOf<>(1, 2, 3, 4) ).intValue(), new IsEqual<>(4) ).affirm(); } @Test public void lengthOfWithDoubleValue() { new Assertion<>( "Must calculate length of iterable for double", new LengthOf( new IterableOf<>(1, 2, 3, 4) ).doubleValue(), new IsEqual<>(4.0) ).affirm(); } @Test public void lengthOfWithFloatValue() { new Assertion<>( "Must calculate length of iterable for float", new LengthOf( new IterableOf<>(1, 2, 3, 4) ).floatValue(), new IsEqual<>(4.0f) ).affirm(); } @Test public void lengthOfEmptyIterable() { new Assertion<>( "Must calculate length of empty iterable", new LengthOf( new IterableOf<>() ).intValue(), new IsEqual<>(0) ).affirm(); } @Test public void lengthOfWithIntegerValues() { new Assertion<>( "Must calculate length of iterator for integer", new LengthOf( new ListOf<>(1, 2, 3, 4) ).intValue(), new IsEqual<>(4) ).affirm(); } @Test public void lengthOfWithDoubleNumber() { new Assertion<>( "Must calculate length of iterator for double", new LengthOf( new ListOf<>(1, 2, 3, 4) ).doubleValue(), new IsEqual<>(4.0) ).affirm(); } @Test public void lengthOfWithFloatNumber() { new Assertion<>( "Must calculate length of iterator for float", new LengthOf( new ListOf<>(1, 2, 3, 4) ).floatValue(), new IsEqual<>(4.0f) ).affirm(); } @Test public void lengthOfEmptyIterator() { new Assertion<>( "Must calculate length of empty iterator", new LengthOf( new ListOf<>() ).intValue(), new IsEqual<>(0) ).affirm(); } @Test public void lengthOfEmptyText() { new Assertion<>( "Must calculate length of empty string", new LengthOf(new TextOf("")).intValue(), new IsEqual<>(0) ).affirm(); } @Test public void lengthOfUnicodeAsText() { new Assertion<>( "Must calculate character-length of unicode text", new LengthOf(new TextOf("привет")).intValue(), new IsEqual<>(6) ).affirm(); } @Test public void lengthOfUnicodeAsInput() { new Assertion<>( "Must calculate character-length of unicode input", new LengthOf(new InputOf("Привет")).intValue(), new IsEqual<>(12) ).affirm(); } @Test public void lengthOfText() { final Number num = new LengthOf(new TextOf("abcd")); new Assertion<>( "Must calculate length of non-empty string", new IterableOf( num.intValue(), num.floatValue(), num.longValue(), num.doubleValue() ), new HasValues<>(4, 4f, 4L, 4d) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/scalar/LowestOfTest.java000066400000000000000000000222111400054650300245170ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.scalar; import java.util.Collections; import java.util.Date; import java.util.NoSuchElementException; import org.cactoos.time.DateOf; import org.hamcrest.MatcherAssert; import org.hamcrest.Matchers; import org.junit.Test; /** * Test case for {@link LowestOf}. * * @since 0.29 * @checkstyle JavadocMethodCheck (500 lines) * @checkstyle MagicNumberCheck (500 lines) */ @SuppressWarnings("PMD.AvoidDuplicateLiterals") public final class LowestOfTest { @Test(expected = NoSuchElementException.class) public void failsForEmptyIterable() throws Exception { new LowestOf<>(() -> Collections.emptyIterator()).value(); } @Test public void singleAtSingleIterable() throws Exception { MatcherAssert.assertThat( "Can't find the lowest among one by scalars", new LowestOf(() -> 10).value(), Matchers.equalTo(10) ); MatcherAssert.assertThat( "Can't find the lowest among one", new LowestOf<>(10).value(), Matchers.equalTo(10) ); } @Test public void lowestIntegerAtIterable() throws Exception { MatcherAssert.assertThat( "Can't find the lowest integer among many by scalars", new LowestOf( () -> 10, () -> 0, () -> -1, () -> 2 ).value(), Matchers.equalTo(-1) ); MatcherAssert.assertThat( "Can't find the lowest integer among many", new LowestOf<>(10, 0, -1, 2).value(), Matchers.equalTo(-1) ); MatcherAssert.assertThat( "Can't find the lowest positive integer among many", new LowestOf<>(272, 10, 134, 101).value(), Matchers.equalTo(10) ); MatcherAssert.assertThat( "Can't find the lowest negative integer among many", new LowestOf<>(-272, -10, -134, -101).value(), Matchers.equalTo(-272) ); MatcherAssert.assertThat( "Can't find the lowest min integer among many", new LowestOf<>(Integer.MIN_VALUE, Integer.MAX_VALUE).value(), Matchers.equalTo(Integer.MIN_VALUE) ); } @Test public void lowestLongAtIterable() throws Exception { MatcherAssert.assertThat( "Can't find the lowest long among many by scalars", new LowestOf( () -> 10L, () -> 0L, () -> -1L, () -> 2L ).value(), Matchers.equalTo(-1L) ); MatcherAssert.assertThat( "Can't find the lowest long among many", new LowestOf<>(10L, 0L, -1L, 2L).value(), Matchers.equalTo(-1L) ); MatcherAssert.assertThat( "Can't find the lowest positive long among many", new LowestOf<>(272L, 10L, 134L, 101L).value(), Matchers.equalTo(10L) ); MatcherAssert.assertThat( "Can't find the lowest negative long among many", new LowestOf<>(-272L, -10L, -134L, -101L).value(), Matchers.equalTo(-272L) ); MatcherAssert.assertThat( "Can't find the lowest mix integer long many", new LowestOf<>(Long.MIN_VALUE, Long.MAX_VALUE).value(), Matchers.equalTo(Long.MIN_VALUE) ); } @Test public void lowestDoubleAtIterable() throws Exception { MatcherAssert.assertThat( "Can't find the lowest double among many by scalars", new LowestOf( () -> 10.9, () -> 0.8, () -> -1.5, () -> 10.8 ).value(), Matchers.equalTo(-1.5) ); MatcherAssert.assertThat( "Can't find the lowest double among many", new LowestOf<>(10., 0., -1., 2.).value(), Matchers.equalTo(-1.) ); MatcherAssert.assertThat( "Can't find the lowest positive double among many", new LowestOf<>(272., 10., 134., 101.).value(), Matchers.equalTo(10.) ); MatcherAssert.assertThat( "Can't find the lowest negative double among many", new LowestOf<>(-272., -10., -134., -101.).value(), Matchers.equalTo(-272.) ); MatcherAssert.assertThat( "Can't find the lowest mix double among many", new LowestOf<>(Double.MIN_VALUE, Double.MAX_VALUE).value(), Matchers.equalTo(Double.MIN_VALUE) ); MatcherAssert.assertThat( "Can't find the lowest min double among many", new LowestOf<>(Double.MIN_VALUE, 10.).value(), Matchers.equalTo(Double.MIN_VALUE) ); MatcherAssert.assertThat( "Can't find the lowest NaN (with min) double among many", new LowestOf<>(Double.NaN, Double.MIN_VALUE).value(), Matchers.equalTo(Double.MIN_VALUE) ); MatcherAssert.assertThat( "Can't find the lowest NaN (with max) double among many", new LowestOf<>(Double.NaN, Double.MAX_VALUE).value(), Matchers.equalTo(Double.MAX_VALUE) ); MatcherAssert.assertThat( "Can't find the lowest positive infinity among many", new LowestOf<>(Double.POSITIVE_INFINITY, Double.MAX_VALUE).value(), Matchers.equalTo(Double.MAX_VALUE) ); MatcherAssert.assertThat( "Can't find the lowest negative infinity among many", new LowestOf<>(Double.NEGATIVE_INFINITY, Double.MAX_VALUE).value(), Matchers.equalTo(Double.NEGATIVE_INFINITY) ); } @Test public void lowestStringAtIterable() throws Exception { MatcherAssert.assertThat( "Can't find the lowest string among many by scalars", new LowestOf( () -> "Banana", () -> "Apple", () -> "Orange" ).value(), Matchers.equalTo("Apple") ); MatcherAssert.assertThat( "Can't find the lowest string among many", new LowestOf<>("Banana", "Apple", "Orange").value(), Matchers.equalTo("Apple") ); } @Test public void lowestCharAtIterable() throws Exception { MatcherAssert.assertThat( "Can't find the lowest char among many by scalars", new LowestOf(() -> 'B', () -> 'U', () -> 'G').value(), Matchers.equalTo('B') ); MatcherAssert.assertThat( "Can't find the lowest char among many", new LowestOf<>('H', 'A', 'N', 'D').value(), Matchers.equalTo('A') ); } @Test public void lowestSumAtIterable() throws Exception { MatcherAssert.assertThat( "Can't find the lowest double sum among many", new LowestOf( new SumOf(1.0d), new SumOf(1.0d, 2.0d), new SumOf(1.0d, 2.0d, 3.0d) ).value(), Matchers.equalTo(new SumOf(1.0d).value()) ); } @Test public void lowestDateAtIterable() throws Exception { MatcherAssert.assertThat( "Can't find the lowest date among many", new LowestOf( new DateOf("2007-12-26T14:20:16.000000016Z"), new DateOf("2007-12-26T14:20:16.000000017Z"), new DateOf("2011-10-01T14:15:16.000000017Z") ).value(), Matchers.equalTo( new DateOf("2007-12-26T14:20:16.000000016Z").value() ) ); } @Test public void lowestBooleanAtIterable() throws Exception { MatcherAssert.assertThat( "Can't find the lowest boolean among many", new LowestOf( new BoolOf("false"), new BoolOf("true") ).value(), Matchers.equalTo(new BoolOf("false").value()) ); } } cactoos-0.49/src/test/java/org/cactoos/scalar/MappedTest.java000066400000000000000000000035751400054650300241770ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.scalar; import org.cactoos.Text; import org.cactoos.text.TextOf; import org.cactoos.text.Upper; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.ScalarHasValue; import org.llorllale.cactoos.matchers.TextIs; /** * Test case for {@link Mapped}. * * @since 0.43 * @checkstyle JavadocMethodCheck (500 lines) */ final class MappedTest { @Test void transformsScalar() throws Exception { new Assertion<>( "must transform scalar", new Mapped( input -> new Upper(new TextOf(input)), () -> "hello" ), new ScalarHasValue<>(new TextIs("HELLO")) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/scalar/MaxOfTest.java000066400000000000000000000302241400054650300237720ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.scalar; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.ScalarHasValue; /** * Test case for {@link MaxOf}. * * @since 0.10 * @checkstyle MagicNumberCheck (500 lines) */ @SuppressWarnings("PMD.TooManyMethods") final class MaxOfTest { @Test void withPositiveIntegerCollection() { new Assertion<>( "must select maximum integer of positive integers", () -> new MaxOf(1, 2, 3, 4).intValue(), new ScalarHasValue<>(4) ).affirm(); new Assertion<>( "must select maximum long of positive integers", () -> new MaxOf(1, 2, 3, 4).longValue(), new ScalarHasValue<>(4L) ).affirm(); new Assertion<>( "must select maximum double of positive integers", () -> new MaxOf(1, 2, 3, 4).doubleValue(), new ScalarHasValue<>(4.0d) ).affirm(); new Assertion<>( "must select maximum float of positive integers", () -> new MaxOf(1, 2, 3, 4).floatValue(), new ScalarHasValue<>(4.0f) ).affirm(); } @Test void withPositiveLongCollection() { new Assertion<>( "must select maximum integer of positive longs", () -> new MaxOf(1L, 2L, 3L, 4L).intValue(), new ScalarHasValue<>(4) ).affirm(); new Assertion<>( "must select maximum long of positive longs", () -> new MaxOf(1L, 2L, 3L, 4L).longValue(), new ScalarHasValue<>(4L) ).affirm(); new Assertion<>( "must select maximum double of positive longs", () -> new MaxOf(1L, 2L, 3L, 4L).doubleValue(), new ScalarHasValue<>(4.0d) ).affirm(); new Assertion<>( "must select maximum float of positive longs", () -> new MaxOf(1L, 2L, 3L, 4L).floatValue(), new ScalarHasValue<>(4.0f) ).affirm(); } @Test void withPositiveDoubleCollection() { new Assertion<>( "must select maximum integer of positive doubles", () -> new MaxOf(1.0d, 2.0d, 3.0d, 4.0d).intValue(), new ScalarHasValue<>(4) ).affirm(); new Assertion<>( "must select maximum long of positive doubles", () -> new MaxOf(1.0d, 2.0d, 3.0d, 4.0d).longValue(), new ScalarHasValue<>(4L) ).affirm(); new Assertion<>( "must select maximum double of positive doubles", () -> new MaxOf(1.0d, 2.0d, 3.0d, 4.0d).doubleValue(), new ScalarHasValue<>(4.0d) ).affirm(); new Assertion<>( "must select maximum float of positive doubles", () -> new MaxOf(1.0d, 2.0d, 3.0d, 4.0d).floatValue(), new ScalarHasValue<>(4.0f) ).affirm(); } @Test void withPositiveFloatCollection() { new Assertion<>( "must select maximum integer of positive floats", () -> new MaxOf(1.0f, 2.0f, 3.0f, 4.0f).intValue(), new ScalarHasValue<>(4) ).affirm(); new Assertion<>( "must select maximum long of positive floats", () -> new MaxOf(1.0f, 2.0f, 3.0f, 4.0f).longValue(), new ScalarHasValue<>(4L) ).affirm(); new Assertion<>( "must select maximum double of positive floats", () -> new MaxOf(1.0f, 2.0f, 3.0f, 4.0f).doubleValue(), new ScalarHasValue<>(4.0d) ).affirm(); new Assertion<>( "must select maximum float of positive floats", () -> new MaxOf(1.0f, 2.0f, 3.0f, 4.0f).floatValue(), new ScalarHasValue<>(4.0f) ).affirm(); } @Test void withNegativeIntegerCollection() { new Assertion<>( "must select maximum integer of negative integers", () -> new MaxOf(-1, -2, -3, -4).intValue(), new ScalarHasValue<>(-1) ).affirm(); new Assertion<>( "must select maximum long of negative integers", () -> new MaxOf(-1, -2, -3, -4).longValue(), new ScalarHasValue<>(-1L) ).affirm(); new Assertion<>( "must select maximum double of negative integers", () -> new MaxOf(-1, -2, -3, -4).doubleValue(), new ScalarHasValue<>(-1.0d) ).affirm(); new Assertion<>( "must select maximum float of negative integers", () -> new MaxOf(-1, -2, -3, -4).floatValue(), new ScalarHasValue<>(-1.0f) ).affirm(); } @Test void withNegativeLongCollection() { new Assertion<>( "must select maximum integer of negative longs", () -> new MaxOf(-1L, -2L, -3L, -4L).intValue(), new ScalarHasValue<>(-1) ).affirm(); new Assertion<>( "must select maximum long of negative longs", () -> new MaxOf(-1L, -2L, -3L, -4L).longValue(), new ScalarHasValue<>(-1L) ).affirm(); new Assertion<>( "must select maximum double of negative longs", () -> new MaxOf(-1L, -2L, -3L, -4L).doubleValue(), new ScalarHasValue<>(-1.0d) ).affirm(); new Assertion<>( "must select maximum float of negative longs", () -> new MaxOf(-1L, -2L, -3L, -4L).floatValue(), new ScalarHasValue<>(-1.0f) ).affirm(); } @Test void withNegativeDoubleCollection() { new Assertion<>( "must select maximum integer of negative doubles", () -> new MaxOf(-1.0d, -2.0d, -3.0d, -4.0d).intValue(), new ScalarHasValue<>(-1) ).affirm(); new Assertion<>( "must select maximum long of negative doubles", () -> new MaxOf(-1.0d, -2.0d, -3.0d, -4.0d).longValue(), new ScalarHasValue<>(-1L) ).affirm(); new Assertion<>( "must select maximum double of negative doubles", () -> new MaxOf(-1.0d, -2.0d, -3.0d, -4.0d).doubleValue(), new ScalarHasValue<>(-1.0d) ).affirm(); new Assertion<>( "must select maximum float of negative doubles", () -> new MaxOf(-1.0d, -2.0d, -3.0d, -4.0d).floatValue(), new ScalarHasValue<>(-1.0f) ).affirm(); } @Test void withNegativeFloatCollection() { new Assertion<>( "must select maximum integer of negative floats", () -> new MaxOf(-1.0f, -2.0f, -3.0f, -4.0f).intValue(), new ScalarHasValue<>(-1) ).affirm(); new Assertion<>( "must select maximum long of negative floats", () -> new MaxOf(-1.0f, -2.0f, -3.0f, -4.0f).longValue(), new ScalarHasValue<>(-1L) ).affirm(); new Assertion<>( "must select maximum double of negative floats", () -> new MaxOf(-1.0f, -2.0f, -3.0f, -4.0f).doubleValue(), new ScalarHasValue<>(-1.0d) ).affirm(); new Assertion<>( "must select maximum float of negative floats", () -> new MaxOf(-1.0f, -2.0f, -3.0f, -4.0f).floatValue(), new ScalarHasValue<>(-1.0f) ).affirm(); } @Test void withPositiveAndNegativeIntegerCollection() { new Assertion<>( "must select maximum integer of positive and negative integers", () -> new MaxOf(-2, -1, 0, 1, 2).intValue(), new ScalarHasValue<>(2) ).affirm(); new Assertion<>( "must select maximum long of positive and negative integers", () -> new MaxOf(-2, -1, 0, 1, 2).longValue(), new ScalarHasValue<>(2L) ).affirm(); new Assertion<>( "must select maximum double of positive and negative integers", () -> new MaxOf(-2, -1, 0, 1, 2).doubleValue(), new ScalarHasValue<>(2.0d) ).affirm(); new Assertion<>( "must select maximum float of positive and negative integers", () -> new MaxOf(-2, -1, 0, 1, 2).floatValue(), new ScalarHasValue<>(2.0f) ).affirm(); } @Test void withPositiveAndNegativeLongCollection() { new Assertion<>( "must select maximum integer of positive and negative longs", () -> new MaxOf(-2L, -1L, 0L, 1L, 2L).intValue(), new ScalarHasValue<>(2) ).affirm(); new Assertion<>( "must select maximum long of positive and negative longs", () -> new MaxOf(-2L, -1L, 0L, 1L, 2L).longValue(), new ScalarHasValue<>(2L) ).affirm(); new Assertion<>( "must select maximum double of positive and negative longs", () -> new MaxOf(-2L, -1L, 0L, 1L, 2L).doubleValue(), new ScalarHasValue<>(2.0d) ).affirm(); new Assertion<>( "must select maximum float of positive and negative longs", () -> new MaxOf(-2L, -1L, 0L, 1L, 2L).floatValue(), new ScalarHasValue<>(2.0f) ).affirm(); } @Test void withPositiveAndNegativeDoubleCollection() { new Assertion<>( "must select maximum integer of positive and negative doubles", () -> new MaxOf(-2.0d, -1.0d, 0.0d, 1.0d, 2.0d).intValue(), new ScalarHasValue<>(2) ).affirm(); new Assertion<>( "must select maximum long of positive and negative doubles", () -> new MaxOf(-2.0d, -1.0d, 0.0d, 1.0d, 2.0d).longValue(), new ScalarHasValue<>(2L) ).affirm(); new Assertion<>( "must select maximum double of positive and negative doubles", () -> new MaxOf(-2.0d, -1.0d, 0.0d, 1.0d, 2.0d).doubleValue(), new ScalarHasValue<>(2.0d) ).affirm(); new Assertion<>( "must select maximum float of positive and negative doubles", () -> new MaxOf(-2.0d, -1.0d, 0.0d, 1.0d, 2.0d).floatValue(), new ScalarHasValue<>(2.0f) ).affirm(); } @Test void withPositiveAndNegativeFloatCollection() { new Assertion<>( "must select maximum integer of positive and negative floats", () -> new MaxOf(-2.0f, -1.0f, 0.0f, 1.0f, 2.0f).intValue(), new ScalarHasValue<>(2) ).affirm(); new Assertion<>( "must select maximum long of positive and negative floats", () -> new MaxOf(-2.0f, -1.0f, 0.0f, 1.0f, 2.0f).longValue(), new ScalarHasValue<>(2L) ).affirm(); new Assertion<>( "must select maximum double of positive and negative floats", () -> new MaxOf(-2.0f, -1.0f, 0.0f, 1.0f, 2.0f).doubleValue(), new ScalarHasValue<>(2.0d) ).affirm(); new Assertion<>( "must select maximum float of positive and negative floats", () -> new MaxOf(-2.0f, -1.0f, 0.0f, 1.0f, 2.0f).floatValue(), new ScalarHasValue<>(2.0f) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/scalar/MinOfTest.java000066400000000000000000000113531400054650300237720ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.scalar; import org.cactoos.list.ListOf; import org.hamcrest.MatcherAssert; import org.hamcrest.Matchers; import org.junit.jupiter.api.Test; /** * Test case for {@link MinOf}. * * @since 0.10 * @checkstyle MagicNumberCheck (500 lines) */ final class MinOfTest { @Test void withIntegerCollection() { MatcherAssert.assertThat( new MinOf( new ListOf<>(1, 2, 3, 4).toArray(new Integer[4]) ).intValue(), Matchers.equalTo(1) ); MatcherAssert.assertThat( new MinOf( new ListOf<>(1, 2, 3, 4).toArray(new Integer[4]) ).longValue(), Matchers.equalTo(1L) ); MatcherAssert.assertThat( new MinOf( new ListOf<>(1, 2, 3, 4).toArray(new Integer[4]) ).doubleValue(), Matchers.equalTo(1.0d) ); MatcherAssert.assertThat( new MinOf( new ListOf<>(1, 2, 3, 4).toArray(new Integer[4]) ).floatValue(), Matchers.equalTo(1.0f) ); } @Test void withLongCollection() { MatcherAssert.assertThat( new MinOf( new ListOf<>(1L, 2L, 3L, 4L).toArray(new Long[4]) ).intValue(), Matchers.equalTo(1) ); MatcherAssert.assertThat( new MinOf( new ListOf<>(1L, 2L, 3L, 4L).toArray(new Long[4]) ).longValue(), Matchers.equalTo(1L) ); MatcherAssert.assertThat( new MinOf( new ListOf<>(1L, 2L, 3L, 4L).toArray(new Long[4]) ).doubleValue(), Matchers.equalTo(1.0d) ); MatcherAssert.assertThat( new MinOf( new ListOf<>(1L, 2L, 3L, 4L).toArray(new Long[4]) ).floatValue(), Matchers.equalTo(1.0f) ); } @Test void withDoubleCollection() { MatcherAssert.assertThat( new MinOf( new ListOf<>(1.0d, 2.0d, 3.0d, 4.0d).toArray(new Double[4]) ).intValue(), Matchers.equalTo(1) ); MatcherAssert.assertThat( new MinOf( new ListOf<>(1.0d, 2.0d, 3.0d, 4.0d).toArray(new Double[4]) ).longValue(), Matchers.equalTo(1L) ); MatcherAssert.assertThat( new MinOf( new ListOf<>(1.0d, 2.0d, 3.0d, 4.0d).toArray(new Double[4]) ).doubleValue(), Matchers.equalTo(1.0d) ); MatcherAssert.assertThat( new MinOf( new ListOf<>(1.0d, 2.0d, 3.0d, 4.0d).toArray(new Double[4]) ).floatValue(), Matchers.equalTo(1.0f) ); } @Test void withFloatCollection() { MatcherAssert.assertThat( new MinOf( new ListOf<>(1.0f, 2.0f, 3.0f, 4.0f).toArray(new Float[4]) ).intValue(), Matchers.equalTo(1) ); MatcherAssert.assertThat( new MinOf( new ListOf<>(1.0f, 2.0f, 3.0f, 4.0f).toArray(new Float[4]) ).longValue(), Matchers.equalTo(1L) ); MatcherAssert.assertThat( new MinOf( new ListOf<>(1.0f, 2.0f, 3.0f, 4.0f).toArray(new Float[4]) ).doubleValue(), Matchers.equalTo(1.0d) ); MatcherAssert.assertThat( new MinOf( new ListOf<>(1.0f, 2.0f, 3.0f, 4.0f).toArray(new Float[4]) ).floatValue(), Matchers.equalTo(1.0f) ); } } cactoos-0.49/src/test/java/org/cactoos/scalar/MultiplicationOfTest.java000066400000000000000000000113421400054650300262420ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.scalar; import org.cactoos.iterable.IterableOf; import org.hamcrest.core.IsEqual; import org.junit.Test; import org.llorllale.cactoos.matchers.Assertion; /** * Test case for {@link MultiplicationOf}. * * @since 0.49.2 * @checkstyle MagicNumberCheck (500 lines) */ @SuppressWarnings("PMD.TooManyMethods") public final class MultiplicationOfTest { /** * Ensures that multiplication of int numbers return proper value. */ @Test public void withListOfNumbersInt() { new Assertion<>( "Multiplication of int must return the appropriate value", new MultiplicationOf(2, 3).intValue(), new IsEqual<>(6) ).affirm(); } /** * Ensures that multiplication of double numbers return proper value. */ @Test public void withListOfNumbersDouble() { new Assertion<>( "Multiplication of double numbers must return proper value", new MultiplicationOf(2.0d, 2.5d, 3.0d).doubleValue(), new IsEqual<>(15.0d) ).affirm(); } /** * Ensures that multiplication of float numbers return proper value. */ @Test public void withListOfNumbersFloat() { new Assertion<>( "Multiplication of float numbers must return proper value", new MultiplicationOf(3.0f, 3.0f, 3.0f).floatValue(), new IsEqual<>(27.0f) ).affirm(); } /** * Ensures that multiplication of long numbers return proper value. */ @Test public void withListOfNumbersLong() { new Assertion<>( "Multiplication of long numbers must return proper value", new MultiplicationOf(2L, 3L, 2L).longValue(), new IsEqual<>(12L) ).affirm(); } /** * Ensures that multiplication of int numbers iterable return proper value. */ @Test public void withIterableInt() { new Assertion<>( "Multiplication of int numbers must return proper value", new MultiplicationOf( new IterableOf<>(2L, 3L, 3L) ).intValue(), new IsEqual<>(18) ).affirm(); } /** * Ensures that multiplication of long numbers iterable return proper value. */ @Test public void withIterableLong() { new Assertion<>( "Multiplication of long numbers iterable must return proper value", new MultiplicationOf( new IterableOf<>(1, 2, 3) ).longValue(), new IsEqual<>(6L) ).affirm(); } /** * Ensures that multiplication of float numbers iterable * return proper value. */ @Test public void withIterableFloat() { new Assertion<>( "Multiplication floating numbers must be iterable", new MultiplicationOf( new IterableOf<>(0.5f, 2.0f, 10.0f) ).floatValue(), new IsEqual<>(10.0f) ).affirm(); } /** * Ensures that multiplication of double numbers iterable * return proper value. */ @Test public void withIterableDouble() { new Assertion<>( "Multiplication double numbers must be iterable", new MultiplicationOf( new IterableOf<>(1.5d, 2.0d, 5.0d) ).doubleValue(), new IsEqual<>(15.0d) ).affirm(); } /** * Ensures that empty iterable will not be multiplied. */ @Test(expected = IllegalArgumentException.class) public void rejectsEmptyIterable() { new MultiplicationOf(new IterableOf<>()).doubleValue(); } } cactoos-0.49/src/test/java/org/cactoos/scalar/NotTest.java000066400000000000000000000035561400054650300235300ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.scalar; import org.hamcrest.core.IsEqual; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; /** * Test case for {@link Not}. * * @since 0.7 * @checkstyle JavadocMethodCheck (500 lines) */ final class NotTest { @Test void trueToFalse() throws Exception { new Assertion<>( "Must be changed from true to false", new Not(new True()).value(), new IsEqual<>(new False().value()) ).affirm(); } @Test void falseToTrue() throws Exception { new Assertion<>( "Must be changed from false to true", new Not(new False()).value(), new IsEqual<>(new True().value()) ); } } cactoos-0.49/src/test/java/org/cactoos/scalar/NumberOfTest.java000066400000000000000000000065701400054650300245040ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.scalar; import java.io.IOException; import org.hamcrest.Matchers; import org.hamcrest.core.IsEqual; import org.junit.Test; import org.llorllale.cactoos.matchers.Assertion; /** * Test case for {@link NumberOf}. * * @since 0.2 * @checkstyle JavadocMethodCheck (500 lines) * @checkstyle MagicNumber (500 lines) */ public final class NumberOfTest { @Test public void parsesFloat() throws IOException { new Assertion<>( "Must parse float number", new NumberOf("1656.894").floatValue(), Matchers.equalTo(1656.894F) ).affirm(); } @Test(expected = RuntimeException.class) public void failsIfTextDoesNotRepresentAFloat() throws IOException { new NumberOf("abcfds").floatValue(); } @Test public void parsesLong() throws IOException { new Assertion<>( "Must parse long number", new NumberOf("186789235425346").longValue(), Matchers.equalTo(186_789_235_425_346L) ).affirm(); } @Test(expected = RuntimeException.class) public void failsIfTextDoesNotRepresentALong() throws IOException { new NumberOf("abcddd").longValue(); } @Test public void parsesInteger() throws IOException { new Assertion<>( "Must parse integer number", new NumberOf("1867892354").intValue(), Matchers.equalTo(1_867_892_354) ).affirm(); } @Test(expected = RuntimeException.class) public void failsIfTextDoesNotRepresentAnInt() throws IOException { new NumberOf("abc fdsf").intValue(); } @Test public void parsesDouble() throws IOException { new Assertion<>( "Must parse double number", new NumberOf("185.65156465123").doubleValue(), Matchers.equalTo(185.65_156_465_123) ).affirm(); } @Test(expected = RuntimeException.class) public void failsIfTextDoesNotRepresentADouble() throws IOException { new NumberOf("abfdsc").doubleValue(); } @Test public void parsesValueInt() throws IOException { new Assertion<>( "Must parse into int", new NumberOf("185").intValue(), new IsEqual<>(185) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/scalar/OrTest.java000066400000000000000000000125121400054650300233400ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.scalar; import java.util.LinkedList; import java.util.List; import org.cactoos.Proc; import org.cactoos.Scalar; import org.cactoos.iterable.IterableOf; import org.hamcrest.MatcherAssert; import org.hamcrest.Matchers; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.ScalarHasValue; /** * Test case for {@link Or}. * * @since 0.8 * @checkstyle JavadocMethodCheck (500 lines) * @checkstyle MagicNumber (500 line) */ @SuppressWarnings("PMD.TooManyMethods") final class OrTest { @Test void allFalse() throws Exception { MatcherAssert.assertThat( new Or( new False(), new False(), new False(), new False(), new False() ), new ScalarHasValue<>(false) ); } @Test void oneTrue() throws Exception { MatcherAssert.assertThat( new Or( new False(), new True(), new False(), new False(), new False() ), new ScalarHasValue<>(true) ); } @Test void allTrue() throws Exception { MatcherAssert.assertThat( new Or( new IterableOf>( new True(), new True(), new True(), new True(), new True() ) ), new ScalarHasValue<>(true) ); } @Test void emptyIterator() throws Exception { MatcherAssert.assertThat( new Or(new IterableOf>()), new ScalarHasValue<>(false) ); } @Test void testProcIterable() throws Exception { final List list = new LinkedList<>(); new Or( (Proc) list::add, new IterableOf<>(1, 2, 3, 4) ).value(); MatcherAssert.assertThat( list, Matchers.contains(1, 2, 3, 4) ); } @Test void testProcIterator() throws Exception { final List list = new LinkedList<>(); new Or( (Proc) list::add, new IterableOf<>(1, 2, 3, 4) ).value(); MatcherAssert.assertThat( list, Matchers.contains(1, 2, 3, 4) ); } @Test void testProcVarargs() throws Exception { final List list = new LinkedList<>(); new Or( (Proc) list::add, 2, 3, 4 ).value(); MatcherAssert.assertThat( list, Matchers.contains(2, 3, 4) ); } @Test void testFuncIterable() throws Exception { MatcherAssert.assertThat( new Or( input -> input > 0, new IterableOf<>(-1, 1, 0) ), new ScalarHasValue<>(true) ); } @Test void testFuncIterator() throws Exception { MatcherAssert.assertThat( new Or( input -> input > 0, new IterableOf<>(-1, 1, 0) ), new ScalarHasValue<>(true) ); } @Test void testFuncVarargs() throws Exception { MatcherAssert.assertThat( new Or( input -> input > 0, -1, -2, 0 ), new ScalarHasValue<>(false) ); } @Test void testMultipleFuncConditionTrue() throws Exception { MatcherAssert.assertThat( "Can't compare subject with true conditions", new Or( 3, input -> input > 0, input -> input > 5, input -> input > 4 ), new ScalarHasValue<>(true) ); } @Test void testMultipleFuncConditionFalse() throws Exception { MatcherAssert.assertThat( "Can't compare subject with false conditions", new Or( "cactoos", input -> input.contains("singleton"), input -> input.contains("static") ), new ScalarHasValue<>(false) ); } } cactoos-0.49/src/test/java/org/cactoos/scalar/PropertiesOfTest.java000066400000000000000000000075631400054650300254130ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.scalar; import java.util.Properties; import org.cactoos.io.InputOf; import org.cactoos.map.MapEntry; import org.cactoos.map.MapOf; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.MatcherOf; import org.llorllale.cactoos.matchers.ScalarHasValue; /** * Test case for {@link PropertiesOf}. * * @since 0.7 * @checkstyle JavadocMethodCheck (500 lines) * @checkstyle ClassDataAbstractionCouplingCheck (500 lines) */ final class PropertiesOfTest { @Test void readsStringContent() { new Assertion<>( "Must read properties from an input string", new PropertiesOf( "foo=Hello, world!\nbar=works fine?\n" ), new ScalarHasValue<>( new MatcherOf( props -> { return "Hello, world!".equals( props.getProperty("foo") ); } ) ) ).affirm(); } @Test void readsInputContent() { new Assertion<>( "Must read properties from an input", new PropertiesOf( new InputOf("greet=Hello, inner world!\nask=works fine?\n") ), new ScalarHasValue<>( new MatcherOf( props -> { return "Hello, inner world!".equals( props.getProperty("greet") ); } ) ) ).affirm(); } @Test void convertsMapToProperties() { new Assertion<>( "Must convert map to properties", new PropertiesOf( new MapOf( new MapEntry<>(0, "hello, world"), new MapEntry<>(1, "how are you?") ) ), new ScalarHasValue<>( new MatcherOf( props -> { return props.getProperty("0").endsWith(", world"); } ) ) ).affirm(); } @Test void convertsMapEntriesToProperties() { new Assertion<>( "Must convert map entries to properties", new PropertiesOf( new MapEntry<>(0, "hello world"), new MapEntry<>(1, "How are you?") ), new ScalarHasValue<>( new MatcherOf( props -> { return props.getProperty("0").endsWith(" world"); } ) ) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/scalar/ReducedTest.java000066400000000000000000000071671400054650300243450ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.scalar; import java.util.Collections; import java.util.NoSuchElementException; import org.cactoos.Scalar; import org.cactoos.iterable.IterableOf; import org.junit.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.ScalarHasValue; /** * Test case for {@link Reduced}. * @since 0.30 * @checkstyle JavadocMethodCheck (500 lines) */ public final class ReducedTest { @Test(expected = NoSuchElementException.class) public void failsForEmptyIterable() throws Exception { new Reduced<>( (first, last) -> first, Collections.emptyList() ).value(); } @Test public void singleAtSingleIterable() { final Integer single = 10; new Assertion<>( "Must find the single", new Reduced<>( (first, last) -> first, new IterableOf>(() -> single) ), new ScalarHasValue<>(single) ).affirm(); } @Test public void firstAtIterable() { final String one = "Apple"; final String two = "Banana"; final String three = "Orange"; new Assertion<>( "Must find the first", new Reduced<>( (first, last) -> first, new IterableOf>( () -> one, () -> two, () -> three ) ), new ScalarHasValue<>(one) ).affirm(); } @Test public void lastAtIterable() { final Character one = 'A'; final Character two = 'B'; final Character three = 'O'; new Assertion<>( "Must find the last", new Reduced<>( (first, last) -> last, new IterableOf>( () -> one, () -> two, () -> three ) ), new ScalarHasValue<>(three) ).affirm(); } @Test public void constructedFromVarargs() { final String one = "One"; final String two = "Two"; final String three = "Three"; new Assertion<>( "Must concatenate the strings in vararg array", new Reduced( (first, last) -> first + last, one, two, three ), new ScalarHasValue<>("OneTwoThree") ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/scalar/RepeatedTest.java000066400000000000000000000050351400054650300245130ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.scalar; import java.util.concurrent.atomic.AtomicInteger; import org.hamcrest.core.IsEqual; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.Throws; /** * Test case for {@link Repeated}. * * @since 0.49.2 * @checkstyle MagicNumberCheck (100 line) * @checkstyle JavadocMethodCheck (100 lines) */ final class RepeatedTest { @Test void runsMultipleTimes() throws Exception { final AtomicInteger atom = new AtomicInteger(); new Assertion<>( "Must run scalar 3 times", new Repeated<>( () -> atom.incrementAndGet(), 3 ).value(), new IsEqual<>(3) ).affirm(); } @Test void throwsIfZero() { new Assertion<>( // @checkstyle LineLengthCheck (1 line) "Must throws an exception if number of repetitions not be at least 1", () -> new Repeated<>( new ScalarOf<>( () -> { throw new IllegalStateException("intended to fail"); }, "discarded" ), 0 ).value(), new Throws<>( "The number of repetitions must be at least 1", IllegalArgumentException.class ) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/scalar/RetryTest.java000066400000000000000000000113271400054650300240700ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.scalar; import java.security.SecureRandom; import java.time.Duration; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import org.hamcrest.Matchers; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.ScalarHasValue; /** * Test case for {@link Retry}. * * @since 0.9 * @checkstyle JavadocMethodCheck (500 lines) */ final class RetryTest { @Test void runsScalarMultipleTimes() throws Exception { new Assertion<>( "must retry in case of failure", new Retry<>( () -> { // @checkstyle MagicNumberCheck (1 line) if (new SecureRandom().nextDouble() > 0.3d) { throw new IllegalArgumentException("May happen"); } return 0; }, Integer.MAX_VALUE ), new ScalarHasValue<>(0) ).affirm(); } @Test void runsScalarTwiceWithDefaults() throws Exception { // @checkstyle MagicNumberCheck (1 line) final AtomicInteger tries = new AtomicInteger(0); new Assertion<>( "Should run twice with defaults", new Retry<>( () -> { // @checkstyle MagicNumberCheck (1 line) if (tries.getAndIncrement() <= 1) { throw new IllegalArgumentException("Not enough tries"); } return 0; } ), new ScalarHasValue<>(0) ).affirm(); } @Test void runsScalarMultipleTimesIgnoringNegativeDuration() throws Exception { // @checkstyle MagicNumberCheck (2 line) final int times = 2; final AtomicInteger tries = new AtomicInteger(0); new Assertion<>( "Should ignore negative duration", new Retry<>( () -> { if (tries.getAndIncrement() < times) { throw new IllegalArgumentException("Not yet"); } return 0; }, Integer.MAX_VALUE, // @checkstyle MagicNumberCheck (1 line) Duration.of(-5, ChronoUnit.DAYS) ), new ScalarHasValue<>(0) ).affirm(); } @Test @SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops") void runsScalarMultipleTimesWithWait() throws Exception { // @checkstyle MagicNumberCheck (3 line) final int times = 3; final long wait = 500; final AtomicInteger tries = new AtomicInteger(0); final List executions = new ArrayList<>(times); new Retry<>( () -> { if (tries.getAndIncrement() < times) { executions.add(Instant.now()); throw new IllegalArgumentException("Not done yet"); } return 0; }, Integer.MAX_VALUE, Duration.ofMillis(wait) ).value(); for (int position = 0; position < executions.size() - 1; position = position + 1) { final int actual = position; new Assertion<>( "Should wait the given time between attempts", executions.get(actual).plusMillis(wait), Matchers.lessThanOrEqualTo(executions.get(actual + 1)) ).affirm(); } } } cactoos-0.49/src/test/java/org/cactoos/scalar/ScalarEnvelopeTest.java000066400000000000000000000047061400054650300256710ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.scalar; import org.cactoos.Scalar; import org.hamcrest.core.IsEqual; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.ScalarHasValue; import org.llorllale.cactoos.matchers.Throws; /** * Test case for {@link ScalarEnvelope}. * * @since 0.41 * @checkstyle JavadocMethodCheck (500 lines) * @checkstyle JavadocTypeCheck (500 lines) */ final class ScalarEnvelopeTest { @Test void envelopeDelegatesCalls() { new Assertion<>( "must delegate calls to apply", new Static(1), new ScalarHasValue<>(1) ).affirm(); } @Test void propagatesException() { final String message = "ok"; final Scalar scalar = () -> { throw new UnsupportedOperationException(message); }; new Assertion<>( "must not alter the exception thrown by original Scalar", new ScalarEnvelope(scalar) { }, new Throws<>( new IsEqual<>(message), UnsupportedOperationException.class ) ).affirm(); } private static final class Static extends ScalarEnvelope { Static(final int result) { super(() -> result); } } } cactoos-0.49/src/test/java/org/cactoos/scalar/ScalarOfSupplierTest.java000066400000000000000000000032611400054650300261770ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.scalar; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.ScalarHasValue; /** * Test case for {@link ScalarOfSupplier}. * @since 0.47 */ final class ScalarOfSupplierTest { @Test void createsScalarFromSupplier() { final Object obj = new Object(); new Assertion<>( "must hold the same value as given by supplier", new ScalarOfSupplier<>(() -> obj), new ScalarHasValue<>(obj) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/scalar/ScalarOfTest.java000066400000000000000000000076351400054650300244640ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.scalar; import java.util.concurrent.atomic.AtomicReference; import org.cactoos.func.FuncOf; import org.cactoos.proc.ProcOf; import org.cactoos.proc.RunnableOf; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.MatcherOf; import org.llorllale.cactoos.matchers.ScalarHasValue; /** * Test case for {@link ScalarOf}. * * @since 0.48 * @checkstyle ClassDataAbstractionCouplingCheck (500 lines) */ @SuppressWarnings("PMD.AvoidDuplicateLiterals") final class ScalarOfTest { @Test void worksWithCallable() { final Object obj = new Object(); new Assertion<>( "Must convert Callable into Scalar", new ScalarOf<>(new CallableOf<>(new Constant<>(obj))), new ScalarHasValue<>(obj) ).affirm(); } @Test void worksWithRunnable() { final Object obj = new Object(); final Object result = new Object(); final AtomicReference done = new AtomicReference<>(); new Assertion<>( "Must convert Runnable into Scalar", new ScalarOf<>( new RunnableOf( () -> { done.set(result); } ), obj ), new MatcherOf<>( scalar -> { final Object res = scalar.value(); return res.equals(obj) && done.get().equals(result); } ) ).affirm(); } @Test void worksWithFunc() { final Object ipt = new Object(); new Assertion<>( "Must convert Func into Scalar", new ScalarOf<>(new FuncOf<>(input -> input), ipt), new ScalarHasValue<>(ipt) ).affirm(); } @Test void worksWithProc() { final Object ipt = new Object(); final Object result = new Object(); final AtomicReference done = new AtomicReference<>(); new Assertion<>( "Must convert Proc into Scalar", new ScalarOf<>( new ProcOf<>( input -> { done.set(input); } ), ipt, result ), new MatcherOf<>( scalar -> { final Object res = scalar.value(); return res.equals(result) && done.get().equals(ipt); } ) ).affirm(); } @Test void worksWithLambda() { final Object obj = new Object(); new Assertion<>( "Must convert Lambda into Scalar", new ScalarOf<>(() -> obj), new ScalarHasValue<>(obj) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/scalar/ScalarWithFallbackTest.java000066400000000000000000000165321400054650300264470ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.scalar; import java.io.IOException; import java.util.IllegalFormatException; import java.util.IllegalFormatWidthException; import org.cactoos.Fallback; import org.cactoos.iterable.IterableOf; import org.junit.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.ScalarHasValue; /** * Test case for {@link ScalarWithFallback}. * * @since 0.31 * @checkstyle JavadocMethodCheck (500 lines) * @checkstyle ClassDataAbstractionCouplingCheck (500 lines) */ @SuppressWarnings("unchecked") public final class ScalarWithFallbackTest { @Test public void usesMainFunc() throws Exception { final String message = "Main function's result #1"; new Assertion<>( "Must use the main function if no exception", new ScalarWithFallback<>( () -> message, new IterableOf<>( new Fallback.From<>( new IterableOf<>(IOException.class), Throwable::getMessage ) ) ), new ScalarHasValue<>(message) ).affirm(); } @Test public void usesMainFuncFromExceptionAndFallback() throws Exception { final String message = "Main function's result #1 (exp & flbck)"; new Assertion<>( "Using the main function if no exception (exp & flbck)", new ScalarWithFallback( () -> message, new Fallback.From<>( IOException.class, Throwable::getMessage ) ), new ScalarHasValue<>(message) ).affirm(); } @Test public void usesMainFuncFromIterableExceptionAndFallback() throws Exception { final String message = "Main function's result #1 (exp iterable & flbck)"; new Assertion<>( "Using the main function if no exception (exp iterable & flbck)", new ScalarWithFallback( () -> message, new Fallback.From<>( new IterableOf<>(IOException.class), Throwable::getMessage ) ), new ScalarHasValue<>(message) ).affirm(); } @Test public void usesFallback() throws Exception { final String message = "Fallback from IOException"; new Assertion<>( "Must use a single fallback in case of exception", new ScalarWithFallback<>( () -> { throw new IOException("Failure with IOException"); }, new IterableOf<>( new Fallback.From<>( new IterableOf<>(IOException.class), new Fallback.From<>( IOException.class, exp -> message ) ) ) ), new ScalarHasValue<>(message) ).affirm(); } @Test public void usesFallbackFromExceptionAndFallback() throws Exception { final String message = "Fallback from IOException (exp & flbck)"; new Assertion<>( "Using a single fallback in case of exception (exp & flbck)", new ScalarWithFallback( () -> { throw new IOException("Failure with IOException (exp & flbck)"); }, new Fallback.From<>( IOException.class, exp -> message ) ), new ScalarHasValue<>(message) ).affirm(); } @Test public void usesFallbackFromIterableExceptionAndFallback() throws Exception { final String message = "Fallback from IOException (exp iterable & flbck)"; new Assertion<>( "Using a single fallback in case of exception (exp iterable & flbck)", new ScalarWithFallback( () -> { throw new IOException("Failure with IOException (exp iterable & flbck)"); }, new Fallback.From<>( new IterableOf<>(IOException.class), exp -> message ) ), new ScalarHasValue<>(message) ).affirm(); } @Test public void usesFallbackOfInterruptedException() throws Exception { final String message = "Fallback from InterruptedException"; new Assertion<>( "Must use a fallback from Interrupted in case of exception", new ScalarWithFallback<>( () -> { throw new InterruptedException( "Failure with InterruptedException" ); }, new IterableOf<>( new Fallback.From<>( new IterableOf<>(InterruptedException.class), exp -> message ) ) ), new ScalarHasValue<>(message) ).affirm(); } @Test public void usesTheClosestFallback() throws Exception { final String expected = "Fallback from IllegalFormatException"; new Assertion<>( "Must find the closest fallback", new ScalarWithFallback<>( () -> { throw new IllegalFormatWidthException(1); }, new IterableOf<>( new Fallback.From<>( new IterableOf<>(IllegalArgumentException.class), exp -> "Fallback from IllegalArgumentException" ), new Fallback.From<>( new IterableOf<>(IllegalFormatException.class), exp -> expected ) ) ), new ScalarHasValue<>(expected) ).affirm(); } @Test(expected = Exception.class) public void noFallbackIsProvided() throws Exception { new ScalarWithFallback<>( () -> { throw new IllegalFormatWidthException(1); }, new IterableOf<>() ).value(); } } cactoos-0.49/src/test/java/org/cactoos/scalar/SealedTest.java000066400000000000000000000047571400054650300241710ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.scalar; import org.hamcrest.core.IsEqual; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; /** * Test case for {@link Sealed}. * * @since 1.0 * @checkstyle JavadocMethodCheck (500 lines) * @checkstyle MagicNumberCheck (500 lines) */ @SuppressWarnings("PMD.AvoidDuplicateLiterals") final class SealedTest { @Test void testInteger() { new Assertion<>( "Integer did not pass equality", new Sealed(100).intValue(), new IsEqual<>(100) ).affirm(); } @Test void testFloat() { new Assertion<>( "Float did not pass equality", new Sealed(100).floatValue(), new IsEqual<>(100.0f) ).affirm(); } @Test void testLong() { new Assertion<>( "Long did not pass equality", new Sealed(100).longValue(), new IsEqual<>(100L) ).affirm(); } @Test void testDouble() { new Assertion<>( "Double did not pass equality", new Sealed(100).doubleValue(), new IsEqual<>(100.0d) ).affirm(); } @Test void testFailed() { new Assertion<>( "Float did not pass equality", new Sealed(100).floatValue(), new IsEqual<>(100.0f) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/scalar/SolidTest.java000066400000000000000000000050761400054650300240410ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.scalar; import java.security.SecureRandom; import org.cactoos.Scalar; import org.cactoos.list.ListOf; import org.hamcrest.core.IsEqual; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.RunsInThreads; import org.llorllale.cactoos.matchers.ScalarHasValue; /** * Test case for {@link Solid}. * * @since 0.24 * @checkstyle JavadocMethodCheck (500 lines) * @checkstyle ClassDataAbstractionCouplingCheck (500 lines) */ final class SolidTest { @Test void cachesScalarResults() throws Exception { final Scalar scalar = new Solid<>( () -> new SecureRandom().nextInt() ); new Assertion<>( "must compute value only once", scalar.value() + scalar.value(), new IsEqual<>(scalar.value() + scalar.value()) ).affirm(); } @Test void worksInThreads() { new Assertion<>( "must work well in multiple threads", scalar -> { new Assertion<>( "must compute value once", scalar, new ScalarHasValue<>(scalar.value()) ).affirm(); return true; }, new RunsInThreads<>( new Unchecked<>( new Solid<>(() -> new ListOf<>(1, 2)) ) ) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/scalar/StickyTest.java000066400000000000000000000035131400054650300242270ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.scalar; import java.security.SecureRandom; import org.cactoos.Scalar; import org.hamcrest.core.IsEqual; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; /** * Test case for {@link Sticky}. * * @since 0.4 * @checkstyle JavadocMethodCheck (500 lines) */ final class StickyTest { @Test void cachesScalarResults() throws Exception { final Scalar scalar = new Sticky<>( () -> new SecureRandom().nextInt() ); new Assertion<>( "must compute value only once", scalar.value() + scalar.value(), new IsEqual<>(scalar.value() + scalar.value()) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/scalar/SumOfDoubleTest.java000066400000000000000000000041431400054650300251450ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.scalar; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.ScalarHasValue; /** * Test case for {@link SumOfDouble}. * * @since 0.30 * @checkstyle JavadocMethodCheck (500 lines) * @checkstyle MagicNumberCheck (500 lines) */ final class SumOfDoubleTest { @Test void withListOfScalarsInt() { new Assertion<>( "must sum scalars", new SumOfDouble(() -> 1.1, () -> 2.1, () -> 3.1), new ScalarHasValue<>(6.3) ).affirm(); } @Test void withEmptyList() { new Assertion<>( "must sum empty list to 0", new SumOfDouble(), new ScalarHasValue<>(0.0) ).affirm(); } @Test void withListOfOneElement() { new Assertion<>( "must sum singleton list", new SumOfDouble(() -> 5.1), new ScalarHasValue<>(5.1) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/scalar/SumOfFloatTest.java000066400000000000000000000041271400054650300250020ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.scalar; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.ScalarHasValue; /** * Test case for {@link SumOfFloat}. * * @since 0.30 * @checkstyle JavadocMethodCheck (500 lines) * @checkstyle MagicNumberCheck (500 lines) */ final class SumOfFloatTest { @Test void withListOfScalarsInt() { new Assertion<>( "must sum scalars", new SumOfFloat(() -> 1f, () -> 2f, () -> 3f), new ScalarHasValue<>(6f) ).affirm(); } @Test void withEmptyList() { new Assertion<>( "must sum empty list to 0", new SumOfFloat(), new ScalarHasValue<>(0f) ).affirm(); } @Test void withListOfOneElement() { new Assertion<>( "must sum singleton list", new SumOfFloat(() -> 5f), new ScalarHasValue<>(5f) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/scalar/SumOfIntTest.java000066400000000000000000000041061400054650300244640ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.scalar; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.ScalarHasValue; /** * Test case for {@link SumOfInt}. * * @since 0.30 * @checkstyle JavadocMethodCheck (500 lines) * @checkstyle MagicNumberCheck (500 lines) */ final class SumOfIntTest { @Test void withListOfScalarsInt() { new Assertion<>( "must sum scalars", new SumOfInt(() -> 1, () -> 2, () -> 3), new ScalarHasValue<>(6) ).affirm(); } @Test void withEmptyList() { new Assertion<>( "must sum empty list to 0", new SumOfInt(), new ScalarHasValue<>(0) ).affirm(); } @Test void withListOfOneElement() { new Assertion<>( "must sum singleton list", new SumOfInt(() -> 5), new ScalarHasValue<>(5) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/scalar/SumOfLongTest.java000066400000000000000000000041221400054650300246270ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.scalar; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.ScalarHasValue; /** * Test case for {@link SumOfLong}. * * @since 0.30 * @checkstyle JavadocMethodCheck (500 lines) * @checkstyle MagicNumberCheck (500 lines) */ final class SumOfLongTest { @Test void withListOfScalarsInt() { new Assertion<>( "must sum scalars", new SumOfLong(() -> 1L, () -> 2L, () -> 3L), new ScalarHasValue<>(6L) ).affirm(); } @Test void withEmptyList() { new Assertion<>( "must sum empty list to 0", new SumOfLong(), new ScalarHasValue<>(0L) ).affirm(); } @Test void withListOfOneElement() { new Assertion<>( "must sum singleton list", new SumOfLong(() -> 5L), new ScalarHasValue<>(5L) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/scalar/SumOfScalarTest.java000066400000000000000000000045131400054650300251410ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.scalar; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.ScalarHasValue; /** * Test case for {@link SumOfScalar}. * * @since 0.30 * @checkstyle JavadocMethodCheck (500 lines) * @checkstyle MagicNumberCheck (500 lines) */ final class SumOfScalarTest { @Test void withScalarsOfInt() { new Assertion<>( "should sum scalars of int", new Mapped<>( Number::intValue, new SumOfScalar(() -> 1, () -> 2, () -> 3) ), new ScalarHasValue<>(6) ).affirm(); } @Test void withNoScalar() { new Assertion<>( "should sum no scalars to 0", new Mapped<>( Number::intValue, new SumOfScalar() ), new ScalarHasValue<>(0) ).affirm(); } @Test void withListOfOneElement() { new Assertion<>( "should sum one scalars of int", new Mapped<>( Number::intValue, new SumOfScalar(() -> 5) ), new ScalarHasValue<>(5) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/scalar/SumOfTest.java000066400000000000000000000101311400054650300240040ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.scalar; import java.util.Collection; import org.cactoos.iterable.IterableOf; import org.cactoos.list.ListOf; import org.hamcrest.MatcherAssert; import org.hamcrest.core.IsEqual; import org.junit.jupiter.api.Test; /** * Test case for {@link SumOf}. * * @since 0.9 * @checkstyle JavadocMethodCheck (500 lines) * @checkstyle MagicNumberCheck (500 lines) */ @SuppressWarnings("PMD.TooManyMethods") final class SumOfTest { @Test void withListOfNumbersInt() { MatcherAssert.assertThat( new SumOf(1, 2, 3).intValue(), new IsEqual<>(6) ); } @Test void withListOfNumbersDouble() { MatcherAssert.assertThat( new SumOf(1.0d, 2.0d, 3.0d).doubleValue(), new IsEqual<>(6.0d) ); } @Test void withListOfNumbersFloat() { MatcherAssert.assertThat( new SumOf(1.0f, 2.0f, 3.0f).floatValue(), new IsEqual<>(6.0f) ); } @Test void withListOfNumbersLong() { MatcherAssert.assertThat( new SumOf(1L, 2L, 3L).longValue(), new IsEqual<>(6L) ); } @Test void withCollectionLong() { MatcherAssert.assertThat( new SumOf( new IterableOf<>(1, 2, 3, 4) ).longValue(), new IsEqual<>(10L) ); } @Test void withCollectionInt() { MatcherAssert.assertThat( new SumOf( new IterableOf<>(1L, 2L, 3L, 4L) ).intValue(), new IsEqual<>(10) ); } @Test void withCollectionFloat() { MatcherAssert.assertThat( new SumOf( new IterableOf<>(1.0f, 2.0f, 3.0f, 4.0f) ).floatValue(), new IsEqual<>(10.0f) ); } @Test void withCollectionDouble() { MatcherAssert.assertThat( new SumOf( new IterableOf<>(1.0d, 2.0d, 3.0d, 4.0d) ).doubleValue(), new IsEqual<>(10.0d) ); } @Test void withIterableOfInts() { final Collection ints = new ListOf<>(1, 2, 3, 4); MatcherAssert.assertThat( new SumOf(ints).intValue(), new IsEqual<>(10) ); } @Test void overflowIntFromLongValues() { MatcherAssert.assertThat( new SumOf(2_147_483_647L + 1L << 1, 10L).intValue(), new IsEqual<>(2_147_483_647) ); } @Test void overflowIntFromLongValuesIncludingNegative() { MatcherAssert.assertThat( new SumOf( 2_147_483_647L + 1L << 1, 10L, -(2_147_483_647L + 1L) << 1 ).intValue(), new IsEqual<>(10) ); } @Test void overflowFloatFromLongValues() { MatcherAssert.assertThat( new SumOf(2_147_483_647L + 1L << 1, 10L).floatValue(), new IsEqual<>(4_294_967_300.0f) ); } } cactoos-0.49/src/test/java/org/cactoos/scalar/SyncedTest.java000066400000000000000000000040251400054650300242050ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.scalar; import java.util.LinkedList; import java.util.List; import org.cactoos.Scalar; import org.hamcrest.core.IsEqual; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.RunsInThreads; /** * Test case for {@link Synced}. * * @since 0.24 * @checkstyle JavadocMethodCheck (500 lines) */ final class SyncedTest { @Test void worksInThreads() { final List list = new LinkedList<>(); final int threads = 100; new Assertion<>( "must work well in multiple threads", Scalar::value, new RunsInThreads<>( new Synced<>(() -> list.add(1)), threads ) ).affirm(); new Assertion<>( "must have correct size", list.size(), new IsEqual<>(threads) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/scalar/TernaryTest.java000066400000000000000000000107211400054650300244040ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.scalar; import java.util.concurrent.atomic.AtomicInteger; import org.cactoos.iterable.IterableOf; import org.cactoos.text.FormattedText; import org.cactoos.text.TextOf; import org.hamcrest.core.AllOf; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.ScalarHasValue; /** * Test case for {@link Ternary}. * @since 0.8 * @checkstyle JavadocMethodCheck (500 lines) * @checkstyle MagicNumberCheck (500 lines) * @checkstyle ClassDataAbstractionCouplingCheck (500 lines) */ final class TernaryTest { @Test void conditionTrueScalar() throws Exception { new Assertion<>( "Must work with true scalar condition", new Ternary<>( new True(), 6, 16 ), new ScalarHasValue<>(6) ).affirm(); } @Test void conditionFalseScalar() throws Exception { new Assertion<>( "Must work with false scalar condition", new Ternary<>( new False(), 6, 16 ), new ScalarHasValue<>(16) ).affirm(); } @Test void conditionStatic() throws Exception { new Assertion<>( "Must work with primitive static condition", new Ternary<>( true, 6, 16 ), new ScalarHasValue<>(6) ).affirm(); } @Test void consequentScalar() throws Exception { new Assertion<>( "Must work with scalar consequent and alternative", new Ternary<>( true, new Constant<>(6), new Constant<>(16) ), new ScalarHasValue<>(6) ).affirm(); } @Test void inputStatic() throws Exception { new Assertion<>( "Must call the functions with the input", new Ternary<>( 5, input -> input > 3, input -> input + 1, input -> input + 2 ), new ScalarHasValue<>(6) ).affirm(); } @Test void inputScalar() throws Exception { new Assertion<>( "Must call the functions with the input scalar value", new Ternary<>( new Constant<>(5), (Integer input) -> input > 3, input -> input + 1, input -> input + 2 ), new ScalarHasValue<>(6) ).affirm(); } @Test @SuppressWarnings("unchecked") void inputScalarValueConserved() throws Exception { new Assertion<>( "Must conserve the same scalar value for each whole evaluation", new Ternary<>( new ScalarOf<>(new AtomicInteger(0)::incrementAndGet), (Integer i) -> i == 1, i -> new FormattedText("%d equals 1", i), i -> new FormattedText("else: %d", i) ), new AllOf<>( new IterableOf<>( new ScalarHasValue<>(new TextOf("1 equals 1")), new ScalarHasValue<>(new TextOf("else: 2")), new ScalarHasValue<>(new TextOf("else: 3")) ) ) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/scalar/TrueTest.java000066400000000000000000000031321400054650300236750ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.scalar; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.IsTrue; /** * Test case for {@link True}. * * @since 0.7 * @checkstyle JavadocMethodCheck (500 lines) */ final class TrueTest { @Test void asValue() throws Exception { new Assertion<>( "Must be True", new True().value(), new IsTrue() ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/scalar/UncheckedTest.java000066400000000000000000000031721400054650300246530ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.scalar; import java.io.IOException; import java.io.UncheckedIOException; import org.junit.Test; /** * Test case for {@link Unchecked}. * * @since 0.3 * @checkstyle JavadocMethodCheck (500 lines) */ public final class UncheckedTest { @Test(expected = UncheckedIOException.class) public void rethrowsCheckedToUncheckedException() { new Unchecked<>( () -> { throw new IOException("intended"); } ).value(); } } cactoos-0.49/src/test/java/org/cactoos/scalar/XorTest.java000066400000000000000000000110511400054650300235250ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.scalar; import org.cactoos.Scalar; import org.cactoos.iterable.IterableOf; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.ScalarHasValue; /** * Test case for {@link Xor}. * @since 0.48 */ @SuppressWarnings({"PMD.AvoidDuplicateLiterals", "PMD.TooManyMethods"}) final class XorTest { @Test void trueTrue() throws Exception { new Assertion<>( "Either one, but not both nor none", new Xor( new True(), new True() ), new ScalarHasValue<>(false) ).affirm(); } @Test void falseTrue() throws Exception { new Assertion<>( "Either one, but not both nor none", new Xor( new False(), new True() ), new ScalarHasValue<>(true) ).affirm(); } @Test void treuFalse() throws Exception { new Assertion<>( "Either one, but not both nor none", new Xor( new True(), new False() ), new ScalarHasValue<>(true) ).affirm(); } @Test void falseFalse() throws Exception { new Assertion<>( "Either one, but not both nor none", new Xor( new False(), new False() ), new ScalarHasValue<>(false) ).affirm(); } @Test void singleTrue() throws Exception { new Assertion<>( "Single True must be True", new Xor( new True() ), new ScalarHasValue<>(true) ).affirm(); } @Test void singleFalse() throws Exception { new Assertion<>( "Single False must be False", new Xor( new False() ), new ScalarHasValue<>(false) ).affirm(); } @Test void emptyIterable() throws Exception { new Assertion<>( "Empty iterable must be False", new Xor(new IterableOf>()), new ScalarHasValue<>(false) ).affirm(); } @Test void oddNumberOfTrue() throws Exception { new Assertion<>( "Odd number of True must be True", new Xor( new False(), new False(), new True() ), new ScalarHasValue<>(true) ).affirm(); } @Test void evenNumberOfTrue() throws Exception { new Assertion<>( "Even number of True must be False", new Xor( new False(), new True(), new True() ), new ScalarHasValue<>(false) ).affirm(); } @Test void allFalse() throws Exception { new Assertion<>( "All False must be False", new Xor( new False(), new False(), new False() ), new ScalarHasValue<>(false) ).affirm(); } @Test void allTrue() throws Exception { new Assertion<>( "Odd number of True must be True", new Xor( new True(), new True(), new True() ), new ScalarHasValue<>(true) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/scalar/package-info.java000066400000000000000000000023141400054650300244430ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ /** * Scalars, tests. * * @since 0.12 */ package org.cactoos.scalar; cactoos-0.49/src/test/java/org/cactoos/set/000077500000000000000000000000001400054650300206025ustar00rootroot00000000000000cactoos-0.49/src/test/java/org/cactoos/set/BehavesAsSet.java000066400000000000000000000051261400054650300237660ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.set; import java.util.Iterator; import java.util.Set; import org.cactoos.collection.BehavesAsCollection; import org.hamcrest.Description; import org.hamcrest.TypeSafeMatcher; import org.hamcrest.core.IsEqual; import org.llorllale.cactoos.matchers.Assertion; /** * Matcher for set. * * @param Type of source sample * @since 0.49.2 */ public final class BehavesAsSet extends TypeSafeMatcher> { /** * Sample sample. */ private final T sample; /** * Ctor. * @param item Sample sample */ public BehavesAsSet(final T item) { super(); this.sample = item; } @Override public boolean matchesSafely(final Set item) { new Assertion<>( "Does not contain duplicates", this.occurrences(item.iterator()), new IsEqual<>(1) ).affirm(); return new BehavesAsCollection<>(this.sample).matchesSafely(item); } @Override public void describeTo(final Description description) { description.appendText("not a valid set"); } /** * Occurrences of sample in iterator. * @param iterator Set iterator * @return Occurrences */ private int occurrences(final Iterator iterator) { int occurrences = 0; while (iterator.hasNext()) { if (this.sample.equals(iterator.next())) { ++occurrences; } } return occurrences; } } cactoos-0.49/src/test/java/org/cactoos/set/SetOfTest.java000066400000000000000000000145321400054650300233320ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.set; import org.cactoos.iterable.IterableOf; import org.cactoos.iterable.Joined; import org.cactoos.text.TextOf; import org.hamcrest.Matcher; import org.hamcrest.core.AllOf; import org.hamcrest.core.IsCollectionContaining; import org.hamcrest.core.IsEqual; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.HasSize; /** * Test case for {@link SetOf}. * @since 0.49.2 * @checkstyle MagicNumber (500 line) * @checkstyle JavadocMethodCheck (500 lines) * @checkstyle ClassDataAbstractionCouplingCheck (500 lines) */ @SuppressWarnings("PMD.AvoidDuplicateLiterals") final class SetOfTest { @Test void behaveAsSetWithOriginalDuplicationsInTheTail() { new Assertion<>( "Must keep unique integer numbers", new SetOf<>(1, 2, 2), new AllOf<>( new IterableOf>>( new HasSize(2), new IsCollectionContaining<>(new IsEqual<>(1)), new IsCollectionContaining<>(new IsEqual<>(2)) ) ) ).affirm(); } @Test void behaveAsSetWithOriginalDuplicationsInTheHead() { new Assertion<>( "Must keep unique integer numbers", new SetOf<>(1, 1, 2, 3), new AllOf<>( new IterableOf>>( new HasSize(3), new IsCollectionContaining<>(new IsEqual<>(1)), new IsCollectionContaining<>(new IsEqual<>(2)), new IsCollectionContaining<>(new IsEqual<>(3)) ) ) ).affirm(); } @Test void behaveAsSetWithOriginalDuplicationsInTheMiddle() { new Assertion<>( "Must keep unique integer numbers", new SetOf<>(1, 2, 2, 3), new AllOf<>( new IterableOf>>( new HasSize(3), new IsCollectionContaining<>(new IsEqual<>(1)), new IsCollectionContaining<>(new IsEqual<>(2)), new IsCollectionContaining<>(new IsEqual<>(3)) ) ) ).affirm(); } @Test void behaveAsSetMergedCollectionsOfLiteralsWithDuplicates() { new Assertion<>( "Must keep unique string literals", new SetOf( new Joined( new IterableOf<>("cc", "ff"), new IterableOf<>("aa", "bb", "cc", "dd") ) ), new AllOf<>( new IterableOf>>( new HasSize(5), new IsCollectionContaining<>(new IsEqual<>("aa")), new IsCollectionContaining<>(new IsEqual<>("bb")), new IsCollectionContaining<>(new IsEqual<>("cc")), new IsCollectionContaining<>(new IsEqual<>("dd")), new IsCollectionContaining<>(new IsEqual<>("ff")) ) ) ).affirm(); } @Test void behaveAsSetWithOriginalDuplicationsOfCharsInTheMiddle() { new Assertion<>( "Must keep unique characters", new SetOf<>('a', 'b', 'b', 'c', 'a', 'b', 'd'), new AllOf<>( new IterableOf>>( new HasSize(4), new IsCollectionContaining<>(new IsEqual<>('a')), new IsCollectionContaining<>(new IsEqual<>('b')), new IsCollectionContaining<>(new IsEqual<>('c')), new IsCollectionContaining<>(new IsEqual<>('d')) ) ) ).affirm(); } @Test void behaveAsSetWithOriginalDuplicationsOfDoublesInTheMiddle() { new Assertion<>( "Must keep unique double numbers", new SetOf<>(1.5d, 2.4d, 1.5d, 2.4d, 2.4d, 1.5d), new AllOf<>( new IterableOf>>( new HasSize(2), new IsCollectionContaining<>(new IsEqual<>(1.5d)), new IsCollectionContaining<>(new IsEqual<>(2.4d)) ) ) ).affirm(); } @Test void behaveAsSetWithOriginalDuplicationsOfTextsInTheMiddle() { new Assertion<>( "Must keep unique TextOf objects", new SetOf<>( new TextOf("12345"), new TextOf("67890"), new TextOf("12345"), new TextOf("00000") ), new AllOf<>( new IterableOf>>( new HasSize(3), new IsCollectionContaining<>( new IsEqual<>(new TextOf("12345")) ), new IsCollectionContaining<>( new IsEqual<>(new TextOf("67890")) ), new IsCollectionContaining<>( new IsEqual<>(new TextOf("00000")) ) ) ) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/set/SortedTest.java000066400000000000000000000160551400054650300235540ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.set; import java.util.Comparator; import org.cactoos.Text; import org.cactoos.list.ListOf; import org.cactoos.text.TextOf; import org.cactoos.text.UncheckedText; import org.hamcrest.Matcher; import org.hamcrest.collection.IsIterableContainingInOrder; import org.hamcrest.core.IsEqual; import org.hamcrest.core.IsNot; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.TextIs; /** * Test case for {@link Sorted}. * @since 1.0.0 * @checkstyle MagicNumber (500 line) * @checkstyle JavadocMethodCheck (500 lines) * @checkstyle ClassDataAbstractionCouplingCheck (500 lines) */ @SuppressWarnings( { "PMD.AvoidDuplicateLiterals", "PMD.TooManyMethods" } ) final class SortedTest { @Test @SuppressWarnings("unchecked") void mustSortIntegerArrayAsSetInAscendingOrder() { new Assertion<>( "Must keep unique integer numbers sorted", new Sorted( Integer::compareTo, 2, 1, 3, 2, 1 ), new IsIterableContainingInOrder( new ListOf<>( new IsEqual<>(1), new IsEqual<>(2), new IsEqual<>(3) ) ) ).affirm(); } @Test @SuppressWarnings("unchecked") void mustSortIntegerIterableAsSetInDescendingOrder() { new Assertion<>( "Must keep unique integer numbers sorted in descending order", new Sorted( Comparator.reverseOrder(), 2, 1, 3, 2, 1 ), new IsIterableContainingInOrder( new ListOf<>( new IsEqual<>(3), new IsEqual<>(2), new IsEqual<>(1) ) ) ).affirm(); } @Test @SuppressWarnings("unchecked") void mustSortTextIterableAsSetUsingCustomCOmparator() { new Assertion<>( "Must keep unique integer numbers sorted in descending order", new Sorted( (first, second) -> { final String left = new UncheckedText(first).asString(); final String right = new UncheckedText(second).asString(); return left.compareTo(right); }, new TextOf("cd"), new TextOf("ab"), new TextOf("gh"), new TextOf("ef") ), new IsIterableContainingInOrder( new ListOf<>( new TextIs("ab"), new TextIs("cd"), new TextIs("ef"), new TextIs("gh") ) ) ).affirm(); } @Test @SuppressWarnings("unchecked") void mustNotBeEqualToSortedSet() { new Assertion<>( "Sorted set must not be equal to the tested collection", new Sorted( Integer::compareTo, 2, 1, 3, 2, 1 ), new IsNot<>( new IsIterableContainingInOrder( new ListOf<>( new IsEqual<>(1), new IsEqual<>(3), new IsEqual<>(2) ) ) ) ).affirm(); } @Test void returnsCorrectComparator() { final Comparator comparator = Integer::compareTo; new Assertion<>( "Comparator must be the same", new Sorted<>(comparator, 1, 2, 3).comparator(), new IsEqual<>(comparator) ).affirm(); } @Test void returnsSubset() { new Assertion<>( "Must return sorted subset", new Sorted<>(Integer::compareTo, 3, 6, 1, 9, 3).subSet(3, 9), new IsIterableContainingInOrder<>( new ListOf>( new IsEqual<>(3), new IsEqual<>(6) ) ) ).affirm(); } @Test void returnsHeadset() { new Assertion<>( "Must return sorted headset", new Sorted<>(Integer::compareTo, 3, 6, 1, 9, 3).headSet(9), new IsIterableContainingInOrder<>( new ListOf>( new IsEqual<>(1), new IsEqual<>(3), new IsEqual<>(6) ) ) ).affirm(); } @Test void returnsTailset() { new Assertion<>( "Must return sorted tailset", new Sorted<>(Integer::compareTo, 3, 6, 1, 9, 3).tailSet(6), new IsIterableContainingInOrder<>( new ListOf>( new IsEqual<>(6), new IsEqual<>(9) ) ) ).affirm(); } @Test void returnsFirst() { new Assertion<>( "Must return first element", new Sorted<>(Integer::compareTo, 3, 6, 1, 9, 3).first(), new IsEqual<>(1) ).affirm(); } @Test void returnsLast() { new Assertion<>( "Must return last element", new Sorted<>(Integer::compareTo, 3, 6, 1, 9, 3).last(), new IsEqual<>(9) ).affirm(); } @Test void mustSortIntegersByNumberComparator() { new Assertion<>( "Must keep unique integer numbers sorted", new Sorted( Comparator.comparing(Number::intValue), 2, 1, 3, 2, 1 ), new IsIterableContainingInOrder<>( new ListOf>( new IsEqual<>(1), new IsEqual<>(2), new IsEqual<>(3) ) ) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/set/package-info.java000066400000000000000000000023101400054650300237650ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ /** * Sets, tests. * * @since 0.49.2 */ package org.cactoos.set; cactoos-0.49/src/test/java/org/cactoos/text/000077500000000000000000000000001400054650300207735ustar00rootroot00000000000000cactoos-0.49/src/test/java/org/cactoos/text/AbbreviatedTest.java000066400000000000000000000117571400054650300247210ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.text; import java.util.concurrent.atomic.AtomicInteger; import org.cactoos.Text; import org.cactoos.iterable.IterableOf; import org.hamcrest.core.AllOf; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.TextIs; /** * Test case for {@link Abbreviated}. * @since 0.29 * @checkstyle JavadocMethodCheck (500 lines) * @checkstyle MagicNumberCheck (500 lines) * @checkstyle ClassDataAbstractionCouplingCheck (500 lines) */ @SuppressWarnings("PMD.TooManyMethods") final class AbbreviatedTest { @Test void abbreviatesAnEmptyText() { final String msg = ""; new Assertion<>( "Must abbreviate an msg text", new Abbreviated(msg, 8), new TextIs(msg) ).affirm(); } @Test void abbreviatesText() { new Assertion<>( "Must abbreviate a text", new Abbreviated("hello world", 8), new TextIs("hello...") ).affirm(); } @Test void abbreviatesTextOneCharSmaller() { new Assertion<>( "Must abbreviate a text one char smaller", new Abbreviated("oo programming", 10), new TextIs("oo prog...") ).affirm(); } @Test void abbreviatesTextWithSameLength() { final String msg = "elegant objects"; new Assertion<>( "Must abbreviate a text with same length", new Abbreviated(msg, 15), new TextIs(msg) ).affirm(); } @Test void abbreviatesTextOneCharBigger() { final String msg = "the old mcdonald"; new Assertion<>( "Must abbreviate a text one char bigger", new Abbreviated(msg, 17), new TextIs(msg) ).affirm(); } @Test void abbreviatesTextTwoCharsBigger() { final String msg = "hi everybody!"; new Assertion<>( "Must abbreviate a text two chars bigger", new Abbreviated(msg, 15), new TextIs(msg) ).affirm(); } @Test void abbreviatesTextWithWidthBiggerThanLength() { final String msg = "cactoos framework"; new Assertion<>( "Must abbreviate a text with width bigger than length", new Abbreviated(msg, 50), new TextIs(msg) ).affirm(); } @Test void abbreviatesTextBiggerThanDefaultMaxWidth() { new Assertion<>( "Must abbreviate a text bigger than default max width", new Abbreviated( // @checkstyle LineLengthCheck (1 line) "The quick brown fox jumps over the lazy black dog and after that returned to the cave" ), new TextIs( // @checkstyle LineLengthCheck (1 line) "The quick brown fox jumps over the lazy black dog and after that returned to ..." ) ).affirm(); } @Test @SuppressWarnings("unchecked") void abbreviatesTextThatChanges() { final AtomicInteger counter = new AtomicInteger(0); final Text txt = new TextOf( () -> { final String result; if (counter.getAndIncrement() == 0) { result = "The quick brown fox jumps"; } else { result = "The lazy black dog"; } return result; } ); new Assertion<>( "Must abbreviate a text that changes", new Abbreviated( txt, 15 ), new AllOf<>( new IterableOf<>( new TextIs( "The quick br..." ), new TextIs( "The lazy bla..." ) ) ) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/text/Base64DecodedTest.java000066400000000000000000000035271400054650300250010ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.text; import java.io.IOException; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.TextHasString; /** * Test Case for {@link Base64Decoded}. * * @since 0.20.2 */ final class Base64DecodedTest { /** * Check text decodes using the Base64 encoding scheme. * @throws IOException If fails. */ @Test void checkDecode() throws IOException { new Assertion<>( "Can't decodes text using the Base64 encoding scheme", new Base64Decoded( "SGVsbG8h" ), new TextHasString( "Hello!" ) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/text/Base64EncodedTest.java000066400000000000000000000035251400054650300250110ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.text; import java.io.IOException; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.TextHasString; /** * Test case for {@link Base64Encoded}. * @since 0.20.2 */ final class Base64EncodedTest { /** * Check text encodes using the Base64 encoding scheme. * @throws IOException If fails. */ @Test void checkEncode() throws IOException { new Assertion<>( "Can't encodes text using the Base64 encoding scheme", new Base64Encoded( "Hello!" ), new TextHasString( "SGVsbG8h" ) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/text/CapitalizedTest.java000066400000000000000000000060071400054650300247320ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.text; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.TextIs; /** * Test case for {@link Capitalized}. * @since 0.46 */ @SuppressWarnings("PMD.AvoidDuplicateLiterals") final class CapitalizedTest { @Test void capitalizeEmptyText() { new Assertion<>( "Must capitalize an empty text", new Capitalized(new TextOf("")), new TextIs("") ).affirm(); } @Test void capitalizeSingleLowerCaseText() { new Assertion<>( "Must capitalize single lower case text", new Capitalized(new TextOf("f")), new TextIs("F") ).affirm(); } @Test void capitalizeSingleUpperCaseText() { new Assertion<>( "Must capitalize single upper case text", new Capitalized(new TextOf("F")), new TextIs("F") ).affirm(); } @Test void capitalizeTextStartingWithUpperCaseCharacter() { new Assertion<>( "Must capitalize text starting with upper case character", new Capitalized("Bar"), new TextIs("Bar") ).affirm(); } @Test void capitalizeTextStartingWithLowerCaseCharacter() { new Assertion<>( "Must capitalize text starting with lower case character", new Capitalized(new TextOf("xyz")), new TextIs("Xyz") ).affirm(); } @Test void capitalizeTextWithUnicodeCharacter() { new Assertion<>( "Must capitalize unicode character dž", new Capitalized("dž"), new TextIs("Dž") ).affirm(); } @Test void capitalizeString() { new Assertion<>( "Must capitalize string", new Capitalized("foo"), new TextIs("Foo") ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/text/ComparableTextTest.java000066400000000000000000000111321400054650300254060ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.text; import org.cactoos.Text; import org.hamcrest.core.IsEqual; import org.hamcrest.core.IsNot; import org.junit.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.TextIs; /** * Test case for {@link FormattedText}. * * @since 0.27 * @checkstyle JavadocMethodCheck (100 lines) * @checkstyle ClassDataAbstractionCouplingCheck (500 lines) */ public final class ComparableTextTest { @Test public void comparesWithASubtext() { new Assertion<>( "Can't compare sub texts", new ComparableText( new TextOf( "here to there" ) ).compareTo( // @checkstyle MagicNumberCheck (2 lines) new ComparableText( new Sub("from here to there", 5) ) ), new IsEqual<>(0) ).affirm(); } @Test public void comparesToUncheckedText() { final String txt = "foobar"; new Assertion<>( "These UncheckedText are not equal", new ComparableText( new UncheckedText( new TextOf(txt) ) ).compareTo( new ComparableText(new TextOf(txt)) ), new IsEqual<>(0) ).affirm(); } @Test public void equalsToItself() { final Text text = new TextOf("text"); new Assertion<>( "Does not equal to itself", text, new TextIs(text) ).affirm(); } @Test public void equalsAndHashCodeOfComparableOfTheSameText() { final Text text = new TextOf("my text"); final Text actual = new ComparableText(text); final Text expected = new ComparableText(text); new Assertion<>( "Does not equal to a comparable text made from the same Text", actual, new IsEqual<>(expected) ).affirm(); new Assertion<>( "Hash codes of the equal objects are not equal", actual.hashCode(), new IsEqual<>( expected.hashCode() ) ).affirm(); } @Test public void equalsOfDifferentText() { final Text text = new ComparableText( new TextOf("my value") ); new Assertion<>( "Is equal to the completely different object", text, new IsNot<>( new IsEqual<>( "The string is ignored" ) ) ).affirm(); new Assertion<>( "Is equal to the completely different text", text, new IsNot<>( new TextIs( "The text is ignored" ) ) ).affirm(); new Assertion<>( "Is equal to the different ComparableText", text, new IsNot<>( new IsEqual<>( new ComparableText( new TextOf("A different text") ) ) ) ).affirm(); new Assertion<>( "The string is equal to the different ComparableText", text, new IsNot<>( new TextIs( new ComparableText( new TextOf("A different value") ) ) ) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/text/ConctatenatedTest.java000066400000000000000000000051121400054650300252510ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.text; import org.cactoos.iterable.IterableOf; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.TextIs; /** * Test case for {@link Concatenated}. * @since 0.47 */ @SuppressWarnings("PMD.AvoidDuplicateLiterals") final class ConctatenatedTest { @Test void contatenateText() { new Assertion<>( "Must contcatenate single text", new Concatenated(new TextOf("bar")), new TextIs("bar") ).affirm(); } @Test void contatenateTexts() { new Assertion<>( "Must contcatenate multi texts", new Concatenated(new TextOf("abc"), new TextOf("xyz")), new TextIs("abcxyz") ).affirm(); } @Test void concatenateIterables() { new Assertion<>( "Must concatenate iterables", new Concatenated(new IterableOf<>(new TextOf("foo"), new TextOf("foo1"))), new TextIs("foofoo1") ).affirm(); } @Test void contatenateString() { new Assertion<>( "Must contcatenate single string", new Concatenated("bar"), new TextIs("bar") ).affirm(); } @Test void contatenateStrings() { new Assertion<>( "Must contcatenate multi strings", new Concatenated("abc", "xyz"), new TextIs("abcxyz") ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/text/ContainsTest.java000066400000000000000000000074241400054650300242630ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.text; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.ScalarHasValue; /** * Test case for {@link Contains}. * @since 1.0 * @checkstyle JavadocMethodCheck (500 lines) */ final class ContainsTest { @Test void textContainsText() { new Assertion<>( "Text contains other Text", new Contains( new TextOf("Elegant Object"), new TextOf("Elegant") ), new ScalarHasValue<>(Boolean.TRUE) ).affirm(); } @Test void textDoesNotContainText() { new Assertion<>( "Text does not contain other Text", new Contains( new TextOf("Java is awesome"), new TextOf("good") ), new ScalarHasValue<>(Boolean.FALSE) ).affirm(); } @Test void textContainsString() { new Assertion<>( "Text contains other String", new Contains( new TextOf("The quick brown fox"), "fox" ), new ScalarHasValue<>(Boolean.TRUE) ).affirm(); } @Test void textDoesNotContainString() { new Assertion<>( "Text does not contain other String", new Contains( new TextOf("Stack Overflow"), "nope" ), new ScalarHasValue<>(Boolean.FALSE) ).affirm(); } @Test void stringContainsText() { new Assertion<>( "String contains other Text", new Contains( "Terra incognita", new TextOf("cognita") ), new ScalarHasValue<>(Boolean.TRUE) ).affirm(); } @Test void stringDoesNotContainText() { new Assertion<>( "String does not contain other Text", new Contains( "ratio", new TextOf("Cogito egro sum") ), new ScalarHasValue<>(Boolean.FALSE) ).affirm(); } @Test void stringContainsString() { new Assertion<>( "String contains other String", new Contains( "Lazy dog", "dog" ), new ScalarHasValue<>(Boolean.TRUE) ).affirm(); } @Test void stringDoesNotContainString() { new Assertion<>( "String does not contain other String", new Contains( "Lorem ipsum", "test" ), new ScalarHasValue<>(Boolean.FALSE) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/text/EndsWithTest.java000066400000000000000000000040131400054650300242210ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.text; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.ScalarHasValue; /** * Test case for {@link EndsWith}. * @since 1.0 * @checkstyle JavadocMethodCheck (500 lines) */ final class EndsWithTest { @Test void textMatchesEnding() { new Assertion<>( "Text's ending must match pattern", new EndsWith( new TextOf("Elegant Object"), "Object" ), new ScalarHasValue<>(Boolean.TRUE) ).affirm(); } @Test void textMismatchesEnding() { new Assertion<>( "Text's ending must not match pattern", new EndsWith( new TextOf("Java is awesome"), "good" ), new ScalarHasValue<>(Boolean.FALSE) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/text/FlattenedTest.java000066400000000000000000000044261400054650300244120ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.text; import org.cactoos.Text; import org.cactoos.iterable.IterableOf; import org.cactoos.iterable.Mapped; import org.cactoos.scalar.ScalarOf; import org.hamcrest.core.AllOf; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.TextIs; /** * Tests for {@link Flattened}. * * @since 0.49 * @checkstyle ClassDataAbstractionCouplingCheck (500 lines) */ final class FlattenedTest { @Test void flattens() { final Text txt = new TextOf("txt"); new Assertion<>( "must flatten", new Flattened( new ScalarOf<>(() -> txt) ), new TextIs(txt) ).affirm(); } @Test void flattensTextThatChanges() { final Iterable txts = new IterableOf<>( new TextOf("txt1"), new TextOf("txt2") ); new Assertion<>( "must flatten a scalar that changes", new Flattened( new ScalarOf<>(txts.iterator()::next) ), new AllOf(new Mapped<>(TextIs::new, txts)) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/text/FormattedTextTest.java000066400000000000000000000073751400054650300253040ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.text; import java.util.Calendar; import java.util.IllegalFormatConversionException; import java.util.Locale; import java.util.UnknownFormatConversionException; import org.cactoos.list.ListOf; import org.junit.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.TextHasString; /** * Test case for {@link FormattedText}. * * @since 0.1 * @checkstyle JavadocMethodCheck (500 lines) */ public final class FormattedTextTest { @Test public void formatsText() { new Assertion<>( "Can't format a text", new FormattedText( "%d. Formatted %s", 1, "text" ), new TextHasString("1. Formatted text") ).affirm(); } @Test public void formatsTextWithObjects() { new Assertion<>( "Can't format a text with objects", new FormattedText( new TextOf("%d. Number as %s"), 1, new String("string") ), new TextHasString("1. Number as string") ).affirm(); } @Test(expected = UnknownFormatConversionException.class) public void failsForInvalidPattern() throws Exception { new FormattedText( new TextOf("%%. Formatted %$"), new ListOf<>(1, "invalid") ).asString(); } @Test public void formatsTextWithCollection() { new Assertion<>( "Can't format a text with a collection", new FormattedText( new TextOf("%d. Formatted as %s"), new ListOf<>(1, "txt") ), new TextHasString("1. Formatted as txt") ).affirm(); } @Test(expected = IllegalFormatConversionException.class) public void ensuresThatFormatterFails() throws Exception { new FormattedText( new TextOf("Local time: %d"), Locale.ROOT, Calendar.getInstance() ).asString(); } @Test public void formatsWithLocale() { new Assertion<>( "Can't format a text with Locale", new FormattedText( // @checkstyle MagicNumber (1 line) "%,d", Locale.GERMAN, 1_234_567_890 ), new TextHasString("1.234.567.890") ).affirm(); } @Test public void formatsWithText() { new Assertion<>( "Can't format a string with text", new FormattedText( "Format with text: %s", new TextOf("Cactoos") ), new TextHasString("Format with text: Cactoos") ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/text/HexOfTest.java000066400000000000000000000040511400054650300235070ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.text; import java.io.IOException; import org.cactoos.bytes.BytesOf; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.TextHasString; /** * Test case for {@link HexOf}. * @since 0.28 * @checkstyle JavadocMethodCheck (500 lines) */ final class HexOfTest { @Test void empytString() { new Assertion<>( "Can't represent an empty string as hexadecimal", new HexOf( new BytesOf("") ), new TextHasString("") ).affirm(); } @Test void notEmpytString() throws IOException { new Assertion<>( "Can't represent a string as hexadecimal", new HexOf( new BytesOf("What's up, друг?") ), new TextHasString("5768617427732075702c20d0b4d180d183d0b33f") ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/text/IsBlankTest.java000066400000000000000000000043121400054650300240210ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.text; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.ScalarHasValue; /** * Test case for {@link IsBlank}. * @since 0.1 * @checkstyle JavadocMethodCheck (500 lines) */ final class IsBlankTest { @Test void determinesEmptyText() { new Assertion<>( "Can't determine an empty text", new IsBlank( new TextOf("") ), new ScalarHasValue<>(Boolean.TRUE) ).affirm(); } @Test void determinesBlankText() { new Assertion<>( "Can't determine an empty text with spaces", new IsBlank( new TextOf(" ") ), new ScalarHasValue<>(Boolean.TRUE) ).affirm(); } @Test void determinesNotBlankText() { new Assertion<>( "Can't detect a nonempty text", new IsBlank( new TextOf("not empty") ), new ScalarHasValue<>(Boolean.FALSE) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/text/IsEmptyTest.java000066400000000000000000000040541400054650300240730ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.text; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.ScalarHasValue; /** * Test case for {@link IsEmpty}. * @since 0.47 */ final class IsEmptyTest { @Test void determinesEmptyText() { new Assertion<>( "Must determine empty text", new IsEmpty(new TextOf("")), new ScalarHasValue<>(Boolean.TRUE) ).affirm(); } @Test void determinesNonemptyText() { new Assertion<>( "Must not detect non-empty text", new IsEmpty(new TextOf("abc")), new ScalarHasValue<>(Boolean.FALSE) ).affirm(); } @Test void determinesBlankText() { new Assertion<>( "Must not detect blank text", new IsEmpty(new TextOf(" ")), new ScalarHasValue<>(Boolean.FALSE) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/text/JoinedTest.java000066400000000000000000000043561400054650300237160ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.text; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.TextHasString; /** * Test case for {@link Joined}. * @since 0.9 * @checkstyle JavadocMethodCheck (500 lines) */ final class JoinedTest { @Test void joinsStrings() { new Assertion<>( "Can't join strings", new Joined(" ", "hello", "world"), new TextHasString("hello world") ).affirm(); } @Test void joinsTexts() { new Assertion<>( "Can't join texts", new Joined( new TextOf(" "), new TextOf("foo"), new TextOf("bar") ), new TextHasString("foo bar") ).affirm(); } @Test void joinsTextsWitjStringDelimit() { new Assertion<>( "Can't join texts with String delimit", new Joined( " ", new TextOf("one"), new TextOf("two") ), new TextHasString("one two") ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/text/LoweredTest.java000066400000000000000000000035161400054650300241040ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.text; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.TextHasString; /** * Test case for {@link Lowered}. * @since 0.11 * @checkstyle JavadocMethodCheck (500 lines) */ final class LoweredTest { @Test void convertsText() { new Assertion<>( "Can't lower case a text", new Lowered(new TextOf("HelLo!")), new TextHasString("hello!") ).affirm(); } @Test void convertsString() { new Assertion<>( "Can't lower case a string", new Lowered("WoRLd!"), new TextHasString("world!") ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/text/MappedTest.java000066400000000000000000000043531400054650300237110ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.text; import org.hamcrest.core.IsEqual; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.TextIs; /** * Tests for @{link Mapped}. * * @since 0.47 */ final class MappedTest { @Test void resultShouldBeEqual() { new Assertion<>( "must be equal to the same text", new Mapped( String::toUpperCase, new TextOf("hi") ), new IsEqual<>(new TextOf("HI")) ).affirm(); } @Test void mapsWithFormat() { new Assertion<>( "must apply lambda to a string", new Mapped( s -> String.format("<%s>", s), new TextOf("hi") ), new TextIs("") ).affirm(); } @Test void maps() { new Assertion<>( "must apply method reference to a string", new Mapped( String::toLowerCase, new TextOf("ABC") ), new TextIs("abc") ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/text/NormalizedTest.java000066400000000000000000000032261400054650300246050ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.text; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.TextHasString; /** * Test case for {@link Normalized}. * @since 0.9 * @checkstyle JavadocMethodCheck (500 lines) */ final class NormalizedTest { @Test void normalizesText() { new Assertion<>( "Can't normalize a text", new Normalized(" \t hello \t\tworld \t"), new TextHasString("hello world") ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/text/PaddedStartTest.java000066400000000000000000000045471400054650300247070ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.text; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.TextHasString; /** * Test case for {@link PaddedStart}. * * @since 0.1 * @checkstyle JavadocMethodCheck (500 lines) */ final class PaddedStartTest { @Test void noPaddingIfOrigTextIsAsLongAsRequestedLength() { new Assertion<>( "Shouldn't pad the text", new PaddedStart( new TextOf("x"), 1, '-' ), new TextHasString("x") ).affirm(); } @Test void somePaddingIfOrigTextIsShorterThanRequestedLength() { new Assertion<>( "Should pad chars at start", new PaddedStart( new TextOf("x"), 2, '-' ), new TextHasString("-x") ).affirm(); } @Test void noPaddingIfRequestedLengthIsNegative() { new Assertion<>( "Shouldn't consider negative min length", new PaddedStart( new TextOf("x"), -1, '-' ), new TextHasString("x") ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/text/PrefixOfTest.java000066400000000000000000000046241400054650300242260ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.text; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.TextIs; /** * Test case for {@link PrefixOf}. * * @since 1.0 */ @SuppressWarnings("PMD.AvoidDuplicateLiterals") final class PrefixOfTest { /** * Ensures that Before is returning given string if * there is no given boundary. */ @Test void returnsInputIfThereIsNoBoundary() { new Assertion<>( "Given strings are not equal", new PrefixOf("Cactoos", "bnd"), new TextIs("Cactoos") ).affirm(); } /** * Ensures that Before is returning empty string if * given boundary is equal to given string. */ @Test void returnsEmptyIfStringIsBoundary() { new Assertion<>( "Given string is not empty", new PrefixOf("Boundary", "Boundary"), new TextIs("") ).affirm(); } /** * Ensures that Before is returning string * before given boundary. */ @Test void returnsBeforeBoundaryString() { new Assertion<>( "Given strings are not equal", new PrefixOf("Anti-pattern", "-pattern"), new TextIs("Anti") ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/text/RandomizedTest.java000066400000000000000000000052451400054650300246000ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.text; import org.hamcrest.Matchers; import org.hamcrest.core.IsEqual; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.TextHasString; /** * Test for {@link Randomized}. * *

There is no thread-safety guarantee. * * @since 0.32 * @checkstyle JavadocMethodCheck (500 lines) * @checkstyle MagicNumberCheck (500 lines) */ final class RandomizedTest { @Test void generatesRandomTextOfRandomLength() throws Exception { new Assertion<>( "Generated text is empty", new Randomized().asString().length(), Matchers.greaterThan(0) ).affirm(); } @Test void generatesRandomTextOfSpecifiedLength() throws Exception { new Assertion<>( "Generated text has incorrect length", new Randomized(512).asString().length(), new IsEqual<>(512) ).affirm(); } @Test void generatesRandomTextOfSpecifiedChars() throws Exception { new Assertion<>( "Generated text contains not allowed characters", new Randomized('a') .asString() .replaceAll("a", "") .length(), new IsEqual<>(0) ).affirm(); } @Test void generatesRandomTextOfSpecifiedCharsAndLength() { new Assertion<>( "Generated text doesn't match specification", new Randomized(10, 'a'), new TextHasString("aaaaaaaaaa") ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/text/RepeatedTest.java000066400000000000000000000036451400054650300242370ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.text; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.TextHasString; /** * Test case for {@link Repeated}. * @since 0.9 * @checkstyle JavadocMethodCheck (500 lines) */ final class RepeatedTest { @Test void repeatsWordsText() { new Assertion<>( "Can't repeats a text", // @checkstyle MagicNumber (1 line) new Repeated("hello", 2), new TextHasString("hellohello") ).affirm(); } @Test void repeatsCharText() { new Assertion<>( "Can't repeats a char", // @checkstyle MagicNumber (1 line) new Repeated("A", 5), new TextHasString("AAAAA") ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/text/ReplacedTest.java000066400000000000000000000134101400054650300242140ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.text; import java.nio.charset.StandardCharsets; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.TextHasString; import org.llorllale.cactoos.matchers.Throws; /** * Test case for {@link Replaced}. * * @since 0.2 * @checkstyle JavadocMethodCheck (500 lines) */ @SuppressWarnings({"PMD.TooManyMethods", "PMD.AvoidDuplicateLiterals"}) final class ReplacedTest { @Test void replaceText() { new Assertion<>( "Can't replace a text", new Replaced( new TextOf("Hello!"), "ello", "i" ), new TextHasString("Hi!") ).affirm(); } @Test void notReplaceTextWhenSubstringNotFound() { final String text = "HelloAgain!"; new Assertion<>( "Replace a text abnormally", new Replaced( new TextOf(text), "xyz", "i" ), new TextHasString(text) ).affirm(); } @Test void replacesAllOccurrences() { new Assertion<>( "Can't replace a text with multiple needle occurrences", new Replaced( new TextOf("one cat, two cats, three cats"), "cat", "dog" ), new TextHasString("one dog, two dogs, three dogs") ).affirm(); } @Test void regexConstantReplace() { new Assertion<>( "Cannot do simple replacement with regex", new Replaced( new TextOf("one cow two cows in the yard"), () -> Pattern.compile("cow"), matcher -> "pig" ), new TextHasString("one pig two pigs in the yard") ).affirm(); } @Test void regexDynamicReplace() { new Assertion<>( "Cannot do dynamic string replacement", new Replaced( new TextOf("one two THREE four FIVE six"), () -> Pattern.compile("[a-z]+"), matcher -> String.valueOf(matcher.group().length()) ), new TextHasString("3 3 THREE 4 FIVE 3") ).affirm(); } @Test void emptyText() { new Assertion<>( "Substitution in empty text with non-empty regex.", new Replaced( new TextOf(""), "123", "WOW" ), new TextHasString("") ).affirm(); } @Test void emptyRegex() { new Assertion<>( "Substitution in text with empty regex.", new Replaced( new TextOf("abc"), "", "1" ), new TextHasString("1a1b1c1") ).affirm(); } @Test void emptyTextAndEmptyRegex() { new Assertion<>( "Substitution in empty text with empty regex.", new Replaced( new TextOf(""), "", "1" ), new TextHasString("1") ).affirm(); } @Test void invalidRegex() { final String regex = "invalid_regex{0,"; new Assertion<>( "Doesn't throw proper exception", new Replaced( new TextOf("text"), regex, "error" )::asString, new Throws<>( new PatternSyntaxException( "Unclosed counted closure", regex, // @checkstyle MagicNumberCheck (1 line) 16 ).getMessage(), PatternSyntaxException.class ) ).affirm(); } @Test void nonDefaultCharsetText() { new Assertion<>( "Cannot do dynamic string replacement with non-default charset", new Replaced( new TextOf("abc def GHI JKL", StandardCharsets.UTF_16LE), () -> Pattern.compile("[A-Z]+"), matcher -> String.valueOf(matcher.group().length()) ), new TextHasString("abc def 3 3") ).affirm(); } @Test void unicodeText() { new Assertion<>( "Cannot do dynamic string replacement with unicode characters", new Replaced( new TextOf("abc def GHI\u2300JKL"), () -> Pattern.compile("[a-z]+|\u2300"), matcher -> String.valueOf(matcher.group().length()) ), new TextHasString("3 3 GHI1JKL") ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/text/ReversedTest.java000066400000000000000000000036311400054650300242600ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.text; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.TextHasString; /** * Test case for {@link Reversed}. * * @since 0.2 * @checkstyle JavadocMethodCheck (500 lines) */ final class ReversedTest { @Test void reverseText() { new Assertion<>( "Can't reverse a text", new Reversed( new TextOf("Hello!") ), new TextHasString("!olleH") ).affirm(); } @Test void reversedEmptyTextIsEmptyText() { new Assertion<>( "Can't reverse empty text", new Reversed( new TextOf("") ), new TextHasString("") ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/text/RotatedTest.java000066400000000000000000000054011400054650300241000ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.text; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.TextHasString; /** * Test case for {@link Rotated}. * * @since 0.12 * @checkstyle JavadocMethodCheck (500 lines) */ final class RotatedTest { @Test void rotateRightText() { new Assertion<>( "Can't rotate text to right", new Rotated( new TextOf("Hello!"), 2 ), new TextHasString("o!Hell") ).affirm(); } @Test void rotateLeftText() { new Assertion<>( "Can't rotate text to left", new Rotated( new TextOf("Hi!"), -1 ), new TextHasString("i!H") ).affirm(); } @Test void noRotateWhenShiftZero() { final String nonrotate = "Cactoos!"; new Assertion<>( "Rotate text shift zero", new Rotated( new TextOf(nonrotate), 0 ), new TextHasString(nonrotate) ).affirm(); } @Test void noRotateWhenShiftModZero() { final String nonrotate = "Rotate"; new Assertion<>( "Rotate text shift mod zero", new Rotated( new TextOf(nonrotate), nonrotate.length() ), new TextHasString(nonrotate) ).affirm(); } @Test void noRotateWhenEmpty() { new Assertion<>( "Rotate text when empty", new Rotated( new TextOf(""), 2 ), new TextHasString("") ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/text/SplitTest.java000066400000000000000000000114331400054650300235730ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.text; import org.cactoos.Text; import org.cactoos.iterable.IterableOf; import org.hamcrest.core.IsEqual; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; /** * Test case for {@link Split}. * @since 0.9 * @checkstyle JavadocMethodCheck (500 lines) * @checkstyle ClassDataAbstractionCouplingCheck (500 lines) */ @SuppressWarnings("PMD.TooManyMethods") final class SplitTest { @Test void splitStringWithStringRegex() throws Exception { new Assertion<>( "Must split string with string regex", new Split("Hello world!", "\\s+"), new IsEqual<>(new IterableOf<>(new TextOf("Hello"), new TextOf("world!"))) ).affirm(); } @Test void splitStringWithTextRegex() throws Exception { new Assertion<>( "Must split string with text regex", new Split("Cactoos OOP!", new TextOf("\\s")), new IsEqual<>(new IterableOf<>(new TextOf("Cactoos"), new TextOf("OOP!"))) ).affirm(); } @Test void splitTextWithStringRegex() throws Exception { new Assertion<>( "Must split text with string regex", new Split(new TextOf("Cact4Primitives!"), "\\d+"), new IsEqual<>(new IterableOf<>(new TextOf("Cact"), new TextOf("Primitives!"))) ).affirm(); } @Test void splitTextWithTextRegex() throws Exception { new Assertion<>( "Must split text with text regex", new Split(new TextOf("Split#OOP"), new TextOf("#")), new IsEqual<>(new IterableOf<>(new TextOf("Split"), new TextOf("OOP"))) ).affirm(); } @Test void splitStringWithStringRegexAndLimit() throws Exception { new Assertion<>( "Must split string with string regex and limit", new Split("Hello! ! world!", " ", 2), new IsEqual<>(new IterableOf<>(new TextOf("Hello!"), new TextOf("! world!"))) ).affirm(); } @Test void splitStringWithTextRegexAndLimit() throws Exception { new Assertion<>( "Must split string with text regex and limit", new Split("Cactoos! ! OOP!", new TextOf(" "), 2), new IsEqual<>(new IterableOf<>(new TextOf("Cactoos!"), new TextOf("! OOP!"))) ).affirm(); } @Test void splitTextWithStringRegexAndLimit() throws Exception { final Text txt = new TextOf("Cact!4Primitives"); new Assertion<>( "Must split text with string regex and limit", new Split(txt, "4", 1), new IsEqual<>(new IterableOf<>(txt)) ).affirm(); } @Test void splitTextWithTextRegexAndLimit() throws Exception { final Text txt = new TextOf("Split!# #OOP"); new Assertion<>( "Must split text with text regex and limit", new Split(txt, "\\W+", 1), new IsEqual<>(new IterableOf<>(txt)) ).affirm(); } @Test void splitWithZeroLimit() throws Exception { new Assertion<>( "Must split string with string regex and zero limit", new Split("Hello. The! !world", " +", 0), new IsEqual<>( new IterableOf<>(new TextOf("Hello."), new TextOf("The!"), new TextOf("!world")) ) ).affirm(); } @Test void splitWithNegativeLimit() throws Exception { new Assertion<>( "Must split string with string regex and negative limit", new Split("Hello: The world", " ", -1), new IsEqual<>( new IterableOf<>(new TextOf("Hello:"), new TextOf("The"), new TextOf("world")) ) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/text/StartsWithTest.java000066400000000000000000000051561400054650300246210ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.text; import org.hamcrest.core.IsNot; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.IsTrue; /** * Test case for {@link StartsWith}. * * @since 0.44 * @checkstyle JavadocMethodCheck (500 lines) */ public class StartsWithTest { @Test void emptyStartsWithEmpty() throws Exception { new Assertion<>( "Empty is not prefix of empty", new StartsWith( new TextOf(""), new TextOf("") ).value(), new IsTrue() ).affirm(); } @Test void textStartsWithEmpty() throws Exception { new Assertion<>( "Empty is not prefix of any string", new StartsWith( new TextOf("Any string"), new TextOf("") ).value(), new IsTrue() ).affirm(); } @Test void textStartsWithPrefix() throws Exception { new Assertion<>( "Foo is not prefix of FooBar", new StartsWith( "FooBar", "Foo" ).value(), new IsTrue() ).affirm(); } @Test void textStartsWithoutPrefix() throws Exception { new Assertion<>( "Baz is prefix of FooBarBaz", new StartsWith( "FooBarBaz", "Baz" ).value(), new IsNot<>(new IsTrue()) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/text/StickyTest.java000066400000000000000000000031601400054650300237440ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.text; import org.cactoos.Text; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.TextIs; /** * Test case for {@link Sticky}. * @since 0.47 */ final class StickyTest { @Test void cachesResult() { final Text sticky = new Sticky(new Randomized()); new Assertion<>( "must be the same", sticky, new TextIs(sticky) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/text/StrictTest.java000066400000000000000000000065261400054650300237570ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.text; import java.util.regex.Pattern; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.TextIs; import org.llorllale.cactoos.matchers.Throws; /** * Test case for {@link Strict}. * * @since 1.0 * @checkstyle MagicNumber (500 line) */ @SuppressWarnings("PMD.AvoidDuplicateLiterals") final class StrictTest { /** * Ensures that Strict is failing on a negative predicate result. * @throws Exception If fails */ @Test void failsIfPredicateIsNegative() { new Assertion<>( "Must throw IllegalArgumentException", () -> new Strict(s -> false, new TextOf("text")).asString(), new Throws<>( "String 'text' does not match a given predicate", IllegalArgumentException.class ) ).affirm(); } /** * Ensures that Strict is returning unchanged string on a positive * predicate result. */ @Test void returnsUnchangedIfPredicateIsPositive() { new Assertion<>( "Given strings are not equal", new Strict(s -> true, new TextOf("text")), new TextIs("text") ).affirm(); } /** * Ensures that Strict is failing on a text not matching a pattern. * @throws Exception If fails */ @Test void failsIfNotMatchedWithPattern() { new Assertion<>( "Must throw IllegalArgumentException", () -> new Strict( Pattern.compile("^[a-zA-Z]+$"), new TextOf("text12") ).asString(), new Throws<>( "String 'text12' does not match a given predicate", IllegalArgumentException.class ) ).affirm(); } /** * Ensures that Strict is returning unchanged string * on a matched with pattern string. */ @Test void returnsUnchangedIfMatchedWithPattern() { new Assertion<>( "Given strings are not equal", new Strict( Pattern.compile("^[a-zA-Z0-9]+$"), new TextOf("text1") ), new TextIs("text1") ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/text/SubTest.java000066400000000000000000000036211400054650300232310ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.text; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.TextHasString; /** * Test case for {@link Sub}. * @since 0.11 * @checkstyle JavadocMethodCheck (500 lines) */ final class SubTest { @Test void cutTextWithStartAndEnd() { new Assertion<>( "Can't cut a text with start and end", // @checkstyle MagicNumber (1 line) new Sub("hello world", 2, 50), new TextHasString("llo world") ).affirm(); } @Test void cutTextWithStart() { new Assertion<>( "Can't cut a text with start", new Sub("cut here", 2), new TextHasString("t here") ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/text/SuffixOfTest.java000066400000000000000000000046311400054650300242330ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.text; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.TextIs; /** * Test case for {@link SuffixOf}. * * @since 1.0 */ @SuppressWarnings("PMD.AvoidDuplicateLiterals") final class SuffixOfTest { /** * Ensures that After is returning empty string if * there is no given boundary. */ @Test void returnsEmptyIfThereIsNoBoundary() { new Assertion<>( "Given string is not empty", new SuffixOf("Cactoos with description", "after"), new TextIs("") ).affirm(); } /** * Ensures that After is returning empty string if * given boundary is equal to given string. */ @Test void returnsEmptyIfStringIsBoundary() { new Assertion<>( "Given string is not empty", new SuffixOf("Boundary", "Boundary"), new TextIs("") ).affirm(); } /** * Ensures that After is returning string * after given boundary. */ @Test void returnsAfterBoundaryString() { new Assertion<>( "Given strings are not equal", new SuffixOf("Anti-pattern", "Anti-"), new TextIs("pattern") ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/text/SwappedCaseTest.java000066400000000000000000000036551400054650300247060ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.text; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.TextHasString; /** * Test case for {@link SwappedCase}. * * @since 0.13.3 * @checkstyle JavadocMethodCheck (500 lines) */ final class SwappedCaseTest { @Test void swapText() { new Assertion<>( "Can't swap a text", new SwappedCase( new TextOf("HellO!") ), new TextHasString("hELLo!") ).affirm(); } @Test void swapEmptyText() { new Assertion<>( "Empty swapped text should be the same as original", new SwappedCase( new TextOf("") ), new TextHasString("") ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/text/TextEnvelopeTest.java000066400000000000000000000054011400054650300251200ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.text; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import org.cactoos.Scalar; import org.hamcrest.core.IsEqual; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; /** * Tests for {@link TextEnvelope}. * @since 0.32 */ final class TextEnvelopeTest { /** * Test for {@link TextEnvelope#asString()} method. Must assert that * the envelope asString value is equal to its string value. * @throws Exception Throws from asString. */ @Test void testAsString() throws Exception { final String text = "asString"; new Assertion<>( "Envelope value does not match String value", new TextEnvelopeDummy(text).asString(), new IsEqual<>(text) ).affirm(); } /** * Dummy class for {@link TextEnvelope} testing. * @since 0.32 */ private final class TextEnvelopeDummy extends TextEnvelope { /** * Ctor. * * @param input The String */ TextEnvelopeDummy(final String input) { this(input, StandardCharsets.UTF_8); } /** * Ctor. * * @param input The String * @param cset The Charset */ TextEnvelopeDummy(final String input, final Charset cset) { this(() -> new String(input.getBytes(cset), cset)); } /** * Ctor. * * @param scalar Text to be enveloped. */ TextEnvelopeDummy(final Scalar scalar) { super(new TextOf(scalar)); } } } cactoos-0.49/src/test/java/org/cactoos/text/TextOfTest.java000066400000000000000000000516611400054650300237200ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.text; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.StringReader; import java.nio.charset.StandardCharsets; import java.text.MessageFormat; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.time.OffsetDateTime; import java.time.ZoneId; import java.time.ZoneOffset; import java.time.ZonedDateTime; import java.util.Calendar; import java.util.Locale; import java.util.TimeZone; import org.cactoos.bytes.BytesOf; import org.cactoos.io.InputOf; import org.cactoos.iterator.IteratorOfChars; import org.hamcrest.Matchers; import org.hamcrest.core.IsEqual; import org.hamcrest.core.IsNot; import org.hamcrest.core.IsNull; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.IsBlank; import org.llorllale.cactoos.matchers.TextHasString; import org.llorllale.cactoos.matchers.TextIs; /** * Test case for {@link TextOf}. * * @since 0.12 * @checkstyle JavadocMethodCheck (1000 lines) * @checkstyle ClassDataAbstractionCouplingCheck (1000 lines) * @checkstyle MagicNumberCheck (1000 lines) * @checkstyle StringLiteralsConcatenationCheck (1000 lines) */ @SuppressWarnings({"PMD.TooManyMethods", "PMD.AvoidDuplicateLiterals"}) final class TextOfTest { @Test void readsInputIntoText() throws Exception { new Assertion<>( "Can't read text from Input", new Synced( new TextOf( new InputOf("привет, друг!"), StandardCharsets.UTF_8 ) ).asString(), Matchers.allOf( Matchers.startsWith("привет, "), Matchers.endsWith("друг!") ) ).affirm(); } @Test void readsInputIntoTextWithDefaultCharset() throws Exception { new Assertion<>( "Can't read text from Input with default charset", new TextOf( new InputOf("Hello, друг! with default charset") ).asString(), Matchers.allOf( Matchers.startsWith("Hello, "), Matchers.endsWith("друг! with default charset") ) ).affirm(); } @Test void readsInputIntoTextWithSmallBuffer() throws Exception { new Assertion<>( "Can't read text with a small reading buffer", new TextOf( new InputOf("Hi, товарищ! with small buffer"), 2, StandardCharsets.UTF_8 ).asString(), Matchers.allOf( Matchers.startsWith("Hi,"), Matchers.endsWith("товарищ! with small buffer") ) ).affirm(); } @Test void readsReaderIntoTextWithSmallBuffer() { final String text = "Hi there! with small buffer"; new Assertion<>( "Can't read text from Reader with a small reading buffer", new TextOf(text), new TextIs( new TextOf( new StringReader(text), 2, StandardCharsets.UTF_8 ) ) ).affirm(); } @Test void readsInputIntoTextWithSmallBufferAndDefaultCharset() throws Exception { new Assertion<>( "Can't read text with a small reading buffer and default charset", new TextOf( new InputOf("Hello, товарищ! with default charset"), 2 ).asString(), Matchers.allOf( Matchers.startsWith("Hello,"), Matchers.endsWith("товарищ! with default charset") ) ).affirm(); } @Test void readsFromReader() throws Exception { final String source = "hello, друг!"; new Assertion<>( "Can't read string through a reader", new TextOf( new StringReader(source), StandardCharsets.UTF_8 ).asString(), Matchers.equalTo( new String( new BytesOf(source).asBytes(), StandardCharsets.UTF_8 ) ) ).affirm(); } @Test void readsFromReaderWithDefaultEncoding() throws Exception { final String source = "hello, друг! with default encoding"; new Assertion<>( "Can't read string with default encoding through a reader", new TextOf(new StringReader(source)).asString(), Matchers.equalTo( new String( new BytesOf(source).asBytes(), StandardCharsets.UTF_8 ) ) ).affirm(); } @Test void readsEncodedArrayOfCharsIntoText() throws Exception { new Assertion<>( "Can't read array of encoded chars into text.", new TextOf( 'O', ' ', 'q', 'u', 'e', ' ', 's', 'e', 'r', 'a', ' ', 'q', 'u', 'e', ' ', 's', 'e', 'r', 'a' ).asString(), Matchers.allOf( Matchers.startsWith("O que sera"), Matchers.endsWith(" que sera") ) ).affirm(); } @Test void readsAnArrayOfBytes() throws Exception { final byte[] bytes = new byte[] {(byte) 0xCA, (byte) 0xFE}; new Assertion<>( "Can't read array of bytes", new TextOf( bytes ).asString(), Matchers.equalTo(new String(bytes, StandardCharsets.UTF_8)) ).affirm(); } @Test void readsStringBuilder() throws Exception { final String starts = "Name it, "; final String ends = "then it exists!"; new Assertion<>( "Can't process a string builder", new TextOf( new StringBuilder(starts).append(ends) ).asString(), Matchers.allOf( Matchers.startsWith(starts), Matchers.endsWith(ends) ) ).affirm(); } @Test void readsStringBuffer() throws Exception { final String starts = "In our daily life, "; final String ends = "we can smile!"; new Assertion<>( "Can't process a string builder hahahaha", new TextOf( new StringBuffer(starts).append(ends) ).asString(), Matchers.allOf( Matchers.startsWith(starts), Matchers.endsWith(ends) ) ).affirm(); } @Test void printsStackTrace() { new Assertion<>( "Can't print exception stacktrace", new TextOf( new IOException( "It doesn't work at all" ) ), new TextHasString( new Joined( System.lineSeparator(), "java.io.IOException: It doesn't work at all", "\tat org.cactoos.text.TextOfTest" ) ) ).affirm(); } @Test void readsFromInputStream() throws Exception { final String content = "line1"; final InputStream stream = new ByteArrayInputStream( content.getBytes(StandardCharsets.UTF_8.name()) ); new Assertion<>( "Can't read inputStream", new TextOf(stream).asString(), Matchers.equalTo( new String(content.getBytes(), StandardCharsets.UTF_8) ) ).affirm(); } @Test void readsMultilineInputStream() throws Exception { final String content = "line1-\nline2"; final InputStream stream = new ByteArrayInputStream( content.getBytes(StandardCharsets.UTF_8.name()) ); new Assertion<>( "Can't read multiline inputStream", new TextOf(stream).asString(), Matchers.equalTo(content) ).affirm(); } @Test void readsMultilineInputStreamWithCarriageReturn() throws Exception { final String content = "line1-\rline2"; final InputStream stream = new ByteArrayInputStream( content.getBytes(StandardCharsets.UTF_8.name()) ); new Assertion<>( "Can't read multiline inputStream with carriage return", new TextOf(stream).asString(), Matchers.equalTo(content) ).affirm(); } @Test void readsClosedInputStream() throws Exception { final String content = "content"; final InputStream stream = new ByteArrayInputStream( content.getBytes(StandardCharsets.UTF_8.name()) ); stream.close(); new Assertion<>( "Can't read closed input stream", new TextOf(stream).asString(), Matchers.equalTo(content) ).affirm(); } @Test void readsEmptyInputStream() throws Exception { final String content = ""; final InputStream stream = new ByteArrayInputStream( content.getBytes(StandardCharsets.UTF_8.name()) ); new Assertion<>( "Can't read empty input stream", new TextOf(stream).asString(), Matchers.equalTo(content) ).affirm(); } @Test void printsStackTraceFromArray() { new Assertion<>( "Can't print exception stacktrace from array", new TextOf( new IOException("").getStackTrace() ), new TextHasString("org.cactoos.text.TextOfTest") ).affirm(); } @Test void readsLocalDateFormattedWithFormatString() { final LocalDate date = LocalDate.of(2017, 12, 13); new Assertion<>( "Can't format a LocalDate with format.", new TextOf(date, "yyyy-MM-dd HH:mm:ss"), new TextIs("2017-12-13 00:00:00") ).affirm(); } @Test void readsLocalDateFormattedWithFormatStringWithLocale() { final LocalDate date = LocalDate.of(2017, 12, 13); new Assertion<>( "Can't format a LocalDate with format using locale.", new TextOf( date, "yyyy MMM dd. HH.mm.ss", Locale.FRENCH ), new TextIs("2017 déc. 13. 00.00.00") ).affirm(); } @Test void readsLocalDateFormattedAsIsoDateTime() throws IOException { final LocalDate date = LocalDate.of(2017, 12, 13); new Assertion<>( "Can't format a LocalDate with default/ISO format.", new TextOf(date), new TextIs( MessageFormat.format( "2017-12-13T00:00:00{0}", date.atTime(LocalTime.MIN).atZone(ZoneId.systemDefault()) .getOffset().toString() ) ) ).affirm(); } @Test void readsCurrentLocalDateAsText() throws Exception { new Assertion<>( "Can't format a LocalDate with ISO format.", new TextOf(LocalDate.now()).asString(), new IsNot<>(new IsBlank()) ).affirm(); } @Test void localDateTimeFormattedAsIsoDateTime() { final LocalDateTime date = LocalDateTime.of( 2017, 12, 13, 14, 15, 16, 17 ); new Assertion<>( "Can't format a LocalDateTime with default/ISO format.", new TextOf(date), new TextIs( MessageFormat.format( "2017-12-13T14:15:16.000000017{0}", date.atZone(ZoneId.systemDefault()).getOffset().toString() ) ) ).affirm(); } @Test void localDateTimeFormattedWithFormatString() { final LocalDateTime date = LocalDateTime.of( 2017, 12, 13, 14, 15, 16, 17 ); new Assertion<>( "Can't format a LocalDateTime with format.", new TextOf(date, "yyyy-MM-dd HH:mm:ss"), new TextIs("2017-12-13 14:15:16") ).affirm(); } @Test void localDateTimeFormattedWithFormatStringWithLocale() { final LocalDateTime date = LocalDateTime.of( 2017, 12, 13, 14, 15, 16, 17 ); new Assertion<>( "Can't format a LocalDateTime with format using locale.", new TextOf( date, "yyyy MMM dd. HH.mm.ss", Locale.FRENCH ), new TextIs("2017 déc. 13. 14.15.16") ).affirm(); } @Test void currentLocalDateTimeAsText() throws Exception { new Assertion<>( "Can't format a LocalDateTime with ISO format.", new TextOf(LocalDateTime.now()).asString(), new IsNot<>(new IsNull<>()) ).affirm(); } @Test void dateFormattedUsingIsoFormatter() { final Calendar calendar = Calendar.getInstance(TimeZone.getDefault()); calendar.set(2017, Calendar.DECEMBER, 13, 14, 15, 16); calendar.set(Calendar.MILLISECOND, 17); final ZoneOffset offset = calendar.getTimeZone().toZoneId() .getRules().getOffset(calendar.toInstant()); new Assertion<>( "Can't format a java.util.Date with ISO format.", new TextOf(calendar.getTime()), new TextIs("2017-12-13T14:15:16.017" + offset) ).affirm(); } @Test void dateFormattedUsingCustomFormat() { final Calendar calendar = Calendar.getInstance(TimeZone.getDefault()); calendar.set(2017, Calendar.DECEMBER, 13, 14, 15, 16); new Assertion<>( "Can't format a java.util.Date with custom format.", new TextOf( calendar.getTime(), "yyyy MM dd hh:mm:ss" ), new TextIs("2017 12 13 02:15:16") ).affirm(); } @Test void dateFormattedUsingCustomFormatDifferentLocale() { final Calendar calendar = Calendar.getInstance(TimeZone.getDefault()); calendar.set(2017, Calendar.DECEMBER, 13, 14, 15, 16); new Assertion<>( "Can't format a java.util.Date with custom format.", new TextOf( calendar.getTime(), "yyyy MMM dd hh:mm:ss", Locale.ITALIAN ), new TextIs("2017 dic 13 02:15:16") ).affirm(); } @Test void offsetDateTimeFormattedAsIsoDateTime() { final OffsetDateTime date = OffsetDateTime.of( 2017, 12, 13, 14, 15, 16, 17, ZoneOffset.ofHours(1) ); new Assertion<>( "Can't format a OffsetDateTime with default/ISO format.", new TextOf(date), new TextIs("2017-12-13T14:15:16.000000017+01:00") ).affirm(); } @Test void offsetDateTimeFormattedWithFormatString() { final OffsetDateTime date = OffsetDateTime.of( 2017, 12, 13, 14, 15, 16, 17, ZoneOffset.ofHours(1) ); new Assertion<>( "Can't format a OffsetDateTime with format.", new TextOf(date, "yyyy-MM-dd HH:mm:ss"), new TextIs("2017-12-13 14:15:16") ).affirm(); } @Test void offsetDateTimeFormattedWithFormatStringWithLocale() { final OffsetDateTime date = OffsetDateTime.of( 2017, 12, 13, 14, 15, 16, 17, ZoneOffset.ofHours(1) ); new Assertion<>( "Can't format a OffsetDateTime with format using locale.", new TextOf( date, "yyyy MMM dd. HH.mm.ss", Locale.FRENCH ), new TextIs("2017 déc. 13. 14.15.16") ).affirm(); } @Test void currentOffsetDateTimeAsText() throws Exception { new Assertion<>( "Can't format a OffsetDateTime with ISO format.", new TextOf(OffsetDateTime.now()).asString(), new IsNot<>(new IsNull<>()) ).affirm(); } @Test void zonedDateTimeFormattedAsIsoDateTime() { final ZonedDateTime date = ZonedDateTime.of( 2017, 12, 13, 14, 15, 16, 17, ZoneId.of("Europe/Berlin") ); new Assertion<>( "Can't format a ZonedDateTime with default/ISO format.", new TextOf(date), new TextIs("2017-12-13T14:15:16.000000017+01:00") ).affirm(); } @Test void zonedDateTimeFormattedWithFormatString() { final ZonedDateTime date = ZonedDateTime.of( 2017, 12, 13, 14, 15, 16, 17, ZoneId.of("Europe/Berlin") ); new Assertion<>( "Can't format a ZonedDateTime with format.", new TextOf(date, "yyyy-MM-dd HH:mm:ss"), new TextIs("2017-12-13 14:15:16") ).affirm(); } @Test void zonedDateTimeFormattedWithFormatStringWithLocale() { final ZonedDateTime date = ZonedDateTime.of( 2017, 12, 13, 14, 15, 16, 17, ZoneId.of("Europe/Berlin") ); new Assertion<>( "Can't format a ZonedDateTime with format using locale.", new TextOf( date, "yyyy MMM dd. HH.mm.ss", Locale.FRENCH ), new TextIs("2017 déc. 13. 14.15.16") ).affirm(); } @Test void currentZonedDateTimeAsText() throws Exception { new Assertion<>( "Can't format a ZonedDateTime with ISO format.", new TextOf(ZonedDateTime.now()).asString(), new IsNot<>(new IsNull<>()) ).affirm(); } @Test void readsIteratorToText() throws Exception { new Assertion<>( "Can't read Iterator to Text", new TextOf( new IteratorOfChars("qwer") ).asString(), new IsEqual<>("qwer") ).affirm(); } /** * Test for {@link TextEnvelope#equals(Object)} method. Must assert * that the envelope value is equal another text representing the same * value. */ @Test void testEquals() { final String text = "equals"; new Assertion<>( "Must match text representing the same value", new TextOf(text), new IsEqual<>(new TextOf(text)) ).affirm(); } /** * Test for {@link TextEnvelope#equals(Object)} method. Must assert * that the envelope value is equal another text representing the same * value (in this case a {@link Joined}). */ @Test void testEqualsOtherText() { new Assertion<>( "Must match another text representing the same value", new TextOf("isequaltoanothertext"), new IsEqual<>( new Joined("", "is", "equal", "to", "another", "text") ) ).affirm(); } /** * Test for {@link TextEnvelope#equals(Object)} method. Must assert * that the envelope value is not equal another object not being a * instance of Text without failing */ @Test void testDoesNotEqualsNonTextObject() { new Assertion<>( "Must match another object which is not a string", new TextOf("is not equals to null"), new IsNot<>( new IsEqual<>(new Object()) ) ).affirm(); } /** * Test for {@link TextEnvelope#equals(Object)} method. Must assert * that the envelope value is not equal to null without failing */ @Test @SuppressWarnings("PMD.EqualsNull") void testDoesNotEqualsFalse() { new Assertion<>( "Must not equals null", new TextOf("is not equals to not Text object") .equals(null), new IsEqual<>(false) ).affirm(); } /** * Test for {@link TextEnvelope#hashCode()} method. Must assert that * the {@link TextEnvelope} hashCode is equals to the hashCode of * the String it represents. */ @Test void testHashCode() { final String hash = "hashCode"; new Assertion<>( "Must match its represented String hashcode", new TextOf(hash).hashCode(), new IsEqual<>(hash.hashCode()) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/text/TrimmedLeftTest.java000066400000000000000000000035731400054650300247220ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.text; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.TextHasString; /** * Test case for {@link TrimmedLeft}. * @since 0.12 * @checkstyle JavadocMethodCheck (500 lines) */ final class TrimmedLeftTest { @Test void convertsText() { new Assertion<>( "Can't left trim a text", new TrimmedLeft(new TextOf(" Hello! \t ")), new TextHasString("Hello! \t ") ).affirm(); } @Test void trimmedBlankTextIsEmptyText() { new Assertion<>( "Can't trim a blank text", new TrimmedLeft(new TextOf(" \t ")), new TextHasString("") ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/text/TrimmedRightTest.java000066400000000000000000000035741400054650300251060ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.text; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.TextHasString; /** * Test case for {@link TrimmedRight}. * @since 0.12 * @checkstyle JavadocMethodCheck (500 lines) */ final class TrimmedRightTest { @Test void convertsText() { new Assertion<>( "Can't right trim a text", new TrimmedRight(new TextOf(" Hello! \t ")), new TextHasString(" Hello!") ).affirm(); } @Test void trimmedBlankTextIsEmptyText() { new Assertion<>( "Can't trim a blank text", new TrimmedRight(new TextOf(" \t ")), new TextHasString("") ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/text/TrimmedTest.java000066400000000000000000000035371400054650300241070ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.text; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.TextHasString; /** * Test case for {@link Trimmed}. * @since 0.1 * @checkstyle JavadocMethodCheck (500 lines) */ final class TrimmedTest { @Test void convertsText() { new Assertion<>( "Can't trim a text", new Trimmed(new TextOf(" Hello! \t ")), new TextHasString("Hello!") ).affirm(); } @Test void trimmedBlankTextIsEmptyText() { new Assertion<>( "Can't trim a blank text", new Trimmed(new TextOf(" \t ")), new TextHasString("") ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/text/UncheckedTextTest.java000066400000000000000000000102221400054650300252310ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.text; import java.io.IOException; import org.cactoos.Text; import org.hamcrest.core.IsEqual; import org.hamcrest.core.IsNot; import org.hamcrest.core.StringContains; import org.hamcrest.object.HasToString; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.Throws; /** * Test case for {@link UncheckedText}. * * @since 0.3 * @checkstyle JavadocMethodCheck (500 lines) * @checkstyle ClassDataAbstractionCouplingCheck (500 lines) */ final class UncheckedTextTest { @Test void rethrowsCheckedToUncheckedException() { final String msg = "intended"; new Assertion<>( "Must throw an exception when something goes wrong", new UncheckedText( () -> { throw new IOException(msg); } )::asString, new Throws<>( new StringContains(msg), RuntimeException.class ) ).affirm(); } @Test void toStringMustReturnSameOfAsString() { final String text = "one"; new Assertion<>( "Must implement #toString which returns the same of #asString", new UncheckedText( new TextOf(text) ), new HasToString<>( new IsEqual<>(text) ) ).affirm(); } @Test void equalsToTheSameTextObject() { final Text text = new TextOf("anything"); new Assertion<>( "Must match text representing the same value", new UncheckedText(text), new IsEqual<>(text) ).affirm(); } @Test void equalsOtherTextRepresentingTheSameValue() { new Assertion<>( "Must match another text representing the same value", new UncheckedText( new TextOf("abcdefghijkl") ), new IsEqual<>( new Joined("", "ab", "cde", "fghi", "j", "kl") ) ).affirm(); } @Test void equalsNonTextObject() { new Assertion<>( "Must does not match another object which is not a string", new UncheckedText( new TextOf("is not equals to null") ), new IsNot<>( new IsEqual<>(new Object()) ) ).affirm(); } @Test @SuppressWarnings("PMD.EqualsNull") void notEqualsWhenAnObjectIsNull() { new Assertion<>( "Must match equals null", new UncheckedText( new TextOf("is not equals to not Text object") ).equals(null), new IsEqual<>(false) ).affirm(); } @Test void matchTheSameHashCode() { final String text = "hashCode"; new Assertion<>( "Must match its represented String hashcode", new UncheckedText( new TextOf(text) ).hashCode(), new IsEqual<>(text.hashCode()) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/text/UpperTest.java000066400000000000000000000035051400054650300235740ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.text; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.TextHasString; /** * Test case for {@link Upper}. * @since 0.1 * @checkstyle JavadocMethodCheck (500 lines) */ final class UpperTest { @Test void convertsText() { new Assertion<>( "Can't upper case a text", new Upper(new TextOf("Hello!")), new TextHasString("HELLO!") ).affirm(); } @Test void convertsString() { new Assertion<>( "Can't upper case a string", new Upper("World!"), new TextHasString("WORLD!") ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/text/package-info.java000066400000000000000000000023071400054650300241640ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ /** * Texts, tests. * * @since 0.1 */ package org.cactoos.text; cactoos-0.49/src/test/java/org/cactoos/time/000077500000000000000000000000001400054650300207455ustar00rootroot00000000000000cactoos-0.49/src/test/java/org/cactoos/time/DateOfTest.java000066400000000000000000000072531400054650300236210ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.time; import java.time.LocalDateTime; import java.time.ZoneOffset; import java.time.format.DateTimeFormatter; import java.util.Date; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.ScalarHasValue; /** * Tests for DateOf. * @since 1.0 * @checkstyle JavadocMethodCheck (500 lines) * @checkstyle MagicNumberCheck (500 lines) */ @SuppressWarnings("PMD.AvoidDuplicateLiterals") public class DateOfTest { @Test public final void testParsingIsoFormattedStringToDate() { new Assertion<>( "must parse a Date with default/ISO format.", new DateOf("2017-12-13T14:15:16.000000017Z"), new ScalarHasValue<>( Date.from( LocalDateTime.of( 2017, 12, 13, 14, 15, 16, 17 ).toInstant(ZoneOffset.UTC) ) ) ).affirm(); } @Test public final void testParsingCustomFormattedStringToDate() { new Assertion<>( "must parse a Date with custom format.", new DateOf( "2017-12-13 14:15:16.000000017", "yyyy-MM-dd HH:mm:ss.n" ), new ScalarHasValue<>( Date.from( LocalDateTime.of( 2017, 12, 13, 14, 15, 16, 17 ).toInstant(ZoneOffset.UTC) ) ) ).affirm(); } @Test public final void testParsingCustomFormattedStringWithoutTimeToDate() { new Assertion<>( "must parse a Date with custom format.", new DateOf( "2018-01-01", "yyyy-MM-dd" ), new ScalarHasValue<>( Date.from( LocalDateTime.of( 2018, 01, 01, 0, 0, 0, 0 ).toInstant(ZoneOffset.UTC) ) ) ).affirm(); } @Test public final void testParsingCustomFormatterStringToDate() { new Assertion<>( "must parse a Date with custom format.", new DateOf( "2017-12-13 14:15:16.000000017", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.n") ), new ScalarHasValue<>( Date.from( LocalDateTime.of( 2017, 12, 13, 14, 15, 16, 17 ).toInstant(ZoneOffset.UTC) ) ) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/time/LocalDateTimeOfTest.java000066400000000000000000000054561400054650300254160ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.time; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.ScalarHasValue; /** * Tests for {@link LocalDateTimeOf}. * @since 1.0 * @checkstyle JavadocMethodCheck (500 lines) * @checkstyle MagicNumberCheck (500 lines) */ @SuppressWarnings("PMD.AvoidDuplicateLiterals") public class LocalDateTimeOfTest { @Test public final void testParsingIsoFormattedStringToLocalDateTime() { new Assertion<>( "Can't parse a LocalDateTime with default/ISO format.", new LocalDateTimeOf("2017-12-13T14:15:16.000000017+01:00"), new ScalarHasValue<>(LocalDateTime.of(2017, 12, 13, 14, 15, 16, 17)) ).affirm(); } @Test public final void testParsingFormattedStringWithFormatToLocalDateTime() { new Assertion<>( "Can't parse a LocalDateTime with custom format.", new LocalDateTimeOf( "2017-12-13 14:15:16.000000017", "yyyy-MM-dd HH:mm:ss.n" ), new ScalarHasValue<>(LocalDateTime.of(2017, 12, 13, 14, 15, 16, 17)) ).affirm(); } @Test public final void testParsingFormattedStringWithFormatterToLocalDateTime() { new Assertion<>( "Can't parse a LocalDateTime with custom formatter.", new LocalDateTimeOf( "2017-12-13 14:15:16.000000017", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.n") ), new ScalarHasValue<>(LocalDateTime.of(2017, 12, 13, 14, 15, 16, 17)) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/time/OffsetDateTimeOfTest.java000066400000000000000000000051661400054650300256100ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.time; import java.time.LocalDateTime; import java.time.OffsetDateTime; import java.time.ZoneOffset; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.ScalarHasValue; /** * Tests for {@link OffsetDateTimeOf}. * @since 1.0 * @checkstyle JavadocMethodCheck (500 lines) * @checkstyle MagicNumberCheck (500 lines) */ @SuppressWarnings("PMD.AvoidDuplicateLiterals") public class OffsetDateTimeOfTest { @Test public final void testParsingIsoFormattedStringToOffsetDateTime() { new Assertion<>( "Can't parse a OffsetDateTime with default/ISO format.", new OffsetDateTimeOf("2017-12-13T14:15:16.000000017+01:00"), new ScalarHasValue<>( OffsetDateTime.of( 2017, 12, 13, 14, 15, 16, 17, ZoneOffset.ofHours(1) ) ) ).affirm(); } @Test public final void testParsingFormattedStringWithOffsetToOffsetDateTime() { new Assertion<>( "Can't parse a OffsetDateTime with custom format.", new OffsetDateTimeOf( "2017-12-13 14:15:16", "yyyy-MM-dd HH:mm:ss", ZoneOffset.ofHours(1) ), new ScalarHasValue<>( OffsetDateTime.of( LocalDateTime.of(2017, 12, 13, 14, 15, 16), ZoneOffset.ofHours(1) ) ) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/time/ZonedDateTimeOfTest.java000066400000000000000000000065471400054650300254450ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.time; import java.time.LocalDateTime; import java.time.ZoneId; import java.time.ZoneOffset; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.ScalarHasValue; /** * Tests for {@link ZonedDateTimeOf}. * @since 1.0 * @checkstyle JavadocMethodCheck (500 lines) * @checkstyle MagicNumberCheck (500 lines) */ @SuppressWarnings("PMD.AvoidDuplicateLiterals") public class ZonedDateTimeOfTest { @Test public final void testParsingIsoFormattedStringToZonedDateTime() { new Assertion<>( "Can't parse a ZonedDateTime with default/ISO format.", new ZonedDateTimeOf("2017-12-13T14:15:16.000000017+01:00"), new ScalarHasValue<>( ZonedDateTime.of( 2017, 12, 13, 14, 15, 16, 17, ZoneId.ofOffset("", ZoneOffset.ofHours(1)) ) ) ).affirm(); } @Test public final void testParsingFormattedStringWithZoneToZonedDateTime() { new Assertion<>( "Can't parse a ZonedDateTime with custom format and zone.", new ZonedDateTimeOf( "2017-12-13 14:15:16", "yyyy-MM-dd HH:mm:ss", ZoneId.of("Europe/Berlin") ), new ScalarHasValue<>( ZonedDateTime.of( LocalDateTime.of(2017, 12, 13, 14, 15, 16), ZoneId.of("Europe/Berlin") ) ) ).affirm(); } @Test public final void testParsingFormattedStringWithFormatterToZonedDateTime() { new Assertion<>( "Can't parse a ZonedDateTime with custom format and zone.", new ZonedDateTimeOf( "2017-12-13 14:15:16", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss") .withZone(ZoneId.of("Europe/Berlin")) ), new ScalarHasValue<>( ZonedDateTime.of( LocalDateTime.of(2017, 12, 13, 14, 15, 16), ZoneId.of("Europe/Berlin") ) ) ).affirm(); } } cactoos-0.49/src/test/java/org/cactoos/time/package-info.java000066400000000000000000000023061400054650300241350ustar00rootroot00000000000000/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ /** * Time, tests. * * @since 1.0 */ package org.cactoos.time; cactoos-0.49/src/test/resources/000077500000000000000000000000001400054650300166565ustar00rootroot00000000000000cactoos-0.49/src/test/resources/forbidden-apis.txt000066400000000000000000000006321400054650300223060ustar00rootroot00000000000000@defaultMessage Do not use static methods org.hamcrest.Matchers @defaultMessage Please specify failure reason org.hamcrest.MatcherAssert#assertThat(java.lang.Object, org.hamcrest.Matcher) @defaultMessage Please specify failure reason org.junit.Assert#assertThat(java.lang.Object, org.hamcrest.Matcher) @defaultMessage Please avoid using static methods. java.util.Collections#unmodifiableList(java.util.List)cactoos-0.49/src/test/resources/org/000077500000000000000000000000001400054650300174455ustar00rootroot00000000000000cactoos-0.49/src/test/resources/org/cactoos/000077500000000000000000000000001400054650300211005ustar00rootroot00000000000000cactoos-0.49/src/test/resources/org/cactoos/digest-calculation.txt000066400000000000000000000002411400054650300254110ustar00rootroot00000000000000That file is used for digest calculation with different algorithms, so please DO NOT CHANGE IT. If you DO, then make sure all tests of DigestInvelope are passed.cactoos-0.49/src/test/resources/org/cactoos/large-text.txt000066400000000000000000002214501400054650300237210ustar00rootroot00000000000000Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Пугачев сидел в креслах на крыльце комендантского дома. На нем был красный казацкий кафтан, обшитый галунами. Высокая соболья шапка с золотыми кистями была надвинута на его сверкающие глаза. Лицо его показалось мне знакомо. Казацкие старшины окружали его. Отец Герасим, бледный и дрожащий, стоял у крыльца, с крестом в руках, и, казалось, молча умолял его за предстоящие жертвы. На площади ставили наскоро виселицу. Когда мы приближились, башкирцы разогнали народ и нас представили Пугачеву. Колокольный звон утих; настала глубокая тишина. «Который комендант?» — спросил самозванец. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. cactoos-0.49/src/test/resources/org/cactoos/small-text.txt000066400000000000000000000010061400054650300237300ustar00rootroot00000000000000Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodocactoos-0.49/src/verifier/000077500000000000000000000000001400054650300155005ustar00rootroot00000000000000cactoos-0.49/src/verifier/verifications.xml000066400000000000000000000030241400054650300210660ustar00rootroot00000000000000 true LICENSE.txt 2017-2020