[
  {
    "path": ".gitignore",
    "content": "sonatype.properties\r\n\r\n#built application files\r\n*.apk\r\n*.ap_\r\n\r\n# files for the dex VM\r\n*.dex\r\n\r\n# Java class files\r\n*.class\r\n\r\n# generated files\r\nbin/\r\ngen/\r\n\r\n# Local configuration file (sdk path, etc)\r\nlocal.properties\r\n\r\n# Windows thumbnail db\r\nThumbs.db\r\n\r\n# OSX files\r\n.DS_Store\r\n\r\n# Android Studio\r\n.idea/\r\n.gradle\r\nbuild/\r\n*.iml\r\ncaptures/\r\n.externalNativeBuild"
  },
  {
    "path": "LICENSE.txt",
    "content": "   Apache License\n   Version 2.0, January 2004\n   http://www.apache.org/licenses/\n\n   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n   1. Definitions.\n\n      \"License\" shall mean the terms and conditions for use, reproduction,\n      and distribution as defined by Sections 1 through 9 of this document.\n\n      \"Licensor\" shall mean the copyright owner or entity authorized by\n      the copyright owner that is granting the License.\n\n      \"Legal Entity\" shall mean the union of the acting entity and all\n      other entities that control, are controlled by, or are under common\n      control with that entity. For the purposes of this definition,\n      \"control\" means (i) the power, direct or indirect, to cause the\n      direction or management of such entity, whether by contract or\n      otherwise, or (ii) ownership of fifty percent (50%) or more of the\n      outstanding shares, or (iii) beneficial ownership of such entity.\n\n      \"You\" (or \"Your\") shall mean an individual or Legal Entity\n      exercising permissions granted by this License.\n\n      \"Source\" form shall mean the preferred form for making modifications,\n      including but not limited to software source code, documentation\n      source, and configuration files.\n\n      \"Object\" form shall mean any form resulting from mechanical\n      transformation or translation of a Source form, including but\n      not limited to compiled object code, generated documentation,\n      and conversions to other media types.\n\n      \"Work\" shall mean the work of authorship, whether in Source or\n      Object form, made available under the License, as indicated by a\n      copyright notice that is included in or attached to the work\n      (an example is provided in the Appendix below).\n\n      \"Derivative Works\" shall mean any work, whether in Source or Object\n      form, that is based on (or derived from) the Work and for which the\n      editorial revisions, annotations, elaborations, or other modifications\n      represent, as a whole, an original work of authorship. For the purposes\n      of this License, Derivative Works shall not include works that remain\n      separable from, or merely link (or bind by name) to the interfaces of,\n      the Work and Derivative Works thereof.\n\n      \"Contribution\" shall mean any work of authorship, including\n      the original version of the Work and any modifications or additions\n      to that Work or Derivative Works thereof, that is intentionally\n      submitted to Licensor for inclusion in the Work by the copyright owner\n      or by an individual or Legal Entity authorized to submit on behalf of\n      the copyright owner. For the purposes of this definition, \"submitted\"\n      means any form of electronic, verbal, or written communication sent\n      to the Licensor or its representatives, including but not limited to\n      communication on electronic mailing lists, source code control systems,\n      and issue tracking systems that are managed by, or on behalf of, the\n      Licensor for the purpose of discussing and improving the Work, but\n      excluding communication that is conspicuously marked or otherwise\n      designated in writing by the copyright owner as \"Not a Contribution.\"\n\n      \"Contributor\" shall mean Licensor and any individual or Legal Entity\n      on behalf of whom a Contribution has been received by Licensor and\n      subsequently incorporated within the Work.\n\n   2. Grant of Copyright License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      copyright license to reproduce, prepare Derivative Works of,\n      publicly display, publicly perform, sublicense, and distribute the\n      Work and such Derivative Works in Source or Object form.\n\n   3. Grant of Patent License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      (except as stated in this section) patent license to make, have made,\n      use, offer to sell, sell, import, and otherwise transfer the Work,\n      where such license applies only to those patent claims licensable\n      by such Contributor that are necessarily infringed by their\n      Contribution(s) alone or by combination of their Contribution(s)\n      with the Work to which such Contribution(s) was submitted. If You\n      institute patent litigation against any entity (including a\n      cross-claim or counterclaim in a lawsuit) alleging that the Work\n      or a Contribution incorporated within the Work constitutes direct\n      or contributory patent infringement, then any patent licenses\n      granted to You under this License for that Work shall terminate\n      as of the date such litigation is filed.\n\n   4. Redistribution. You may reproduce and distribute copies of the\n      Work or Derivative Works thereof in any medium, with or without\n      modifications, and in Source or Object form, provided that You\n      meet the following conditions:\n\n      (a) You must give any other recipients of the Work or\n          Derivative Works a copy of this License; and\n\n      (b) You must cause any modified files to carry prominent notices\n          stating that You changed the files; and\n\n      (c) You must retain, in the Source form of any Derivative Works\n          that You distribute, all copyright, patent, trademark, and\n          attribution notices from the Source form of the Work,\n          excluding those notices that do not pertain to any part of\n          the Derivative Works; and\n\n      (d) If the Work includes a \"NOTICE\" text file as part of its\n          distribution, then any Derivative Works that You distribute must\n          include a readable copy of the attribution notices contained\n          within such NOTICE file, excluding those notices that do not\n          pertain to any part of the Derivative Works, in at least one\n          of the following places: within a NOTICE text file distributed\n          as part of the Derivative Works; within the Source form or\n          documentation, if provided along with the Derivative Works; or,\n          within a display generated by the Derivative Works, if and\n          wherever such third-party notices normally appear. The contents\n          of the NOTICE file are for informational purposes only and\n          do not modify the License. You may add Your own attribution\n          notices within Derivative Works that You distribute, alongside\n          or as an addendum to the NOTICE text from the Work, provided\n          that such additional attribution notices cannot be construed\n          as modifying the License.\n\n      You may add Your own copyright statement to Your modifications and\n      may provide additional or different license terms and conditions\n      for use, reproduction, or distribution of Your modifications, or\n      for any such Derivative Works as a whole, provided Your use,\n      reproduction, and distribution of the Work otherwise complies with\n      the conditions stated in this License.\n\n   5. Submission of Contributions. Unless You explicitly state otherwise,\n      any Contribution intentionally submitted for inclusion in the Work\n      by You to the Licensor shall be under the terms and conditions of\n      this License, without any additional terms or conditions.\n      Notwithstanding the above, nothing herein shall supersede or modify\n      the terms of any separate license agreement you may have executed\n      with Licensor regarding such Contributions.\n\n   6. Trademarks. This License does not grant permission to use the trade\n      names, trademarks, service marks, or product names of the Licensor,\n      except as required for reasonable and customary use in describing the\n      origin of the Work and reproducing the content of the NOTICE file.\n\n   7. Disclaimer of Warranty. Unless required by applicable law or\n      agreed to in writing, Licensor provides the Work (and each\n      Contributor provides its Contributions) on an \"AS IS\" BASIS,\n      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n      implied, including, without limitation, any warranties or conditions\n      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n      PARTICULAR PURPOSE. You are solely responsible for determining the\n      appropriateness of using or redistributing the Work and assume any\n      risks associated with Your exercise of permissions under this License.\n\n   8. Limitation of Liability. In no event and under no legal theory,\n      whether in tort (including negligence), contract, or otherwise,\n      unless required by applicable law (such as deliberate and grossly\n      negligent acts) or agreed to in writing, shall any Contributor be\n      liable to You for damages, including any direct, indirect, special,\n      incidental, or consequential damages of any character arising as a\n      result of this License or out of the use or inability to use the\n      Work (including but not limited to damages for loss of goodwill,\n      work stoppage, computer failure or malfunction, or any and all\n      other commercial damages or losses), even if such Contributor\n      has been advised of the possibility of such damages.\n\n   9. Accepting Warranty or Additional Liability. While redistributing\n      the Work or Derivative Works thereof, You may choose to offer,\n      and charge a fee for, acceptance of support, warranty, indemnity,\n      or other liability obligations and/or rights consistent with this\n      License. However, in accepting such obligations, You may act only\n      on Your own behalf and on Your sole responsibility, not on behalf\n      of any other Contributor, and only if You agree to indemnify,\n      defend, and hold each Contributor harmless for any liability\n      incurred by, or claims asserted against, such Contributor by reason\n      of your accepting any such warranty or additional liability.\n\n   END OF TERMS AND CONDITIONS\n\n   APPENDIX: How to apply the Apache License to your work.\n\n      To apply the Apache License to your work, attach the following\n      boilerplate notice, with the fields enclosed by brackets \"{}\"\n      replaced with your own identifying information. (Don't include\n      the brackets!)  The text should be enclosed in the appropriate\n      comment syntax for the file format. We also recommend that a\n      file or class name and description of purpose be included on the\n      same \"printed page\" as the copyright notice for easier\n      identification within third-party archives.\n\n   Copyright {yyyy} {name of copyright owner}\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n"
  },
  {
    "path": "README.md",
    "content": "# ThreadPoster\n\nLightweight library for unit testable and expressive multi-threading in Android.\n\n**ThreadPoster is in public beta**. I'm actively looking for feedback on project's structure, naming and usability. Bug reports are also welcome, of course.\n\n## Install\n\nTo use ThreadPoster in your project, make sure that you have Maven Central set up in your root `build.gradle` script:\n\n```\nallprojects {\n    repositories {\n        google()\n        mavenCentral()\n    }\n}\n```\n\nThen add ThreadPoster as a dependency into your main module's (called `app` by default) `build.gradle` script:\n\n```\ndependencies {\n    implementation 'com.techyourchance:threadposter:1.0.1'\n}\n```\n\n## Usage\nAt the core of this library are two simple classes: `UiThreadPoster` and `BackgroundThreadPoster`.\n\n### Executing code on UI thread\nIn the following example, `updateText(String)` can be safely called on any thread. The actual UI update will always take place on UI thread:\n\n```java\npublic class TextUpdater {\n\n    private final UiThreadPoster mUiThreadPoster;\n    private final TextView mTxtSample;\n    \n    public void updateText(final String text) {\n        mUiThreadPoster.post(() -> {\n            mTxtSample.setText(text);\n        });\n    }\n}\n```\n\n### Executing code on \"background\" thread\nIn the following example, `fetchAndCacheUserDetails(String)` can be safely called on any thread. The actual network request and data caching will always take place on background thread (non-UI thread):\n\n```java\npublic class UpdateUserDetailsUseCase {\n\n    private final BackgroundThreadPoster mBackgroundThreadPoster;\n    private final UserDetailsEndpoint mUserDetailsEndpoint;\n    private final UserDetailsCache mUserDetailsCache;\n\n    public void fetchAndCacheUserDetails(final String userId) {\n        mBackgroundThreadPoster.post(() -> {\n            UserDetails userDetails = mUserDetailsEndpoint.fetchUserDetails(userId);\n            mUserDetailsCache.cacheUserDetails(userDetails);\n        });\n    }\n}\n```\n\n### Executing code on \"background\" thread and notifying Observers on UI thread\nIn the [following example](sample/src/main/java/com/techyourchance/threadposters/FetchDataUseCase.java), `fetchData()` can be safely called on any thread. The actual data fetch will always take place on background thread, and the observers will always be notified on UI thread:\n\n```java\npublic class FetchDataUseCase {\n\n    public interface Listener {\n        void onDataFetched(String data);\n        void onDataFetchFailed();\n    }\n\n    private final FakeDataFetcher mFakeDataFetcher;\n    private final BackgroundThreadPoster mBackgroundThreadPoster;\n    private final UiThreadPoster mUiThreadPoster;\n\n    public void fetchData() {\n        // offload work to background thread\n        mBackgroundThreadPoster.post(() -> {\n            fetchDataSync();\n        });\n    }\n\n    @WorkerThread\n    private void fetchDataSync() {\n        try {\n            final String data = mFakeDataFetcher.getData();\n            mUiThreadPoster.post(() -> {\n                notifySuccess(data); // notify listeners on UI thread\n            });\n        } catch (FakeDataFetcher.DataFetchException e) {\n            mUiThreadPoster.post(() -> {\n                notifyFailure(); // notify listeners on UI thread\n            });\n        }\n\n    }\n\n    @UiThread\n    private void notifyFailure() {\n        for (Listener listener : mListeners) {\n            listener.onDataFetchFailed();\n        }\n    }\n\n    @UiThread\n    private void notifySuccess(String data) {\n        for (Listener listener : mListeners) {\n            listener.onDataFetched(data);\n        }\n    }\n\n}\n```\n\n## Unit Testing\n\nThis library allows for easy unit testing of multithreaded code.\n\n**Important note: no amount of unit testing can guarantee that your code is thread-safe. In other words, even if your unit tests pass, your code can still be subject to race conditions, deadlocks, livelocks, etc.**\n\nTo support unit testing, ThreadPosters library is shipped with test double implementations for both `UiThreadPoster` and `BackgroundThreadPoster`. The core feature of these test doubles is that they are truly multi-threaded. In other words, when you unit test using these test doubles, you exercise your code in real multi-threaded environment which is the best approximation of the real production setting.\n\n### Benefits and drawbacks of multi-threaded unit testing\n\nThe approach employed by ThreadPoster's test doubles has its benefits and drawbacks.\n\n**Benefits of multi-threaded unit testing:**\n1. Exercises the code in real production setting.\n2. Has a chance to find multi-threading bugs. This will manifest itself in the form of \"flaky\" tests (tests that fail ocassionally).\n\n**Drawbacks of multi-threaded unit testing:**\n1. Longer unit tests execution times.\n2. Requires user assistance in the form of an additional step in each test case (`join()` calls in the examples below).\n\nOn my machine, test cases that use ThreadPoster test doubles execute in ~10ms (as opposed to <1ms for plain Java). That's not an issue if you have 100 multi-threaded test cases, but it's a show stopper for proper TDD if you have 1000.\n\nThe upside is that absolute majority of your classes shoudln't be multi-threaded, which means that the overall percentage of slow unit tests should be low.\n\nI'm currently working on ways to optimize the test times, but you should definitely keep this drawback in mind if you intend to unit test using ThreadPoster test doubles.\n\n### Example unit test\n\nBelow code shows a unit test that makes use of ThreadPoster test doubles. It's part of the sample project.\n\nNote the calls to `mThreadPostersTestDouble.join()` in tests - that's the drawback number two. Since test cases become multithreaded, JUnit can't control tests' execution by itself anymore. \nTherefore, you'll need to call `mThreadPostersTestDouble.join()` before the assertions stage in each of your test cases. This makes sure that all involved threads run to completion and their side effects will be visible during assertions stage.\n\n```java\npublic class FetchDataUseCaseTest {\n\n    private static final String TEST_DATA = \"testData\";\n\n    private ThreadPostersTestDouble mThreadPostersTestDouble = new ThreadPostersTestDouble();\n\n    private FakeDataFetcher mFakeDataFetcherMock;\n    private FetchDataUseCase.Listener mListener1;\n    private FetchDataUseCase.Listener mListener2;\n\n    private FetchDataUseCase SUT;\n\n    @Before\n    public void setup() throws Exception {\n        mFakeDataFetcherMock = mock(FakeDataFetcher.class);\n\n        SUT = new FetchDataUseCase(\n                mFakeDataFetcherMock,\n                mThreadPostersTestDouble.getBackgroundTestDouble(),\n                mThreadPostersTestDouble.getUiTestDouble());\n\n        mListener1 = mock(FetchDataUseCase.Listener.class);\n        mListener2 = mock(FetchDataUseCase.Listener.class);\n    }\n\n    @Test\n    public void fetchData_successNoListeners_completesWithoutErrors() throws Exception {\n        // Arrange\n        when(mFakeDataFetcherMock.getData()).thenReturn(TEST_DATA);\n        // Act\n        SUT.fetchData();\n        // Assert\n\n        // needs to be called before assertions in order for all threads to complete and\n        // all side effects to be present\n        mThreadPostersTestDouble.join();\n\n        assertThat(true, is(true));\n    }\n\n    @Test\n    public void fetchData_successMultipleListeners_notifiedWithCorrectData() throws Exception {\n        // Arrange\n        when(mFakeDataFetcherMock.getData()).thenReturn(TEST_DATA);\n        ArgumentCaptor<String> ac = ArgumentCaptor.forClass(String.class);\n        // Act\n        SUT.registerListener(mListener1);\n        SUT.registerListener(mListener2);\n        SUT.fetchData();\n        // Assert\n\n        // needs to be called before assertions in order for all threads to complete and\n        // all side effects to be present\n        mThreadPostersTestDouble.join();\n\n        verify(mListener1).onDataFetched(TEST_DATA);\n        verify(mListener2).onDataFetched(TEST_DATA);\n    }\n\n    @Test\n    public void fetchData_failureMultipleListeners_notifiedOfFailure() throws Exception {\n        // Arrange\n        doThrow(new FakeDataFetcher.DataFetchException()).when(mFakeDataFetcherMock).getData();\n        // Act\n        SUT.registerListener(mListener1);\n        SUT.registerListener(mListener2);\n        SUT.fetchData();\n        // Assert\n\n        // needs to be called before assertions in order for all threads to complete and\n        // all side effects to be present\n        mThreadPostersTestDouble.join();\n\n        verify(mListener1).onDataFetchFailed();\n        verify(mListener2).onDataFetchFailed();\n    }\n\n}\n```\n\n## License\n\nThis project is licensed under the Apache-2.0 License - see the [LICENSE.txt](LICENSE.txt) file for details\n\n"
  },
  {
    "path": "build.gradle",
    "content": "// Top-level build file where you can add configuration options common to all sub-projects/modules.\n\nbuildscript {\n    repositories {\n        google()\n        mavenCentral()\n    }\n\n    dependencies {\n        classpath 'com.android.tools.build:gradle:4.1.1'\n    }\n}\n\nallprojects {\n    repositories {\n        google()\n        mavenCentral()\n    }\n}\n\next {\n    compileSdkVersion = 30\n    buildToolsVersion = \"30.0.2\"\n    supportLibVersion = \"27.1.1\"\n    junitVersion = \"4.13\"\n    mockitoVersion = \"2.19.0\"\n}\n\n\ntask clean(type: Delete) {\n    delete rootProject.buildDir\n}\n"
  },
  {
    "path": "gradle/wrapper/gradle-wrapper.properties",
    "content": "#Wed Nov 18 09:35:17 CET 2020\ndistributionBase=GRADLE_USER_HOME\ndistributionPath=wrapper/dists\nzipStoreBase=GRADLE_USER_HOME\nzipStorePath=wrapper/dists\ndistributionUrl=https\\://services.gradle.org/distributions/gradle-6.5-all.zip\n"
  },
  {
    "path": "gradle.properties",
    "content": "# Project-wide Gradle settings.\n\n# IDE (e.g. Android Studio) users:\n# Gradle settings configured through the IDE *will override*\n# any settings specified in this file.\n\n# For more details on how to configure your build environment visit\n# http://www.gradle.org/docs/current/userguide/build_environment.html\n\n# Specifies the JVM arguments used for the daemon process.\n# The setting is particularly useful for tweaking memory settings.\norg.gradle.jvmargs=-Xmx1536m\n\n# When configured, Gradle will run in incubating parallel mode.\n# This option should only be used with decoupled projects. More details, visit\n# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects\n# org.gradle.parallel=true\n"
  },
  {
    "path": "gradlew",
    "content": "#!/usr/bin/env bash\n\n##############################################################################\n##\n##  Gradle start up script for UN*X\n##\n##############################################################################\n\n# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.\nDEFAULT_JVM_OPTS=\"\"\n\nAPP_NAME=\"Gradle\"\nAPP_BASE_NAME=`basename \"$0\"`\n\n# Use the maximum available, or set MAX_FD != -1 to use that value.\nMAX_FD=\"maximum\"\n\nwarn ( ) {\n    echo \"$*\"\n}\n\ndie ( ) {\n    echo\n    echo \"$*\"\n    echo\n    exit 1\n}\n\n# OS specific support (must be 'true' or 'false').\ncygwin=false\nmsys=false\ndarwin=false\ncase \"`uname`\" in\n  CYGWIN* )\n    cygwin=true\n    ;;\n  Darwin* )\n    darwin=true\n    ;;\n  MINGW* )\n    msys=true\n    ;;\nesac\n\n# Attempt to set APP_HOME\n# Resolve links: $0 may be a link\nPRG=\"$0\"\n# Need this for relative symlinks.\nwhile [ -h \"$PRG\" ] ; do\n    ls=`ls -ld \"$PRG\"`\n    link=`expr \"$ls\" : '.*-> \\(.*\\)$'`\n    if expr \"$link\" : '/.*' > /dev/null; then\n        PRG=\"$link\"\n    else\n        PRG=`dirname \"$PRG\"`\"/$link\"\n    fi\ndone\nSAVED=\"`pwd`\"\ncd \"`dirname \\\"$PRG\\\"`/\" >/dev/null\nAPP_HOME=\"`pwd -P`\"\ncd \"$SAVED\" >/dev/null\n\nCLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar\n\n# Determine the Java command to use to start the JVM.\nif [ -n \"$JAVA_HOME\" ] ; then\n    if [ -x \"$JAVA_HOME/jre/sh/java\" ] ; then\n        # IBM's JDK on AIX uses strange locations for the executables\n        JAVACMD=\"$JAVA_HOME/jre/sh/java\"\n    else\n        JAVACMD=\"$JAVA_HOME/bin/java\"\n    fi\n    if [ ! -x \"$JAVACMD\" ] ; then\n        die \"ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME\n\nPlease set the JAVA_HOME variable in your environment to match the\nlocation of your Java installation.\"\n    fi\nelse\n    JAVACMD=\"java\"\n    which java >/dev/null 2>&1 || die \"ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.\n\nPlease set the JAVA_HOME variable in your environment to match the\nlocation of your Java installation.\"\nfi\n\n# Increase the maximum file descriptors if we can.\nif [ \"$cygwin\" = \"false\" -a \"$darwin\" = \"false\" ] ; then\n    MAX_FD_LIMIT=`ulimit -H -n`\n    if [ $? -eq 0 ] ; then\n        if [ \"$MAX_FD\" = \"maximum\" -o \"$MAX_FD\" = \"max\" ] ; then\n            MAX_FD=\"$MAX_FD_LIMIT\"\n        fi\n        ulimit -n $MAX_FD\n        if [ $? -ne 0 ] ; then\n            warn \"Could not set maximum file descriptor limit: $MAX_FD\"\n        fi\n    else\n        warn \"Could not query maximum file descriptor limit: $MAX_FD_LIMIT\"\n    fi\nfi\n\n# For Darwin, add options to specify how the application appears in the dock\nif $darwin; then\n    GRADLE_OPTS=\"$GRADLE_OPTS \\\"-Xdock:name=$APP_NAME\\\" \\\"-Xdock:icon=$APP_HOME/media/gradle.icns\\\"\"\nfi\n\n# For Cygwin, switch paths to Windows format before running java\nif $cygwin ; then\n    APP_HOME=`cygpath --path --mixed \"$APP_HOME\"`\n    CLASSPATH=`cygpath --path --mixed \"$CLASSPATH\"`\n    JAVACMD=`cygpath --unix \"$JAVACMD\"`\n\n    # We build the pattern for arguments to be converted via cygpath\n    ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`\n    SEP=\"\"\n    for dir in $ROOTDIRSRAW ; do\n        ROOTDIRS=\"$ROOTDIRS$SEP$dir\"\n        SEP=\"|\"\n    done\n    OURCYGPATTERN=\"(^($ROOTDIRS))\"\n    # Add a user-defined pattern to the cygpath arguments\n    if [ \"$GRADLE_CYGPATTERN\" != \"\" ] ; then\n        OURCYGPATTERN=\"$OURCYGPATTERN|($GRADLE_CYGPATTERN)\"\n    fi\n    # Now convert the arguments - kludge to limit ourselves to /bin/sh\n    i=0\n    for arg in \"$@\" ; do\n        CHECK=`echo \"$arg\"|egrep -c \"$OURCYGPATTERN\" -`\n        CHECK2=`echo \"$arg\"|egrep -c \"^-\"`                                 ### Determine if an option\n\n        if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then                    ### Added a condition\n            eval `echo args$i`=`cygpath --path --ignore --mixed \"$arg\"`\n        else\n            eval `echo args$i`=\"\\\"$arg\\\"\"\n        fi\n        i=$((i+1))\n    done\n    case $i in\n        (0) set -- ;;\n        (1) set -- \"$args0\" ;;\n        (2) set -- \"$args0\" \"$args1\" ;;\n        (3) set -- \"$args0\" \"$args1\" \"$args2\" ;;\n        (4) set -- \"$args0\" \"$args1\" \"$args2\" \"$args3\" ;;\n        (5) set -- \"$args0\" \"$args1\" \"$args2\" \"$args3\" \"$args4\" ;;\n        (6) set -- \"$args0\" \"$args1\" \"$args2\" \"$args3\" \"$args4\" \"$args5\" ;;\n        (7) set -- \"$args0\" \"$args1\" \"$args2\" \"$args3\" \"$args4\" \"$args5\" \"$args6\" ;;\n        (8) set -- \"$args0\" \"$args1\" \"$args2\" \"$args3\" \"$args4\" \"$args5\" \"$args6\" \"$args7\" ;;\n        (9) set -- \"$args0\" \"$args1\" \"$args2\" \"$args3\" \"$args4\" \"$args5\" \"$args6\" \"$args7\" \"$args8\" ;;\n    esac\nfi\n\n# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules\nfunction splitJvmOpts() {\n    JVM_OPTS=(\"$@\")\n}\neval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS\nJVM_OPTS[${#JVM_OPTS[*]}]=\"-Dorg.gradle.appname=$APP_BASE_NAME\"\n\nexec \"$JAVACMD\" \"${JVM_OPTS[@]}\" -classpath \"$CLASSPATH\" org.gradle.wrapper.GradleWrapperMain \"$@\"\n"
  },
  {
    "path": "gradlew.bat",
    "content": "@if \"%DEBUG%\" == \"\" @echo off\r\n@rem ##########################################################################\r\n@rem\r\n@rem  Gradle startup script for Windows\r\n@rem\r\n@rem ##########################################################################\r\n\r\n@rem Set local scope for the variables with windows NT shell\r\nif \"%OS%\"==\"Windows_NT\" setlocal\r\n\r\n@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.\r\nset DEFAULT_JVM_OPTS=\r\n\r\nset DIRNAME=%~dp0\r\nif \"%DIRNAME%\" == \"\" set DIRNAME=.\r\nset APP_BASE_NAME=%~n0\r\nset APP_HOME=%DIRNAME%\r\n\r\n@rem Find java.exe\r\nif defined JAVA_HOME goto findJavaFromJavaHome\r\n\r\nset JAVA_EXE=java.exe\r\n%JAVA_EXE% -version >NUL 2>&1\r\nif \"%ERRORLEVEL%\" == \"0\" goto init\r\n\r\necho.\r\necho ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.\r\necho.\r\necho Please set the JAVA_HOME variable in your environment to match the\r\necho location of your Java installation.\r\n\r\ngoto fail\r\n\r\n:findJavaFromJavaHome\r\nset JAVA_HOME=%JAVA_HOME:\"=%\r\nset JAVA_EXE=%JAVA_HOME%/bin/java.exe\r\n\r\nif exist \"%JAVA_EXE%\" goto init\r\n\r\necho.\r\necho ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%\r\necho.\r\necho Please set the JAVA_HOME variable in your environment to match the\r\necho location of your Java installation.\r\n\r\ngoto fail\r\n\r\n:init\r\n@rem Get command-line arguments, handling Windowz variants\r\n\r\nif not \"%OS%\" == \"Windows_NT\" goto win9xME_args\r\nif \"%@eval[2+2]\" == \"4\" goto 4NT_args\r\n\r\n:win9xME_args\r\n@rem Slurp the command line arguments.\r\nset CMD_LINE_ARGS=\r\nset _SKIP=2\r\n\r\n:win9xME_args_slurp\r\nif \"x%~1\" == \"x\" goto execute\r\n\r\nset CMD_LINE_ARGS=%*\r\ngoto execute\r\n\r\n:4NT_args\r\n@rem Get arguments from the 4NT Shell from JP Software\r\nset CMD_LINE_ARGS=%$\r\n\r\n:execute\r\n@rem Setup the command line\r\n\r\nset CLASSPATH=%APP_HOME%\\gradle\\wrapper\\gradle-wrapper.jar\r\n\r\n@rem Execute Gradle\r\n\"%JAVA_EXE%\" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% \"-Dorg.gradle.appname=%APP_BASE_NAME%\" -classpath \"%CLASSPATH%\" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%\r\n\r\n:end\r\n@rem End local scope for the variables with windows NT shell\r\nif \"%ERRORLEVEL%\"==\"0\" goto mainEnd\r\n\r\n:fail\r\nrem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of\r\nrem the _cmd.exe /c_ return code!\r\nif  not \"\" == \"%GRADLE_EXIT_CONSOLE%\" exit 1\r\nexit /b 1\r\n\r\n:mainEnd\r\nif \"%OS%\"==\"Windows_NT\" endlocal\r\n\r\n:omega\r\n"
  },
  {
    "path": "sample/.gitignore",
    "content": "/build\n"
  },
  {
    "path": "sample/build.gradle",
    "content": "apply plugin: 'com.android.application'\n\nandroid {\n    compileSdkVersion rootProject.ext.compileSdkVersion\n    buildToolsVersion rootProject.ext.buildToolsVersion\n\n    defaultConfig {\n        applicationId \"com.techyourchance.threadposters\"\n        minSdkVersion 16\n        targetSdkVersion 28\n        versionCode 1\n        versionName \"1.0\"\n    }\n\n    buildTypes {\n        release {\n            minifyEnabled false\n            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'\n        }\n    }\n}\n\ndependencies {\n    implementation project(path: ':threadposter')\n    implementation fileTree(dir: 'libs', include: ['*.jar'])\n\n    implementation \"com.android.support:appcompat-v7:${rootProject.ext.supportLibVersion}\"\n\n    testImplementation \"junit:junit:${rootProject.ext.junitVersion}\"\n    testImplementation \"org.mockito:mockito-core:${rootProject.ext.mockitoVersion}\"\n}\n"
  },
  {
    "path": "sample/proguard-rules.pro",
    "content": "# Add project specific ProGuard rules here.\n# By default, the flags in this file are appended to flags specified\n# in /Users/Vasiliy/Library/Android/sdk/tools/proguard/proguard-android.txt\n# You can edit the include path and order by changing the proguardFiles\n# directive in build.gradle.\n#\n# For more details, see\n#   http://developer.android.com/guide/developing/tools/proguard.html\n\n# Add any project specific keep options here:\n\n# If your project uses WebView with JS, uncomment the following\n# and specify the fully qualified class name to the JavaScript interface\n# class:\n#-keepclassmembers class fqcn.of.javascript.interface.for.webview {\n#   public *;\n#}\n\n# Uncomment this to preserve the line number information for\n# debugging stack traces.\n#-keepattributes SourceFile,LineNumberTable\n\n# If you keep the line number information, uncomment this to\n# hide the original source file name.\n#-renamesourcefileattribute SourceFile\n"
  },
  {
    "path": "sample/src/main/AndroidManifest.xml",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest package=\"com.techyourchance.threadposters\"\n          xmlns:android=\"http://schemas.android.com/apk/res/android\">\n\n    <application\n        android:name=\".SampleApplication\"\n        android:allowBackup=\"true\"\n        android:icon=\"@mipmap/ic_launcher\"\n        android:label=\"@string/app_name\"\n        android:roundIcon=\"@mipmap/ic_launcher_round\"\n        android:supportsRtl=\"true\"\n        android:theme=\"@style/AppTheme\">\n        <activity android:name=\".SampleActivity\">\n            <intent-filter>\n                <action android:name=\"android.intent.action.MAIN\"/>\n\n                <category android:name=\"android.intent.category.LAUNCHER\"/>\n            </intent-filter>\n        </activity>\n    </application>\n\n</manifest>"
  },
  {
    "path": "sample/src/main/java/com/techyourchance/threadposters/FakeDataFetcher.java",
    "content": "package com.techyourchance.threadposters;\r\n\r\nimport android.support.annotation.WorkerThread;\r\n\r\npublic class FakeDataFetcher {\r\n\r\n    public static class DataFetchException extends Exception {}\r\n\r\n    private boolean mIsError = true;\r\n\r\n    @WorkerThread\r\n    public String getData() throws DataFetchException {\r\n\r\n        // simulate 2 seconds worth of work\r\n        try {\r\n            Thread.sleep(2000);\r\n        } catch (InterruptedException e) {\r\n            e.printStackTrace();\r\n        }\r\n\r\n        mIsError = !mIsError; // error response every other time\r\n\r\n        if (mIsError) {\r\n            throw new DataFetchException();\r\n        } else {\r\n            return \"fake data\";\r\n        }\r\n\r\n    }\r\n}\r\n"
  },
  {
    "path": "sample/src/main/java/com/techyourchance/threadposters/FetchDataUseCase.java",
    "content": "package com.techyourchance.threadposters;\r\n\r\nimport android.support.annotation.UiThread;\r\nimport android.support.annotation.WorkerThread;\r\n\r\nimport com.techyourchance.threadposter.UiThreadPoster;\r\nimport com.techyourchance.threadposter.BackgroundThreadPoster;\r\n\r\nimport java.util.Collections;\r\nimport java.util.Set;\r\nimport java.util.concurrent.ConcurrentHashMap;\r\n\r\npublic class FetchDataUseCase {\r\n\r\n    public interface Listener {\r\n        void onDataFetched(String data);\r\n        void onDataFetchFailed();\r\n    }\r\n\r\n    private final FakeDataFetcher mFakeDataFetcher;\r\n    private final BackgroundThreadPoster mBackgroundThreadPoster;\r\n    private final UiThreadPoster mUiThreadPoster;\r\n\r\n    private final Set<Listener> mListeners = Collections.newSetFromMap(\r\n            new ConcurrentHashMap<Listener, Boolean>());\r\n\r\n    public FetchDataUseCase(FakeDataFetcher fakeDataFetcher,\r\n                            BackgroundThreadPoster backgroundThreadPoster,\r\n                            UiThreadPoster uiThreadPoster) {\r\n        mFakeDataFetcher = fakeDataFetcher;\r\n        mBackgroundThreadPoster = backgroundThreadPoster;\r\n        mUiThreadPoster = uiThreadPoster;\r\n    }\r\n\r\n    public void registerListener(Listener listener) {\r\n        mListeners.add(listener);\r\n    }\r\n\r\n    public void unregisterListener(Listener listener) {\r\n        mListeners.remove(listener);\r\n    }\r\n\r\n    public void fetchData() {\r\n        // offload work to background thread\r\n        mBackgroundThreadPoster.post(new Runnable() {\r\n            @Override\r\n            public void run() {\r\n                fetchDataSync();\r\n            }\r\n        });\r\n    }\r\n\r\n    @WorkerThread\r\n    private void fetchDataSync() {\r\n        try {\r\n            final String data = mFakeDataFetcher.getData();\r\n            mUiThreadPoster.post(new Runnable() { // notify listeners on UI thread\r\n                @Override\r\n                public void run() {\r\n                    notifySuccess(data);\r\n                }\r\n            });\r\n        } catch (FakeDataFetcher.DataFetchException e) {\r\n            mUiThreadPoster.post(new Runnable() { // notify listeners on UI thread\r\n                @Override\r\n                public void run() {\r\n                    notifyFailure();\r\n                }\r\n            });\r\n        }\r\n\r\n    }\r\n\r\n    @UiThread\r\n    private void notifyFailure() {\r\n        for (Listener listener : mListeners) {\r\n            listener.onDataFetchFailed();\r\n        }\r\n    }\r\n\r\n    @UiThread\r\n    private void notifySuccess(String data) {\r\n        for (Listener listener : mListeners) {\r\n            listener.onDataFetched(data);\r\n        }\r\n    }\r\n\r\n}\r\n"
  },
  {
    "path": "sample/src/main/java/com/techyourchance/threadposters/SampleActivity.java",
    "content": "package com.techyourchance.threadposters;\n\nimport android.os.Bundle;\nimport android.support.v7.app.AppCompatActivity;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.ProgressBar;\nimport android.widget.TextView;\n\npublic class SampleActivity extends AppCompatActivity implements FetchDataUseCase.Listener {\n\n    private Button mBtnFetchData;\n    private ProgressBar mProgressWorking;\n    private TextView mTxtData;\n    private TextView mTxtError;\n\n    private FetchDataUseCase mFetchDataUseCase;\n\n    @Override\n    protected void onCreate(Bundle savedInstanceState) {\n        super.onCreate(savedInstanceState);\n        setContentView(R.layout.activity_sample);\n\n        mFetchDataUseCase = ((SampleApplication)getApplication()).getFetchDataUseCase();\n\n        mBtnFetchData = (Button) findViewById(R.id.btn_fetch_data);\n        mProgressWorking = (ProgressBar) findViewById(R.id.progress_working);\n        mTxtData = (TextView) findViewById(R.id.txt_data);\n        mTxtError = (TextView) findViewById(R.id.txt_error);\n\n        mBtnFetchData.setOnClickListener(new View.OnClickListener() {\n            @Override\n            public void onClick(View v) {\n                fetchData();\n            }\n        });\n\n    }\n\n    @Override\n    protected void onStart() {\n        super.onStart();\n        mFetchDataUseCase.registerListener(this);\n    }\n\n    @Override\n    protected void onStop() {\n        super.onStop();\n        mFetchDataUseCase.unregisterListener(this);\n    }\n\n    private void fetchData() {\n        showProgressIndicationAndHideOthers();\n        mFetchDataUseCase.fetchData();\n    }\n\n    @Override\n    public void onDataFetched(String data) {\n        hideProgressIndication();\n        showData(data);\n    }\n\n    private void showData(String data) {\n        mTxtData.setText(data);\n        mTxtData.setVisibility(View.VISIBLE);\n        mBtnFetchData.setVisibility(View.VISIBLE);\n    }\n\n    @Override\n    public void onDataFetchFailed() {\n        hideProgressIndication();\n        showError();\n    }\n\n    private void showError() {\n        mTxtError.setVisibility(View.VISIBLE);\n        mBtnFetchData.setVisibility(View.VISIBLE);\n    }\n\n    private void showProgressIndicationAndHideOthers() {\n        mBtnFetchData.setVisibility(View.GONE);\n        mTxtData.setVisibility(View.GONE);\n        mTxtError.setVisibility(View.GONE);\n        mProgressWorking.setVisibility(View.VISIBLE);\n    }\n\n    private void hideProgressIndication() {\n        mProgressWorking.setVisibility(View.GONE);\n    }\n}\n"
  },
  {
    "path": "sample/src/main/java/com/techyourchance/threadposters/SampleApplication.java",
    "content": "package com.techyourchance.threadposters;\n\nimport android.app.Application;\n\nimport com.techyourchance.threadposter.BackgroundThreadPoster;\nimport com.techyourchance.threadposter.UiThreadPoster;\n\npublic class SampleApplication extends Application {\n\n    /*\n      IMPORTANT:\n      Both BackgroundThreadPoster and UiThreadPoster should be global objects (single instance).\n     */\n    private final BackgroundThreadPoster mBackgroundThreadPoster = new BackgroundThreadPoster();\n    private final UiThreadPoster mUiThreadPoster = new UiThreadPoster();\n\n    private final FakeDataFetcher mFakeDataFetcher = new FakeDataFetcher();\n    private final FetchDataUseCase mFetchDataUseCase =\n            new FetchDataUseCase(mFakeDataFetcher, mBackgroundThreadPoster, mUiThreadPoster);\n\n    public FetchDataUseCase getFetchDataUseCase() {\n        return mFetchDataUseCase;\n    }\n}\n"
  },
  {
    "path": "sample/src/main/res/layout/activity_sample.xml",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout\n    xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    xmlns:tools=\"http://schemas.android.com/tools\"\n    android:layout_width=\"match_parent\"\n    android:layout_height=\"match_parent\"\n    android:padding=\"20dp\">\n\n    <Button\n        android:id=\"@+id/btn_fetch_data\"\n        android:layout_width=\"wrap_content\"\n        android:layout_height=\"wrap_content\"\n        android:layout_centerInParent=\"true\"\n        android:text=\"Fetch data!\"/>\n\n    <ProgressBar\n        android:id=\"@+id/progress_working\"\n        android:layout_width=\"wrap_content\"\n        android:layout_height=\"wrap_content\"\n        android:layout_centerInParent=\"true\"\n        android:visibility=\"gone\"/>\n\n    <TextView\n        android:id=\"@+id/txt_data\"\n        android:layout_width=\"wrap_content\"\n        android:layout_height=\"wrap_content\"\n        android:layout_centerHorizontal=\"true\"\n        android:layout_below=\"@id/btn_fetch_data\"\n        android:layout_marginTop=\"10dp\"\n        android:visibility=\"gone\"/>\n\n    <TextView\n        android:id=\"@+id/txt_error\"\n        android:layout_width=\"wrap_content\"\n        android:layout_height=\"wrap_content\"\n        android:layout_centerHorizontal=\"true\"\n        android:layout_below=\"@id/btn_fetch_data\"\n        android:layout_marginTop=\"10dp\"\n        android:text=\"error\"\n        android:textColor=\"@android:color/holo_red_dark\"\n        android:visibility=\"gone\"/>\n\n</RelativeLayout>\n"
  },
  {
    "path": "sample/src/main/res/values/colors.xml",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<resources>\n    <color name=\"colorPrimary\">#3F51B5</color>\n    <color name=\"colorPrimaryDark\">#303F9F</color>\n    <color name=\"colorAccent\">#FF4081</color>\n</resources>\n"
  },
  {
    "path": "sample/src/main/res/values/strings.xml",
    "content": "<resources>\n    <string name=\"app_name\">ThreadPosters</string>\n</resources>\n"
  },
  {
    "path": "sample/src/main/res/values/styles.xml",
    "content": "<resources>\n\n    <!-- Base application theme. -->\n    <style name=\"AppTheme\" parent=\"Theme.AppCompat.Light.DarkActionBar\">\n        <!-- Customize your theme here. -->\n        <item name=\"colorPrimary\">@color/colorPrimary</item>\n        <item name=\"colorPrimaryDark\">@color/colorPrimaryDark</item>\n        <item name=\"colorAccent\">@color/colorAccent</item>\n    </style>\n\n</resources>\n"
  },
  {
    "path": "sample/src/test/java/com/techyourchance/threadposters/FetchDataUseCaseTest.java",
    "content": "package com.techyourchance.threadposters;\r\n\r\nimport com.techyourchance.threadposter.testdoubles.ThreadPostersTestDouble;\r\n\r\nimport org.junit.Before;\r\nimport org.junit.Test;\r\n\r\nimport static org.hamcrest.MatcherAssert.assertThat;\r\nimport static org.hamcrest.core.Is.is;\r\nimport static org.mockito.Mockito.doThrow;\r\nimport static org.mockito.Mockito.mock;\r\nimport static org.mockito.Mockito.verify;\r\nimport static org.mockito.Mockito.when;\r\n\r\npublic class FetchDataUseCaseTest {\r\n\r\n    private static final String TEST_DATA = \"testData\";\r\n\r\n    private ThreadPostersTestDouble mThreadPostersTestDouble;\r\n\r\n    private FakeDataFetcher mFakeDataFetcherMock;\r\n    private FetchDataUseCase.Listener mListener1;\r\n    private FetchDataUseCase.Listener mListener2;\r\n\r\n    private FetchDataUseCase SUT;\r\n\r\n    @Before\r\n    public void setup() throws Exception {\r\n        mFakeDataFetcherMock = mock(FakeDataFetcher.class);\r\n        mThreadPostersTestDouble = new ThreadPostersTestDouble();\r\n\r\n        SUT = new FetchDataUseCase(\r\n                mFakeDataFetcherMock,\r\n                mThreadPostersTestDouble.getBackgroundTestDouble(),\r\n                mThreadPostersTestDouble.getUiTestDouble());\r\n\r\n        mListener1 = mock(FetchDataUseCase.Listener.class);\r\n        mListener2 = mock(FetchDataUseCase.Listener.class);\r\n    }\r\n\r\n    @Test\r\n    public void fetchData_successNoListeners_completesWithoutErrors() throws Exception {\r\n        // Arrange\r\n        success();\r\n        // Act\r\n        SUT.fetchData();\r\n        // Assert\r\n\r\n        // needs to be called before assertions in order for all threads to complete and\r\n        // all side effects to be present\r\n        mThreadPostersTestDouble.join();\r\n\r\n        assertThat(true, is(true));\r\n    }\r\n\r\n    @Test\r\n    public void fetchData_successMultipleListeners_notifiedWithCorrectData() throws Exception {\r\n        // Arrange\r\n        success();\r\n        // Act\r\n        SUT.registerListener(mListener1);\r\n        SUT.registerListener(mListener2);\r\n        SUT.fetchData();\r\n        // Assert\r\n\r\n        // needs to be called before assertions in order for all threads to complete and\r\n        // all side effects to be present\r\n        mThreadPostersTestDouble.join();\r\n\r\n        verify(mListener1).onDataFetched(TEST_DATA);\r\n        verify(mListener2).onDataFetched(TEST_DATA);\r\n    }\r\n\r\n    @Test\r\n    public void fetchData_failureMultipleListeners_notifiedOfFailure() throws Exception {\r\n        // Arrange\r\n        failure();\r\n        // Act\r\n        SUT.registerListener(mListener1);\r\n        SUT.registerListener(mListener2);\r\n        SUT.fetchData();\r\n        // Assert\r\n\r\n        // needs to be called before assertions in order for all threads to complete and\r\n        // all side effects to be present\r\n        mThreadPostersTestDouble.join();\r\n\r\n        verify(mListener1).onDataFetchFailed();\r\n        verify(mListener2).onDataFetchFailed();\r\n    }\r\n\r\n    // ---------------------------------------------------------------------------------------------\r\n    // Helper methods\r\n    // ---------------------------------------------------------------------------------------------\r\n\r\n    private void success() throws FakeDataFetcher.DataFetchException {\r\n        when(mFakeDataFetcherMock.getData()).thenReturn(TEST_DATA);\r\n    }\r\n\r\n    private void failure() throws FakeDataFetcher.DataFetchException {\r\n        doThrow(new FakeDataFetcher.DataFetchException()).when(mFakeDataFetcherMock).getData();\r\n    }\r\n}"
  },
  {
    "path": "settings.gradle",
    "content": "include ':sample', ':threadposter'\n"
  },
  {
    "path": "threadposter/.gitignore",
    "content": "/build\r\n"
  },
  {
    "path": "threadposter/build.gradle",
    "content": "apply plugin: 'com.android.library'\r\n\r\next {\r\n    PUBLISH_GROUP_ID = 'com.techyourchance'\r\n    PUBLISH_VERSION = '1.0.1'\r\n    PUBLISH_ARTIFACT_ID = 'threadposter'\r\n}\r\n\r\napply from: \"${rootDir}/threadposter/publish-maven.gradle\"\r\n\r\nandroid {\r\n    compileSdkVersion rootProject.ext.compileSdkVersion\r\n    buildToolsVersion \"30.0.2\"\r\n\r\n    defaultConfig {\r\n        minSdkVersion 16\r\n        targetSdkVersion 30\r\n        versionCode 4\r\n        versionName PUBLISH_VERSION\r\n    }\r\n    buildTypes {\r\n        release {\r\n            minifyEnabled false\r\n            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'\r\n        }\r\n    }\r\n}\r\n\r\ndependencies {\r\n    implementation fileTree(dir: 'libs', include: ['*.jar'])\r\n    testImplementation \"junit:junit:${rootProject.ext.junitVersion}\"\r\n    testImplementation \"org.mockito:mockito-core:${rootProject.ext.mockitoVersion}\"\r\n}\r\n\r\n"
  },
  {
    "path": "threadposter/proguard-rules.pro",
    "content": "# Add project specific ProGuard rules here.\r\n# By default, the flags in this file are appended to flags specified\r\n# in C:\\android\\sdk/tools/proguard/proguard-android.txt\r\n# You can edit the include path and order by changing the proguardFiles\r\n# directive in build.gradle.\r\n#\r\n# For more details, see\r\n#   http://developer.android.com/guide/developing/tools/proguard.html\r\n\r\n# Add any project specific keep options here:\r\n\r\n# If your project uses WebView with JS, uncomment the following\r\n# and specify the fully qualified class name to the JavaScript interface\r\n# class:\r\n#-keepclassmembers class fqcn.of.javascript.interface.for.webview {\r\n#   public *;\r\n#}\r\n\r\n# Uncomment this to preserve the line number information for\r\n# debugging stack traces.\r\n#-keepattributes SourceFile,LineNumberTable\r\n\r\n# If you keep the line number information, uncomment this to\r\n# hide the original source file name.\r\n#-renamesourcefileattribute SourceFile\r\n"
  },
  {
    "path": "threadposter/publish-maven.gradle",
    "content": "apply plugin: 'maven-publish'\napply plugin: 'signing'\n\ntask androidSourcesJar(type: Jar) {\n    archiveClassifier.set('sources')\n    if (project.plugins.findPlugin(\"com.android.library\")) {\n        from android.sourceSets.main.java.srcDirs\n    } else {\n        from sourceSets.main.java.srcDirs\n    }\n}\n\nartifacts {\n    archives androidSourcesJar\n}\n\ngroup = PUBLISH_GROUP_ID\nversion = PUBLISH_VERSION\n\next[\"signing.keyId\"] = ''\next[\"signing.password\"] = ''\next[\"signing.secretKeyRingFile\"] = ''\next[\"ossrhUsername\"] = ''\next[\"ossrhPassword\"] = ''\next[\"sonatypeStagingProfileId\"] = ''\n\nFile secretPropsFile = project.rootProject.file('sonatype.properties')\nif (secretPropsFile.exists()) {\n    Properties p = new Properties()\n    p.load(new FileInputStream(secretPropsFile))\n    p.each { name, value ->\n        ext[name] = value\n    }\n} else {\n    ext[\"signing.keyId\"] = System.getenv('SIGNING_KEY_ID')\n    ext[\"signing.password\"] = System.getenv('SIGNING_PASSWORD')\n    ext[\"signing.secretKeyRingFile\"] = System.getenv('SIGNING_SECRET_KEY_RING_FILE')\n    ext[\"ossrhUsername\"] = System.getenv('OSSRH_USERNAME')\n    ext[\"ossrhPassword\"] = System.getenv('OSSRH_PASSWORD')\n    ext[\"sonatypeStagingProfileId\"] = System.getenv('SONATYPE_STAGING_PROFILE_ID')\n}\n\npublishing {\n    publications {\n        release(MavenPublication) {\n            groupId PUBLISH_GROUP_ID\n            artifactId PUBLISH_ARTIFACT_ID\n            version PUBLISH_VERSION\n            if (project.plugins.findPlugin(\"com.android.library\")) {\n                artifact(\"$buildDir/outputs/aar/${project.getName()}-release.aar\")\n            } else {\n                artifact(\"$buildDir/libs/${project.getName()}-${version}.jar\")\n            }\n\n            artifact androidSourcesJar\n\n            pom {\n                name = PUBLISH_ARTIFACT_ID\n                description = 'Lightweight library for unit testable and expressive multi-threading in Android.'\n                url = 'https://github.com/techyourchance/thread-poster'\n                licenses {\n                    license {\n                        name = 'The Apache Software License, Version 2.0'\n                        url = 'http://www.apache.org/licenses/LICENSE-2.0.txt'\n                    }\n                }\n                developers {\n                    developer {\n                        id = 'techyourchance'\n                        name = 'Vasiliy Zukanov'\n                        email = 'vasiliy@techyourchance.com'\n                    }\n                }\n                scm {\n                    connection = 'scm:git:github.com/techyourchance/thread-poster.git'\n                    developerConnection = 'scm:git:github.com/techyourchance/thread-poster.git'\n                    url = 'https://github.com/techyourchance/thread-poster'\n                }\n            }\n        }\n    }\n    repositories {\n        maven {\n            name = \"sonatype\"\n\n            def releasesRepoUrl = \"https://s01.oss.sonatype.org/service/local/staging/deploy/maven2/\"\n            def snapshotsRepoUrl = \"https://s01.oss.sonatype.org/content/repositories/snapshots/\"\n            url = version.endsWith('SNAPSHOT') ? snapshotsRepoUrl : releasesRepoUrl\n\n            credentials {\n                username ossrhUsername\n                password ossrhPassword\n            }\n        }\n    }\n}\n\n//nexusStaging {\n//    packageGroup = PUBLISH_GROUP_ID\n//    stagingProfileId = sonatypeStagingProfileId\n//    username = ossrhUsername\n//    password = ossrhPassword\n//}\n\nsigning {\n    sign publishing.publications\n}"
  },
  {
    "path": "threadposter/src/main/AndroidManifest.xml",
    "content": "<manifest package=\"com.techyourchance.threadposter\"\r\n          xmlns:android=\"http://schemas.android.com/apk/res/android\">\r\n\r\n    <application\r\n        android:label=\"@string/app_name\"/>\r\n\r\n</manifest>\r\n"
  },
  {
    "path": "threadposter/src/main/java/com/techyourchance/threadposter/BackgroundThreadPoster.java",
    "content": "package com.techyourchance.threadposter;\n\nimport java.util.concurrent.SynchronousQueue;\nimport java.util.concurrent.ThreadFactory;\nimport java.util.concurrent.ThreadPoolExecutor;\nimport java.util.concurrent.TimeUnit;\n\npublic class BackgroundThreadPoster {\n\n    private static final int CORE_THREADS = 3;\n    private static final long KEEP_ALIVE_SECONDS = 60L;\n\n    private final ThreadPoolExecutor mThreadPoolExecutor;\n\n    public BackgroundThreadPoster() {\n        mThreadPoolExecutor = newThreadPoolExecutor();\n    }\n\n    /**\n     * Execute {@link Runnable} on a random background thread.\n     * @param runnable {@link Runnable} instance containing the code that should be executed\n     */\n    public void post(Runnable runnable) {\n        mThreadPoolExecutor.execute(runnable);\n    }\n\n    /**\n     * Get the underlying {@link ThreadPoolExecutor}.\n     * In general, this method shouldn't be used and is provided only for the purpose of\n     * integration with existing libraries and frameworks.\n     */\n    protected final ThreadPoolExecutor getThreadPoolExecutor() {\n        return mThreadPoolExecutor;\n    }\n\n    /**\n     * Get the underlying {@link ThreadFactory}.\n     * In general, this method shouldn't be used and is provided only for the purpose of\n     * integration with existing libraries and frameworks.\n     */\n    protected final ThreadFactory getThreadFactory() {\n        return getThreadPoolExecutor().getThreadFactory();\n    }\n\n    /**\n     * This factory method constructs the instance of {@link ThreadPoolExecutor} that is used by\n     * {@link BackgroundThreadPoster} internally.<br>\n     * The returned executor has sensible defaults for Android applications.<br>\n     * Override only if you're ABSOLUTELY sure that you know what you're doing.\n     */\n    protected ThreadPoolExecutor newThreadPoolExecutor() {\n        return new ThreadPoolExecutor(\n                CORE_THREADS,\n                Integer.MAX_VALUE,\n                KEEP_ALIVE_SECONDS,\n                TimeUnit.SECONDS,\n                new SynchronousQueue<Runnable>()\n        );\n    }\n\n}\n"
  },
  {
    "path": "threadposter/src/main/java/com/techyourchance/threadposter/UiThreadPoster.java",
    "content": "package com.techyourchance.threadposter;\r\n\r\nimport android.os.Handler;\r\nimport android.os.Looper;\r\n\r\npublic class UiThreadPoster {\r\n\r\n    private final Handler mUiHandler;\r\n\r\n    public UiThreadPoster() {\r\n        mUiHandler = getMainHandler();\r\n    }\r\n\r\n    /**\r\n     * Execute {@link Runnable} on application's UI thread.\r\n     * @param runnable {@link Runnable} instance containing the code that should be executed\r\n     */\r\n    public void post(Runnable runnable) {\r\n        mUiHandler.post(runnable);\r\n    }\r\n\r\n    /**\r\n     * The only reason this method exists is that UiThreadPosterTestDouble can override\r\n     * it.\r\n     */\r\n    protected Handler getMainHandler() {\r\n        return new Handler(Looper.getMainLooper());\r\n    }\r\n\r\n}\r\n"
  },
  {
    "path": "threadposter/src/main/java/com/techyourchance/threadposter/testdoubles/BackgroundThreadPosterTestDouble.java",
    "content": "package com.techyourchance.threadposter.testdoubles;\n\n\nimport com.techyourchance.threadposter.BackgroundThreadPoster;\n\nimport java.util.Queue;\nimport java.util.concurrent.ConcurrentLinkedQueue;\nimport java.util.concurrent.SynchronousQueue;\nimport java.util.concurrent.ThreadFactory;\nimport java.util.concurrent.ThreadPoolExecutor;\nimport java.util.concurrent.TimeUnit;\n\n/**\n * Test double of {@link BackgroundThreadPoster} that can be used in tests in order to establish\n * a happens-before relationship between any {@link Runnable} sent to execution and subsequent\n * test assertions.\n */\n/* pp */  class BackgroundThreadPosterTestDouble extends BackgroundThreadPoster {\n\n    private final Object MONITOR = new Object();\n\n    private final Queue<Runnable> mRunnables = new ConcurrentLinkedQueue<>();\n\n    private int mNonCompletedRunnables = 0;\n\n    @Override\n    public void post(Runnable runnable) {\n        synchronized (MONITOR) {\n            mRunnables.add(runnable);\n            mNonCompletedRunnables++;\n            MONITOR.notifyAll();\n        }\n    }\n\n    @Override\n    protected ThreadPoolExecutor newThreadPoolExecutor() {\n        return new ThreadPoolExecutor(\n                0,\n                Integer.MAX_VALUE,\n                0L,\n                TimeUnit.SECONDS,\n                new SynchronousQueue<Runnable>(),\n                new ThreadFactory() {\n                    @Override\n                    public Thread newThread(final Runnable r) {\n                        return new Thread(new Runnable() {\n                            @Override\n                            public void run() {\n                                r.run();\n                                synchronized (MONITOR) {\n                                    mNonCompletedRunnables--;\n                                    MONITOR.notifyAll();\n                                }\n                            }\n                        });\n                    }\n                }\n        );\n    }\n\n    /**\n     * Execute all {@link Runnable}s posted to this \"test double\". The caller will block until the operation completes<br>\n     * Call to this method allows to establish a happens-before relationship between the previously\n     * posted {@link Runnable}s and subsequent code.\n     */\n    /* pp */ void join() {\n        synchronized (MONITOR) {\n            Runnable runnable;\n            while (mNonCompletedRunnables > 0) {\n                while ((runnable = mRunnables.poll()) != null) {\n                    super.post(runnable);\n                }\n                try {\n                    MONITOR.wait();\n                } catch (InterruptedException e) {\n                    throw new RuntimeException(\"interrupted\");\n                }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "threadposter/src/main/java/com/techyourchance/threadposter/testdoubles/ThreadPostersTestDouble.java",
    "content": "package com.techyourchance.threadposter.testdoubles;\r\n\r\nimport com.techyourchance.threadposter.BackgroundThreadPoster;\r\nimport com.techyourchance.threadposter.UiThreadPoster;\r\n\r\n/**\r\n * This class should be used in unit tests to obtain test doubles of {@link UiThreadPoster} and\r\n * {@link BackgroundThreadPoster}.<br>\r\n * The reason for the existence of this class is that it handles special ordering requirements\r\n * between thread posters when {@link ThreadPostersTestDouble#join()} is called.\r\n */\r\npublic class ThreadPostersTestDouble {\r\n\r\n    private final BackgroundThreadPosterTestDouble mBackgroundThreadPosterTestDouble =\r\n            new BackgroundThreadPosterTestDouble();\r\n    private final UiThreadPosterTestDouble mUiThreadPosterTestDouble =\r\n            new UiThreadPosterTestDouble();\r\n\r\n    public void join() {\r\n        // The ordering here is important - it's assumed that if both bg and ui thread posters\r\n        // involved, then the flow is from bg thread poster to ui thread poster.\r\n        // If the clients will try to use a reverse order (invoke bg thread poster from ui thread poster),\r\n        // then the tests will simply hang.\r\n        // Not optimal, but, at least, the clients will know that something is wrong right away.\r\n        mBackgroundThreadPosterTestDouble.join();\r\n        mUiThreadPosterTestDouble.join();\r\n    }\r\n\r\n    public BackgroundThreadPoster getBackgroundTestDouble() {\r\n        return mBackgroundThreadPosterTestDouble;\r\n    }\r\n\r\n    public UiThreadPoster getUiTestDouble() {\r\n        return mUiThreadPosterTestDouble;\r\n    }\r\n}\r\n"
  },
  {
    "path": "threadposter/src/main/java/com/techyourchance/threadposter/testdoubles/UiThreadPosterTestDouble.java",
    "content": "package com.techyourchance.threadposter.testdoubles;\r\n\r\nimport android.os.Handler;\r\n\r\nimport com.techyourchance.threadposter.UiThreadPoster;\r\n\r\nimport java.util.Queue;\r\nimport java.util.concurrent.ConcurrentLinkedQueue;\r\n\r\n/**\r\n * Test double of {@link UiThreadPoster} that can be used in tests in order to establish\r\n * a happens-before relationship between any {@link Runnable} sent to execution and subsequent\r\n * test assertions.\r\n * Instead of using Android's UI (aka main) thread, this implementation runs all {@link Runnable}s\r\n * on a single background thread in order, thus simulating serial execution on UI thread.\r\n */\r\n/* pp */  class UiThreadPosterTestDouble extends UiThreadPoster {\r\n\r\n    private final Queue<Runnable> mRunnables = new ConcurrentLinkedQueue<>();\r\n\r\n    @Override\r\n    protected Handler getMainHandler() {\r\n        // need to override this method in order to prevent \"stub\" RuntimeException during unit\r\n        // testing; since this class does not use Handler at all, we can simply return null\r\n        return null;\r\n    }\r\n\r\n    @Override\r\n    public void post(final Runnable runnable) {\r\n        mRunnables.add(runnable);\r\n    }\r\n\r\n    /**\r\n     * Execute all {@link Runnable}s posted to this \"test double\". The caller will block until the operation completes<br>\r\n     * Call to this method allows to establish a happens-before relationship between the previously\r\n     * posted {@link Runnable}s and subsequent code.\r\n     */\r\n    /* pp */ void join() {\r\n        final Thread fakeUiThread = new Thread() {\r\n            @Override\r\n            public void run() {\r\n                Runnable runnable;\r\n                while ((runnable = mRunnables.poll()) != null) {\r\n                    runnable.run();\r\n                }\r\n            }\r\n        };\r\n\r\n        fakeUiThread.start();\r\n\r\n        try {\r\n            fakeUiThread.join();\r\n        } catch (InterruptedException e) {\r\n            throw new RuntimeException(\"interrupted\");\r\n        }\r\n    }\r\n\r\n\r\n}\r\n"
  },
  {
    "path": "threadposter/src/main/res/values/strings.xml",
    "content": "<resources>\r\n    <string name=\"app_name\">threadposter</string>\r\n</resources>\r\n"
  },
  {
    "path": "threadposter/src/test/java/com/techyourchance/threadposter/BackgroundThreadPosterTest.java",
    "content": "package com.techyourchance.threadposter;\r\n\r\n\r\nimport org.junit.Before;\r\nimport org.junit.ClassRule;\r\nimport org.junit.Test;\r\nimport org.junit.rules.Timeout;\r\n\r\nimport java.util.concurrent.Semaphore;\r\n\r\npublic class BackgroundThreadPosterTest {\r\n\r\n    private static final int TEST_TIMEOUT_MS = 1000;\r\n\r\n    @ClassRule\r\n    public final static Timeout TIMEOUT = Timeout.millis(TEST_TIMEOUT_MS);\r\n\r\n    private BackgroundThreadPoster SUT;\r\n\r\n    @Before\r\n    public void setup() throws Exception {\r\n        SUT = new BackgroundThreadPoster();\r\n    }\r\n\r\n    @Test\r\n    public void execute_singleRunnable_executionSuccessful() throws Exception {\r\n        // Arrange\r\n        final Semaphore semaphore = new Semaphore(0);\r\n        Runnable runnable = new Runnable() {\r\n            @Override\r\n            public void run() {\r\n                semaphore.release();\r\n            }\r\n        };\r\n        // Act\r\n        SUT.post(runnable);\r\n        // Assert\r\n        semaphore.acquireUninterruptibly();\r\n    }\r\n\r\n    @Test\r\n    public void execute_multipleRunnablesIndependent_executionSuccessful() throws Exception {\r\n        // Arrange\r\n        final Semaphore semaphore = new Semaphore(-1);\r\n        Runnable runnable1 = new Runnable() {\r\n            @Override\r\n            public void run() {\r\n                semaphore.release();\r\n            }\r\n        };\r\n        Runnable runnable2 = new Runnable() {\r\n            @Override\r\n            public void run() {\r\n                semaphore.release();\r\n            }\r\n        };\r\n        // Act\r\n        SUT.post(runnable1);\r\n        SUT.post(runnable2);\r\n        // Assert\r\n        semaphore.acquireUninterruptibly();\r\n    }\r\n\r\n    @Test\r\n    public void execute_multipleRunnablesInterdependent_executionSuccessful() throws Exception {\r\n        // Arrange\r\n        final Semaphore semaphore1 = new Semaphore(0);\r\n        final Semaphore semaphore2 = new Semaphore(0);\r\n        Runnable runnable1 = new Runnable() {\r\n            @Override\r\n            public void run() {\r\n                semaphore1.acquireUninterruptibly();\r\n                semaphore2.release();\r\n            }\r\n        };\r\n        Runnable runnable2 = new Runnable() {\r\n            @Override\r\n            public void run() {\r\n                semaphore1.release();\r\n            }\r\n        };\r\n        // Act\r\n        SUT.post(runnable1);\r\n        SUT.post(runnable2);\r\n        // Assert\r\n        semaphore2.acquireUninterruptibly();\r\n    }\r\n}"
  },
  {
    "path": "threadposter/src/test/java/com/techyourchance/threadposter/UiThreadPosterTest.java",
    "content": "package com.techyourchance.threadposter;\r\n\r\nimport android.os.Handler;\r\n\r\nimport org.junit.Before;\r\nimport org.junit.Test;\r\nimport org.mockito.ArgumentCaptor;\r\n\r\nimport static org.hamcrest.MatcherAssert.assertThat;\r\nimport static org.hamcrest.core.Is.is;\r\nimport static org.mockito.Mockito.mock;\r\nimport static org.mockito.Mockito.times;\r\nimport static org.mockito.Mockito.verify;\r\n\r\npublic class UiThreadPosterTest {\r\n\r\n    private Handler mUiHandlerMock;\r\n    private UiThreadPoster SUT;\r\n\r\n    @Before\r\n    public void setup() throws Exception {\r\n        mUiHandlerMock = mock(Handler.class);\r\n        SUT = new UiThreadPoster() {\r\n            @Override\r\n            protected Handler getMainHandler() {\r\n                return mUiHandlerMock;\r\n            }\r\n        };\r\n    }\r\n\r\n\r\n    @Test\r\n    public void execute_delegatesToUiHandler() throws Exception {\r\n        // Arrange\r\n        Runnable runnable = new Runnable() {\r\n            @Override\r\n            public void run() {\r\n                // no-op\r\n            }\r\n        };\r\n        ArgumentCaptor<Runnable> ac = ArgumentCaptor.forClass(Runnable.class);\r\n        // Act\r\n        SUT.post(runnable);\r\n        // Assert\r\n        verify(mUiHandlerMock, times(1)).post(ac.capture());\r\n        assertThat(ac.getValue(), is(runnable));\r\n    }\r\n}"
  },
  {
    "path": "threadposter/src/test/java/com/techyourchance/threadposter/testdoubles/BackgroundThreadPosterTestDoubleTest.java",
    "content": "package com.techyourchance.threadposter.testdoubles;\r\n\r\n\r\nimport org.junit.Before;\r\nimport org.junit.ClassRule;\r\nimport org.junit.Test;\r\nimport org.junit.rules.Timeout;\r\n\r\nimport java.util.concurrent.Semaphore;\r\nimport java.util.concurrent.atomic.AtomicInteger;\r\n\r\nimport static org.hamcrest.MatcherAssert.assertThat;\r\nimport static org.hamcrest.core.Is.is;\r\n\r\npublic class BackgroundThreadPosterTestDoubleTest {\r\n\r\n    private static final int TEST_DELAY_MS = 10;\r\n\r\n    @ClassRule\r\n    public final static Timeout TIMEOUT = Timeout.seconds(5);\r\n\r\n    private BackgroundThreadPosterTestDouble SUT;\r\n\r\n    @Before\r\n    public void setup() throws Exception {\r\n        SUT = new BackgroundThreadPosterTestDouble();\r\n    }\r\n\r\n    @Test\r\n    public void executeThenJoin_singleRunnable_sideEffectsNotVisibleBeforeJoin() throws Exception {\r\n        // Arrange\r\n        final Counter counter = new Counter();\r\n        Runnable runnable = new Runnable() {\r\n            @Override\r\n            public void run() {\r\n                counter.increment();\r\n            }\r\n        };\r\n        // Act\r\n        SUT.post(runnable);\r\n        // Assert\r\n        Thread.sleep(TEST_DELAY_MS);\r\n        assertThat(counter.getCount(), is(0));\r\n    }\r\n\r\n    @Test\r\n    public void executeThenJoin_singleRunnable_sideEffectsVisibleAfterJoin() throws Exception {\r\n        // Arrange\r\n        final Counter counter = new Counter();\r\n        Runnable runnable = new Runnable() {\r\n            @Override\r\n            public void run() {\r\n                counter.increment();\r\n            }\r\n        };\r\n        // Act\r\n        SUT.post(runnable);\r\n        // Assert\r\n        SUT.join();\r\n        assertThat(counter.getCount(), is(1));\r\n    }\r\n\r\n    @Test\r\n    public void executeThenJoin_multipleRunnablesIndependent_sideEffectsNotVisibleBeforeJoin() throws Exception {\r\n        // Arrange\r\n        final Counter counter = new Counter();\r\n        Runnable runnable1 = new Runnable() {\r\n            @Override\r\n            public void run() {\r\n                counter.increment();\r\n            }\r\n        };\r\n        Runnable runnable2 = new Runnable() {\r\n            @Override\r\n            public void run() {\r\n                counter.increment();\r\n            }\r\n        };\r\n        // Act\r\n        SUT.post(runnable1);\r\n        SUT.post(runnable2);\r\n        // Assert\r\n        Thread.sleep(TEST_DELAY_MS);\r\n        assertThat(counter.getCount(), is(0));\r\n    }\r\n\r\n    @Test\r\n    public void executeThenJoin_multipleRunnablesIndependent_sideEffectsVisibleAfterJoin() throws Exception {\r\n        // Arrange\r\n        final Counter counter = new Counter();\r\n        Runnable runnable1 = new Runnable() {\r\n            @Override\r\n            public void run() {\r\n                counter.increment();\r\n            }\r\n        };\r\n        Runnable runnable2 = new Runnable() {\r\n            @Override\r\n            public void run() {\r\n                counter.increment();\r\n            }\r\n        };\r\n        // Act\r\n        SUT.post(runnable1);\r\n        SUT.post(runnable2);\r\n        // Assert\r\n        SUT.join();\r\n        assertThat(counter.getCount(), is(2));\r\n    }\r\n\r\n    @Test\r\n    public void executeThenJoin_multipleRunnablesInterdependent_sideEffectsNotVisibleBeforeJoin() throws Exception {\r\n        // Arrange\r\n        final Counter counter = new Counter();\r\n        final Semaphore semaphore = new Semaphore(0);\r\n        Runnable runnable1 = new Runnable() {\r\n            @Override\r\n            public void run() {\r\n                semaphore.acquireUninterruptibly();\r\n                counter.increment();\r\n            }\r\n        };\r\n        Runnable runnable2 = new Runnable() {\r\n            @Override\r\n            public void run() {\r\n                semaphore.release();\r\n                counter.increment();\r\n            }\r\n        };\r\n        // Act\r\n        SUT.post(runnable1);\r\n        SUT.post(runnable2);\r\n        // Assert\r\n        Thread.sleep(TEST_DELAY_MS);\r\n        assertThat(counter.getCount(), is(0));\r\n    }\r\n\r\n    @Test\r\n    public void executeThenJoin_multipleRunnablesInterdependent_sideEffectsVisibleAfterJoin() throws Exception {\r\n        // Arrange\r\n        final Counter counter = new Counter();\r\n        final Semaphore semaphore = new Semaphore(0);\r\n        Runnable runnable1 = new Runnable() {\r\n            @Override\r\n            public void run() {\r\n                semaphore.acquireUninterruptibly();\r\n                counter.increment();\r\n            }\r\n        };\r\n        Runnable runnable2 = new Runnable() {\r\n            @Override\r\n            public void run() {\r\n                semaphore.release();\r\n                counter.increment();\r\n            }\r\n        };\r\n        // Act\r\n        SUT.post(runnable1);\r\n        SUT.post(runnable2);\r\n        // Assert\r\n        SUT.join();\r\n        assertThat(counter.getCount(), is(2));\r\n    }\r\n\r\n    @Test\r\n    public void executeThenJoin_multipleNestedRunnablesInterdependent_sideEffectsVisibleAfterJoin() throws Exception {\r\n        // Arrange\r\n        final Counter counter = new Counter();\r\n        final Semaphore semaphore = new Semaphore(0);\r\n        final Runnable runnable1 = new Runnable() {\r\n            @Override\r\n            public void run() {\r\n                semaphore.release();\r\n                counter.increment();\r\n            }\r\n        };\r\n        final Runnable runnable2 = new Runnable() {\r\n            @Override\r\n            public void run() {\r\n                SUT.post(runnable1);\r\n                semaphore.acquireUninterruptibly();\r\n                counter.increment();\r\n            }\r\n        };\r\n        final Runnable runnable3 = new Runnable() {\r\n            @Override\r\n            public void run() {\r\n                SUT.post(runnable2);\r\n                counter.increment();\r\n            }\r\n        };\r\n        // Act\r\n        SUT.post(runnable3);\r\n        // Assert\r\n        SUT.join();\r\n        assertThat(counter.getCount(), is(3));\r\n    }\r\n\r\n    /**\r\n     * This class will be used in order to check side effects in tests\r\n     */\r\n    private class Counter {\r\n\r\n        private AtomicInteger mCount = new AtomicInteger(0);\r\n\r\n        private void increment() {\r\n            mCount.incrementAndGet();\r\n        }\r\n\r\n        private int getCount() {\r\n            return mCount.get();\r\n        }\r\n    }\r\n\r\n}"
  },
  {
    "path": "threadposter/src/test/java/com/techyourchance/threadposter/testdoubles/UiThreadPosterTestDoubleTest.java",
    "content": "package com.techyourchance.threadposter.testdoubles;\r\n\r\nimport org.junit.Before;\r\nimport org.junit.ClassRule;\r\nimport org.junit.Test;\r\nimport org.junit.rules.Timeout;\r\n\r\nimport static org.hamcrest.MatcherAssert.assertThat;\r\nimport static org.hamcrest.core.Is.is;\r\n\r\npublic class UiThreadPosterTestDoubleTest {\r\n\r\n    private static final int TEST_DELAY_MS = 10;\r\n\r\n    @ClassRule\r\n    public final static Timeout TIMEOUT = Timeout.seconds(5);\r\n\r\n    private UiThreadPosterTestDouble SUT;\r\n\r\n    @Before\r\n    public void setup() throws Exception {\r\n        SUT = new UiThreadPosterTestDouble();\r\n    }\r\n\r\n    @Test\r\n    public void executeThenJoin_singleRunnable_sideEffectNotVisibleBeforeJoin() throws Exception {\r\n        // Arrange\r\n        final Appender appender = new Appender();\r\n        Runnable runnable = new Runnable() {\r\n            @Override\r\n            public void run() {\r\n                appender.append(\"a\");\r\n            }\r\n        };\r\n        // Act\r\n        SUT.post(runnable);\r\n        // Assert\r\n        Thread.sleep(TEST_DELAY_MS);\r\n        assertThat(appender.getString(), is(\"\"));\r\n    }\r\n\r\n\r\n    @Test\r\n    public void executeThenJoin_singleRunnable_sideEffectsVisibleAfterJoin() throws Exception {\r\n        // Arrange\r\n        final Appender appender = new Appender();\r\n        Runnable runnable = new Runnable() {\r\n            @Override\r\n            public void run() {\r\n                appender.append(\"a\");\r\n            }\r\n        };\r\n        // Act\r\n        SUT.post(runnable);\r\n        // Assert\r\n        SUT.join();\r\n        assertThat(appender.getString(), is(\"a\"));\r\n    }\r\n\r\n\r\n    @Test\r\n    public void executeThenJoin_multipleRunnables_sideEffectsNotVisibleBeforeJoin() throws Exception {\r\n        // Arrange\r\n        final Appender appender = new Appender();\r\n        Runnable runnable1 = new Runnable() {\r\n            @Override\r\n            public void run() {\r\n                appender.append(\"a\");\r\n            }\r\n        };\r\n        Runnable runnable2 = new Runnable() {\r\n            @Override\r\n            public void run() {\r\n                appender.append(\"b\");\r\n            }\r\n        };\r\n        Runnable runnable3 = new Runnable() {\r\n            @Override\r\n            public void run() {\r\n                appender.append(\"c\");\r\n            }\r\n        };\r\n        // Act\r\n        SUT.post(runnable1);\r\n        SUT.post(runnable2);\r\n        SUT.post(runnable3);\r\n        // Assert\r\n        Thread.sleep(TEST_DELAY_MS);\r\n        assertThat(appender.getString(), is(\"\"));\r\n    }\r\n\r\n    @Test\r\n    public void executeThenJoin_multipleRunnables_sideEffectsVisibleAfterJoinInOrder() throws Exception {\r\n        // Arrange\r\n        final Appender appender = new Appender();\r\n        Runnable runnable1 = new Runnable() {\r\n            @Override\r\n            public void run() {\r\n                appender.append(\"a\");\r\n            }\r\n        };\r\n        Runnable runnable2 = new Runnable() {\r\n            @Override\r\n            public void run() {\r\n                appender.append(\"b\");\r\n            }\r\n        };\r\n        Runnable runnable3 = new Runnable() {\r\n            @Override\r\n            public void run() {\r\n                appender.append(\"c\");\r\n            }\r\n        };\r\n        // Act\r\n        SUT.post(runnable1);\r\n        SUT.post(runnable2);\r\n        SUT.post(runnable3);\r\n        // Assert\r\n        SUT.join();\r\n        assertThat(appender.getString(), is(\"abc\"));\r\n    }\r\n\r\n\r\n    @Test\r\n    public void executeThenJoin_multipleNestedRunnables_sideEffectsVisibleAfterJoinInReversedOrder() throws Exception {\r\n        // Arrange\r\n        final Appender appender = new Appender();\r\n        final Runnable runnable1 = new Runnable() {\r\n            @Override\r\n            public void run() {\r\n                appender.append(\"a\");\r\n            }\r\n        };\r\n        final Runnable runnable2 = new Runnable() {\r\n            @Override\r\n            public void run() {\r\n                SUT.post(runnable1);\r\n                appender.append(\"b\");\r\n            }\r\n        };\r\n        final Runnable runnable3 = new Runnable() {\r\n            @Override\r\n            public void run() {\r\n                SUT.post(runnable2);\r\n                appender.append(\"c\");\r\n            }\r\n        };\r\n        // Act\r\n        SUT.post(runnable3);\r\n        // Assert\r\n        SUT.join();\r\n        assertThat(appender.getString(), is(\"cba\"));\r\n    }\r\n\r\n    /**\r\n     * This class will be used in order to check side effects in tests\r\n     */\r\n    private class Appender {\r\n\r\n        private String mString = \"\";\r\n\r\n        private synchronized void append(String string) {\r\n            mString += string;\r\n        }\r\n\r\n        private synchronized String getString() {\r\n            return mString;\r\n        }\r\n    }\r\n}"
  }
]