<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Bastien Paul on Medium]]></title>
        <description><![CDATA[Stories by Bastien Paul on Medium]]></description>
        <link>https://medium.com/@bastienpaul?source=rss-b3cd84d27c3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*WSPWsxONMwJdDamz98dplg.jpeg</url>
            <title>Stories by Bastien Paul on Medium</title>
            <link>https://medium.com/@bastienpaul?source=rss-b3cd84d27c3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 16:21:38 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@bastienpaul/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[The day we (almost) lost 1000 customers]]></title>
            <link>https://medium.com/qonto-way/the-day-we-almost-lost-1000-customers-24ff2afcc736?source=rss-b3cd84d27c3------2</link>
            <guid isPermaLink="false">https://medium.com/p/24ff2afcc736</guid>
            <category><![CDATA[qonto]]></category>
            <category><![CDATA[ca]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[ssl-certificate]]></category>
            <dc:creator><![CDATA[Bastien Paul]]></dc:creator>
            <pubDate>Thu, 10 Oct 2024 06:54:58 GMT</pubDate>
            <atom:updated>2024-10-10T09:00:35.281Z</atom:updated>
            <content:encoded><![CDATA[<h3>The day we (almost) lost 1,000 customers</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M5bf1oMjn9Z82IqxNv7KbA.png" /></figure><p>It all began with a bug report. The kind of report you see on a Friday afternoon and defer to the next Monday. We overlooked the report that day, and we shouldn’t have. <br>Android 6&amp;7 users couldn’t log in or make a transfer due to an update of the SSL root certificate issued by Let’s Encrypt. We needed to unblock those users. <br>Here, I want to share our experience weathering the storm caused by the flap of this butterfly’s wings.</p><h3>What led to 1,000 customers getting locked out</h3><figure><img alt="Screen users see when they want to log in from the web app" src="https://cdn-images-1.medium.com/max/1024/1*q4kaEKZe7Fbgrs16jtmXrQ.png" /><figcaption>Screen users see when they want to log in from the web app</figcaption></figure><p>As a payment institution, Qonto must comply with regulations such as the Revised Payment Services Directive or PSD2. One of PSD2’s key requirements is that every institution implements Strong Customer Authentication (SCA). SCA is designed to ensure the person initiating a sensitive action, such as a transfer or a card payment, is a legitimate user. It requires the use of at least two out of three independent authentication factors:</p><ol><li><strong>Something the user knows</strong>: This can be a password, PIN, or any other knowledge-based factor.</li><li><strong>Something the user has</strong>: This refers to physical equipment such as a smartphone, token, or card, which the user possesses.</li><li><strong>Something the user is</strong>: This involves biometric authentication, like fingerprints or facial recognition.</li></ol><p>For instance, to validate a payment by card, users must grab their device (something the user has), validate the payment, and put in their password or fingerprint (something they know or are).</p><h3>A tough week</h3><p>We looked at the bug report. It was about a customer not being able to pair her phone to enable SCA. After digging into the case it was clear that not only the first enrollment was impacted, but also all the actions linked to SCA. The service responsible for approving the sensitive actions such as card payments, provided by a partner, wasn’t working for a subset of our users.</p><p>You can imagine the trouble users might face when they can’t access their account:</p><ul><li>They need to complete a transaction before the weekend, but it cannot be processed.</li><li>An online payment their business relies on can’t be approved.</li><li>Their operations come to a halt.</li></ul><p>Since there wasn’t any recent change in our systems that could explain the issue, we resorted to the Socratic method. We asked ourselves open-ended questions and wrote down the answers, drawing a tree of potential causes. In the end, all branches were dead ends.</p><p>Since nothing looked wrong on our side, we contacted our partner about the issue. They pointed us to <a href="https://letsencrypt.org/2023/07/10/cross-sign-expiration.html">an article talking about a change of certificate made by Let’s Encrypt.</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MVCgPK-f93Un91C44yI7Rw.png" /><figcaption>Extract of the article published in Let’s Encrypt web site</figcaption></figure><p>Was this certificate issue preventing all communications between the SDK and the server?</p><p>We checked on Kibana that the impacted users were running on Android 6 &amp; 7.0 devices. We also got the <strong>CertPathValidatorException</strong> event on Crashlytics.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HChhuRxbCIEv6OTwzNAOHQ.png" /><figcaption>The issue on Crashlytics shows that mainly Android 6 and 7 devices are affected.</figcaption></figure><p>Bingo! We found the root cause of the issue.</p><p>Let’s Encrypt changed their root certificate. The new one was incompatible with Android devices below 7.0. Qonto’s SCA servers use certificates signed by Let’s Encrypt. So the impacted Android devices could not trust the server anymore, resulting in a CertPathValidatorException every time a request was made.</p><p>The device pairing could not proceed. Neither could sensitive action requests.</p><h3>Starting the countdown</h3><p>Our first idea was to ask the customer to add the missing certificate manually. This was too much friction; a customer is unlikely to install a certificate file on the secure panel of their Android settings.</p><p>The only acceptable option for mitigating the issue was to roll back the certificate change made by our partner. Collaboration was key to ensuring that all their other clients wouldn’t be affected by this Qonto-specific rollback.</p><p>Once our partner reverted the changes, we started to plan a definitive fix.</p><p>A communication from CloudFlare alerted us to an impending similar issue with our own API. This highlighted the urgency of developing a robust solution.</p><p>We evaluated several options:</p><ul><li><strong>Using another root certificate:</strong> Our SRE team discarded this idea due to its potential impact on our entire system. We needed to implement the fix on the front-end side instead.</li><li><strong>Dropping support for Android 6 and 7:</strong> This was not an option, as it would have been too disruptive for our 1,000 customers who rely on these versions. They need their mobile device to perform sensitive actions.</li><li><strong>Supporting only Android 7:</strong> Initially considered but discarded for the same reason as the previous point. Dropping the support for Android 6 was not an option.</li><li><strong>Supporting Android 6 &amp; 7:</strong> We chose this path because it allowed us to maintain support for a broader range of devices without causing significant disruption.</li></ul><p>For devices running Android 7, we leveraged the <a href="https://developer.android.com/privacy-and-security/security-config">security configuration options introduced with this version</a>. The Android security config allows us to specify trusted certificates explicitly. This configuration also applies to all the libraries we integrate and use in the application. Here’s the <em>network_security_config.xml</em> file we introduced:</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;network-security-config&gt;<br>    &lt;base-config&gt;<br>        &lt;trust-anchors&gt;<br>            &lt;certificates src=&quot;@raw/isrgrootx1&quot;/&gt;<br>            &lt;certificates src=&quot;system&quot;/&gt;<br>        &lt;/trust-anchors&gt;<br>    &lt;/base-config&gt;<br>&lt;/network-security-config&gt;</pre><p>For Android 6 we relied <a href="https://square.github.io/okhttp/features/https/#certificate-pinning-kt-java">on Square’s okhttp-tls library</a> to create a custom sslSocketFactory. This factory gave us the socket connection able to trust our server’s certificate to establish a secure and encrypted connection.</p><pre>fun OkHttpClient.Builder.trustISRGRootX1CertificateForApi23(): OkHttpClient.Builder {<br>    if (android.os.Build.VERSION.SDK_INT == android.os.Build.VERSION_CODES.M) {<br>        // Convert the PEM in plain string format to a Certificate object<br>        val certificate = convertPemToCertificate()<br><br>        // Load certificate in a builder, being appended to the platform ones.<br>        val certificates = HandshakeCertificates.Builder()<br>            .addPlatformTrustedCertificates()<br>            .addTrustedCertificate(<br>                certificate as X509Certificate,<br>            )<br>            .build()<br><br>        sslSocketFactory(certificates.sslSocketFactory(), certificates.trustManager)<br>    }<br><br>    // Return the builder for further configuration.<br>    return this<br>}</pre><h3>How we ensured that our changes solved the problem</h3><p>We needed an environment to test the network configuration. We needed one that would not disrupt several hundred developers already using the app deployed on the staging environment.</p><p>Here our idea was to provision a specificIP address leading to a reverse proxy, targeting the regular endpoints.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5_lA0GyvOVaKHUEXKzA2Bw.png" /><figcaption>QA setup diagram</figcaption></figure><p>The proxy would serve the new root certificate. Our machines and emulators would rely on the /etc/hosts file to override the network configuration and target the specific IP. This way, we have the entire connection route using certificates signed by the new root certificate authority of Let’s Encrypt.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Aebb8XD83NV1x1p8o4Ha6A.png" /><figcaption>Test setup with the code, the emulator and the /etc/hosts tweaks</figcaption></figure><h3>Deploying the fix</h3><p>The particularity of the mobile world is that you have different versions of the app in the field. All of our users aren’t updating their applications at the same time.</p><p>We needed to ensure that nobody had the faulty versions installed on their phone to be able to apply the change of certificate. To do that, we sunsetted the application versions deployed before the fix was shipped to avoid having users blocked by the new network configuration.</p><h3>What we learned</h3><p>This is one of the most interesting cases we’ve had to solve in Qonto’s Android team, not just because of the unexpectedly low-level nature of the root cause, but also thanks to the broad cross-functional collaboration required to solve it:</p><ul><li>Android developers needed to update the application.</li><li>Site reliability engineers had to set up the test environment and revert certificate changes.</li><li>User experience writers were asked to produce communication materials in five languages.</li><li>Customer relationship managers had to launch communication campaigns in four markets.</li><li>Customer success managers needed to handle the cases raised by our clients.</li><li>Our partner’s team was also involved, handling issues on their side.</li></ul><p>Deferring the first investigation from Friday to the next Monday put our customers’ business in a tough situation during the weekend. We will never forget that a simple bug report can hide a high-stakes situation which needs to be addressed quickly.</p><h3>About Qonto</h3><p>Qonto makes day-to-day banking easier for SMEs and freelancers thanks to an online business account that’s combined with invoicing, bookkeeping and spend management tools.</p><p>Thanks to its innovative product, highly reactive 24/7 customer support, and clear pricing, Qonto has become the leader in its market with more than 500,000 customers.</p><p>Created in 2016 by Alexandre Prot and Steve Anavi, Qonto now operates in 8 European markets (France, Germany, Italy, Spain, Austria, Belgium, the Netherlands and Portugal), and employs more than 1,600 people.</p><p>Since its creation, Qonto has raised €622 million from well-established investors.</p><p>Interested in joining a challenging and game-changing company? Consult our <a href="https://qonto.com/en/careers">job offers</a>!</p><p>Illustration by Eloïse Rulquin</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=24ff2afcc736" width="1" height="1" alt=""><hr><p><a href="https://medium.com/qonto-way/the-day-we-almost-lost-1000-customers-24ff2afcc736">The day we (almost) lost 1000 customers</a> was originally published in <a href="https://medium.com/qonto-way">The Qonto Way</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The importance of making one single commit per dependency update.]]></title>
            <link>https://medium.com/@bastienpaul/the-importance-of-making-one-single-commit-per-dependency-update-e050bb1c5e0e?source=rss-b3cd84d27c3------2</link>
            <guid isPermaLink="false">https://medium.com/p/e050bb1c5e0e</guid>
            <category><![CDATA[dependency-management]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[code]]></category>
            <category><![CDATA[good-practices]]></category>
            <category><![CDATA[git]]></category>
            <dc:creator><![CDATA[Bastien Paul]]></dc:creator>
            <pubDate>Thu, 18 May 2023 12:54:37 GMT</pubDate>
            <atom:updated>2023-05-18T12:54:37.171Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OYXfpT5H_rRqu8tn" /><figcaption>Photo by <a href="https://unsplash.com/@simonfromengland?utm_source=medium&amp;utm_medium=referral">Simon Wilkes</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>As software developers, we often find ourselves working with numerous libraries, frameworks, and dependencies to build robust and efficient applications. However, staying up-to-date with these dependencies can be a challenging task. One common practice that is often overlooked is making a single commit for each dependency update. In this article, we will delve into the significance of this approach and explore why it is essential for the stability, maintainability, and overall health of our projects.</p><p>Dependency updates can sometimes introduce unexpected bugs or conflicts, leading to regressions in our code.</p><p>By isolating each update in a separate commit, we create a clear history that allows us to track changes and identify potential issues that might arise from a specific update. This practice makes the application easier to debug in case of regression. When we make a single commit for each update, it becomes significantly easier to pinpoint the exact change that caused the issue. This granular control enables us to revert to the previous version, minimizing the impact on our project’s stability and saving valuable development time.</p><p>Updating dependencies is not just about ensuring we have the latest features and bug fixes; it also involves validating that our codebase remains functional after the update. By making individual commits for each dependency update, we can conduct incremental testing and verification. This approach allows us to assess the impact of each update and catch any incompatibilities or breaking changes early on. Furthermore, it facilitates easier integration with continuous integration/continuous deployment (CI/CD) pipelines, enabling automated testing and validation at each step.</p><p>Adopting a single-commit approach for dependency updates enhances the documentation and changelog of our projects. Each commit can include a concise and meaningful description of the update, providing valuable insights into the changes made. These commit messages serve as a documentation resource for developers who want to understand the evolution of the project, the reasons behind certain updates, or to review the impact of a specific change in the future.</p><p>The importance of making a single commit for each dependency update cannot be overstated. This practice brings clarity, transparency, and control to our codebase, allowing for better collaboration, easier troubleshooting, and faster rollbacks if necessary. By embracing this approach, we ensure the stability, maintainability, and long-term health of our projects. So, let’s make it a habit to keep our dependencies up to date, one commit at a time, and build robust software that stands the test of time.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e050bb1c5e0e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is the Open/Closed Principle?]]></title>
            <link>https://medium.com/@bastienpaul/what-is-the-open-closed-principle-4a4c0d929f26?source=rss-b3cd84d27c3------2</link>
            <guid isPermaLink="false">https://medium.com/p/4a4c0d929f26</guid>
            <category><![CDATA[open-closed-principle]]></category>
            <category><![CDATA[solid]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[architecture]]></category>
            <dc:creator><![CDATA[Bastien Paul]]></dc:creator>
            <pubDate>Fri, 05 May 2023 11:42:00 GMT</pubDate>
            <atom:updated>2023-05-05T11:44:53.656Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kgvvsfP4kYdOrVWY" /><figcaption>Photo by <a href="https://unsplash.com/@james_open?utm_source=medium&amp;utm_medium=referral">James Kirkup</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The Open/Closed Principle (OCP) is one of the SOLID principles of object-oriented design, as described by Uncle Bob in his book “Clean Architecture”. The principle states that software entities (classes, modules, functions, etc.) should be open for extension but closed for modification.</p><p>In other words, once a software entity has been created and tested, it should not be modified in a way that breaks existing code that depends on it. Instead, new functionality should be added by extending the existing entity, rather than modifying it.</p><p>Also, if adding new functionality to the existing code means modifying it, then this principle is broken.</p><p>Complying with this principle will allow you to add new functionalities without changing the existing code.</p><p>👉 It will be easier to test and easier to maintain.</p><h3>Please give me an example.</h3><p>Let’s say that we are dealing with an Android WebView. The Android framework allows us to set a WebViewClient into a WebView to configure its behavior. One of the abilities of WebViewClient is to tell if a page can be loaded inside a WebView or not by overriding the shouldOverrideUrlLoading method.</p><pre>class CustomWebViewClient: WebViewClient() {<br>    override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest): Boolean {<br>        return super.shouldOverrideUrlLoading(view, request)<br>    }<br>}</pre><p>Now, we want to open the links belonging to our domain inside the WebView, and the other ones inside the browser.</p><pre>class CustomWebViewClient: WebViewClient() {<br>    override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest): Boolean {<br>        return request.url?.host?.endsWith(&quot;.mydomain.com&quot;) == false<br>    }<br>}</pre><h3>Here is the issue!</h3><p>Now, the requirement has changed. We should load all pages belonging to some verified partners inside the WebView as well.</p><p>To do that, we need to change the implementation of shouldOverrideUrlLoading() method.</p><p>👉 We need to modify the implementation. Why?</p><ul><li>❌ The class is not open to extension</li><li>❌ The class is not closed to modification</li></ul><h3>How can we fix this?</h3><p>Here, we can rely on the strategy pattern. We will delegate the decision of overriding the loading to an implementation of the strategy.</p><ul><li>Let’s introduce the strategy:</li></ul><pre>interface OverrideUrlLoadingPolicy {<br>    fun shouldOverrideUrlLoading(uri: Uri): Boolean<br>}</pre><ul><li>A basic implementation of it can be</li></ul><pre>class DefaultOverrideUrlLoadingPolicy: OverrideUrlLoadingPolicy {<br>    override fun shouldOverrideUrlLoading(uri: Uri): Boolean {<br>        return uri?.host?.endsWith(&quot;.mydomain.com&quot;) == false<br>    }<br>}</pre><ul><li>We can use the strategy in the WebViewClient</li></ul><pre>class CustomWebViewClient(<br>    private val overrideUrlLoadingPolicy: OverrideUrlLoadingPolicy<br>): WebViewClient() {<br>        override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest): Boolean {<br>            return overrideUrlLoadingPolicy.shouldOverrideUrlLoading(request.url)<br>        }<br>    }</pre><p>We can create other implementations of OverrideUrlLoadingPolicy with a different logic to comply with other requirements. The other implementation can be provided by a dependency injection framework.</p><p>Let’s go back to our example. Remember that we should load all pages belonging to some verified partners inside the WebView as well?</p><p>Let’s create a new implementation for that:</p><pre>class PartnerOverrideUrlLoadingPolicy: OverrideUrlLoadingPolicy {<br>    override fun shouldOverrideUrlLoading(uri: Uri): Boolean {<br>        return listOf(<br>            &quot;mydomain.com&quot;,<br>            &quot;sub.mydomain.com&quot;,<br>            &quot;partner.com&quot;,<br>        ).contains(uri.host)<br>    }<br>}</pre><p>The DI framework will be configured to inject PartnerOverrideUrlLoadingPolicy into CustomWebViewClient and this is it!</p><p>Have we changed the CustomWebViewClient&#39;s implementation?</p><ul><li>No ✅</li></ul><p>Have we extended the CustomWebViewClient&#39;s logic?</p><ul><li>Yes ✅</li></ul><h3>Conclusion</h3><p>In conclusion, the Open/Closed Principle (OCP) is an important principle of object-oriented design that states that software entities should be open for extension but closed for modification. This can be achieved by using design patterns such as the strategy pattern to delegate the logic to an implementation of the strategy. By complying with this principle, we can add new functionalities without changing the existing code and make it easier to test and maintain.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a4c0d929f26" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Daily goals]]></title>
            <link>https://medium.com/@bastienpaul/daily-goals-5f57ebd8772e?source=rss-b3cd84d27c3------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f57ebd8772e</guid>
            <category><![CDATA[life]]></category>
            <category><![CDATA[personal-growth]]></category>
            <category><![CDATA[personal-development]]></category>
            <category><![CDATA[goals-objectives]]></category>
            <category><![CDATA[task-management]]></category>
            <dc:creator><![CDATA[Bastien Paul]]></dc:creator>
            <pubDate>Fri, 10 Mar 2023 10:22:39 GMT</pubDate>
            <atom:updated>2023-03-10T10:22:39.103Z</atom:updated>
            <content:encoded><![CDATA[<h3>What is a daily goal?</h3><p>A daily goal is a specific task or objective you set to achieve within a single day. These goals could be related to work, personal growth, health, or any other aspect of your life. The key is that they are specific and achievable within 24 hours.</p><h3>Why is it important?</h3><p>Daily goals are essential because they help you stay focused and motivated. By breaking larger goals into smaller, more manageable tasks, you can progress daily and build momentum over time. Additionally, achieving daily goals can give you a sense of accomplishment and boost your confidence.</p><p>This gesture seems to be about performance, but it is actually about raising a signal to the team. One benefit of daily goals is that they indicate that you may need to ask for help. If you consistently struggle to meet your daily goals or fall behind schedule, it may be time to reach out to a coworker, friend, or family member for support.</p><h3>Traps to avoid</h3><p>One trap to avoid when setting daily goals is over-committing. It’s essential to be realistic about what you can achieve in a single day and not set yourself up for failure. Another trap is getting too caught up in the details and losing sight of the bigger picture. Remember to keep your daily goals aligned with your larger goals and values.</p><p>To set your daily goal, use precise verbs, not vague ones. This helps readers understand your message and improves your writing. So, take the time to choose your words and phrases carefully to communicate more precisely and effectively.</p><p>Some examples of fuzzy daily goals include:</p><ul><li>“Work on project X all day” (too vague and not specific enough)</li><li>“Get in shape” (too general and not measurable)</li><li>“Read more books” (not clear enough and not actionable)</li></ul><h3>Key points</h3><p>Key points to remember when setting daily goals include making them specific, measurable, and realistic. It’s also helpful to prioritize your goals and focus on the most critical tasks.</p><p>Another key point to remember when setting daily goals is to make them actionable. This means breaking down larger goals into specific, concrete actions that you can take each day. For example, instead of setting a daily goal to “lose weight,” set a goal to “go for a 30-minute walk after dinner.” By making your goals actionable, you can more easily track your progress and stay motivated.</p><p>Here are some examples of reasonable daily goals:</p><ul><li>“Submit this piece of work for review”</li><li>“Complete this task from my to-do list”</li><li>“Read 30 pages of my book”</li><li>“Connect with one new person on LinkedIn”</li><li>“Spend 30 minutes learning a new skill”</li><li>“Clean my workspace for 15 minutes”</li></ul><p>Finally, track your progress and celebrate your successes along the way.</p><p>It’s also important to be flexible with your daily goals. Life is unpredictable, and sometimes you may need to adjust your goals based on unexpected events or changes in priorities. Don’t be too hard on yourself if you don’t achieve all of your daily goals every day. Remember that progress, not perfection, is the goal.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f57ebd8772e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Activities backstack issue with ActivityScenario]]></title>
            <link>https://medium.com/@bastienpaul/activities-backstack-issue-with-activityscenario-f62ac27563e5?source=rss-b3cd84d27c3------2</link>
            <guid isPermaLink="false">https://medium.com/p/f62ac27563e5</guid>
            <category><![CDATA[androidx]]></category>
            <category><![CDATA[ui]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[test]]></category>
            <dc:creator><![CDATA[Bastien Paul]]></dc:creator>
            <pubDate>Sat, 06 Aug 2022 09:57:15 GMT</pubDate>
            <atom:updated>2022-08-06T09:57:15.397Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mNNuxRHW7qjqsN__5raOgQ.jpeg" /><figcaption>Photo de Egor Kamelev: <a href="https://www.pexels.com/fr-fr/photo/beetle-sur-feuille-verte-1126775/">https://www.pexels.com/fr-fr/photo/beetle-sur-feuille-verte-1126775/</a></figcaption></figure><h3>UI Testing</h3><p>UI testing is an important step of Android software development. We can verify the UI/UX behaviour in addition to implementing end to end testing. AndroidX API brings some facilities to perform such tests. For the scope of this article, we will only deal with activities.</p><h4>We are testing activity with JUnit rules</h4><p>First step to test a UI is to bring the Activity up front. This way, we can interact with buttons, verify view states, and so on. At some point, the API to launch an activity was proposed by <a href="https://developer.android.com/reference/androidx/test/rule/ActivityTestRule.html">ActivityTestRule</a>. But now it is deprecated in favour of <a href="https://developer.android.com/reference/androidx/test/core/app/ActivityScenario.html">ActivityScenario</a>.</p><blockquote><em>ActivityScenario provides APIs to start and drive an Activity’s lifecycle state for testing. It works with arbitrary activities and works consistently across different versions of the Android framework.</em></blockquote><p>We need to be careful with resource cleaning as specified in the <a href="https://developer.android.com/reference/androidx/test/core/app/ActivityScenario.html">documentation</a></p><blockquote><em>ActivityScenario does’t clean up device state automatically and may leave the activity keep running after the test finishes. Call </em><a href="https://developer.android.com/reference/androidx/test/core/app/ActivityScenario#close()"><em>close()</em></a><em> in your test to clean up the state or use try-with-resources statement. This is optional but highly recommended to improve the stability of your tests. Also, consider using </em><a href="https://developer.android.com/reference/androidx/test/ext/junit/rules/ActivityScenarioRule"><em>ActivityScenarioRule</em></a><em>.</em></blockquote><h4>ActivityScenarioRule</h4><p>To automate the cleaning of ActivityScenario we might want to use <a href="https://developer.android.com/reference/androidx/test/ext/junit/rules/ActivityScenarioRule">ActivityScenarioRule</a> API.</p><p>This rule a one limitation though. It will start the activity before the test method. It is OK for many use cases, but if you need to setup your test in a specific way before actually starting the activity, it can be problematic.</p><p>In my own test setup, I need to configure the mockup server before starting the activity because it is communicating with the backend when it starts. To do that, I’ve introduced the LazyActivityScenarioRule</p><h4>LazyActivityScenarioRule</h4><p>This rule is forwarding calls to its launch() methods to ActivityScenario.</p><pre>class LazyActivityScenarioRule&lt;A : Activity&gt;(<br>    private val activityClass: Class&lt;A&gt;,<br>) : ExternalResource() {<br>    private var localScenario: ActivityScenario&lt;A&gt;? = null<br>    val scenario: ActivityScenario&lt;A&gt;?<br>        get() = localScenario</pre><pre>    fun launch(): ActivityScenario&lt;A&gt; {<br>        localScenario?.close() // We close any potential previous scenario to release underneath resources.<br>        return ActivityScenario.launch(activityClass).also {<br>            localScenario = it<br>        }<br>    }</pre><pre>    fun launch(intent: Intent): ActivityScenario&lt;A&gt; {<br>        localScenario?.close() // We close any potential previous scenario to release underneath resources.<br>        return ActivityScenario.launch&lt;A&gt;(intent).also {<br>            localScenario = it<br>        }<br>    }</pre><pre>    override fun after() {<br>        super.after()<br>        localScenario?.close()<br>    }<br>}</pre><p>We can call it from our test class</p><pre>@RunWith(AndroidJUnit4::class)<br>class Test {</pre><pre>    // Do not automatically launch the Activity, as we need setup to be executed first<br>    @get:Rule<br>    val lazyScenarioRule = LazyActivityScenarioRule(ActivityUnderTest::class.java)</pre><pre>	@Test<br>	fun test() {<br>	    // Arrange<br>	       // Specific test setup here<br>	    // Act<br>		lazyScenarioRule.launch()<br>	    // Assert<br>	       // Verify behaviour here<br>	}</pre><p>Thanks to the rule, we do not need to think about resource closing.</p><h3>Issue with ActivityScenario</h3><p>Now, we have a replacement for ActivityTestRule that allows us to configure the test before actually launching the Activity under test. It is working well for most cases, but we are facing an issue for a particular scenario that will force us to keep with ActivityTestRule for this case. The issue is happening on a complex flow involving a notification or a deeplink.</p><h4>Real world case</h4><p>Let’s say that we have an application with a Login screen. Log in into the app starts a communication with the back-end. It may notify us that we need to change our password because it has expired. Then the user needs to go to his email to click on a validation link that leads back to the application. The deeplink opens a page that propose the user to update its data. Once done, the screen is closing and the user should ends in login screen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gNZM8j2lytWttTTkcLh91g.png" /></figure><h4>Simulation</h4><p>A repo has been set up to simulate such a behaviour : <a href="https://github.com/bastienpaulfr/ActivityScenarioBug">https://github.com/bastienpaulfr/ActivityScenarioBug</a></p><p>Let’s define several Activities : MainActivity, A, B, C and DeeplinkSimulatorActivity</p><p>👉 Manifest attributes of DeeplinkSimulatorActivity are:</p><pre>android:launchMode=&quot;singleInstance&quot;<br>android:noHistory=&quot;true&quot;</pre><p>In Android test we have set up this flow:</p><ol><li>MainActivity starts A with Intent.FLAG_ACTIVITY_NEW_TASK then A starts B</li><li>Go to launcher</li><li>Open Deeplink Activity that that starts C</li><li>Press back until reaching MainActivity</li></ol><h4>With old deprecated ActivityTestRule</h4><p>Everything is fine, test run as expected.</p><h4>With use of ActivityScenario</h4><p>We have an issue in UI testing. Pressing back goes from C to B then to Activity A, pressing again closes the app and goes to launcher screen instead of going to main activty.</p><blockquote>❓ So what’s going on here ???</blockquote><p>Let’s have a look to the activity backstack when executing the flow. To be able to gig into Activities’s backstack, we have a wonderful adb command available :</p><pre>adb shell dumpsys activity activities</pre><h4>Happy path with ActivityTestRule</h4><p>Here MainActivity is launched by the deprecated ActivityTestRule</p><pre>@get:Rule<br>val mainActivityTestRule = ActivityTestRule(MainActivity::class.java, true, false)</pre><pre>@Test<br>fun pressingBackGoesBackToMainActivityWithActivityTestRule() {<br>    mainActivityTestRule.launchActivity(null)<br>    testFlow()<br>}</pre><ul><li>Launch MainActivity</li></ul><pre>* Task{aa107ad com.example.activityscenariobug}<br>    * Hist  #0: ActivityRecord{748bfdf MainActivity}</pre><p>Here, MainActivity is the root of the task.</p><ul><li>Start A</li></ul><pre>Task{aa107ad com.example.activityscenariobug }<br>    * Hist  #1: ActivityRecord{c68e87c ActivityA}<br>    * Hist  #0: ActivityRecord{748bfdf MainActivity}</pre><ul><li>Start B</li></ul><pre>* Task{aa107ad com.example.activityscenariobug}<br>    * Hist  #2: ActivityRecord{c5cea70 ActivityB}<br>    * Hist  #1: ActivityRecord{c68e87c ActivityA}<br>    * Hist  #0: ActivityRecord{748bfdf MainActivity}</pre><ul><li>Go back home</li></ul><pre>* Task{40701c1type=home com.google.android.apps.nexuslauncher/.NexusLauncherActivity}<br>      * Hist  #0: ActivityRecord{8ec5e9 NexusLauncherActivity }</pre><pre>  * Task{aa107ad com.example.activityscenariobug }<br>    * Hist  #2: ActivityRecord{c5cea70 ActivityB}<br>    * Hist  #1: ActivityRecord{c68e87c ActivityA}<br>    * Hist  #0: ActivityRecord{748bfdf MainActivity}</pre><p>Here we have two different tasks. The active one is the launcher</p><ul><li>Simulate a click on a deeplink by launching the DeepLinkSimulatorActivity that launches C in onCreate()</li></ul><pre>* Task{aa107ad com.example.activityscenariobug}<br>    * Hist  #3: ActivityRecord{cd5bfc9 ActivityC}<br>    * Hist  #2: ActivityRecord{c5cea70 ActivityB}<br>    * Hist  #1: ActivityRecord{c68e87c ActivityA}<br>    * Hist  #0: ActivityRecord{748bfdf MainActivity}</pre><p>Our app task is brung into front and C is put at the top of the stack.</p><p>👉 Pressing back pop up Activities until reaching the main one.</p><h4>Sad path with ActivityScenario</h4><p>Here, the main activity will be launched by ActivityScenario through the LazyActivityScenarioRule</p><pre>@get:Rule<br>val mainActivityScenarioRule = LazyActivityScenarioRule(MainActivity::class.java)</pre><pre>@Test<br>fun pressingBackGoesBackToMainActivityWithActivityScenario() {<br>    mainActivityScenarioRule.launch()<br>    testFlow()<br>}</pre><ul><li>Launch MainActivity</li></ul><pre>* Task{a032769 com.example.activityscenariobug.test}<br>    * Hist  #1: ActivityRecord{93f8a9b MainActivity }<br>    * Hist  #0: ActivityRecord{9084331 com.example.activityscenariobug.test/androidx.test.core.app.InstrumentationActivityInvoker$BootstrapActivity}</pre><p>We can see a difference between two ways. Here MainActivity is not the root of the task but InstrumentationActivityInvoker$BootstrapActivity is. Indeed, ActivityScenario is using a BootstrapActivity internally to launch the target activity.</p><p>It is very important to see that for the following.</p><ul><li>Start A</li></ul><pre>* Task{907b4a0 com.example.activityscenariobug}<br>    * Hist  #0: ActivityRecord{d22f407 ActivityA}</pre><pre>  * Task{a032769 com.example.activityscenariobug.test }<br>    * Hist  #1: ActivityRecord{93f8a9b MainActivity t155}<br>    * Hist  #0: ActivityRecord{9084331 com.example.activityscenariobug.test/androidx.test.core.app.InstrumentationActivityInvoker$BootstrapActivity}</pre><p>Here A has been put in another task. Please remember that we are starting it with Intent.FLAG_ACTIVITY_NEW_TASK flag. Actually, the use of this flag is not an option because in real app, this activity is started by an application context. This flag is mandatory in this case.</p><ul><li>Start B</li></ul><pre>* Task{907b4a0 com.example.activityscenariobug }<br>    * Hist  #1: ActivityRecord{7665f51 ActivityB}<br>    * Hist  #0: ActivityRecord{d22f407 ActivityA}</pre><pre>  * Task{a032769 com.example.activityscenariobug.test }<br>    * Hist  #1: ActivityRecord{93f8a9b MainActivity}<br>    * Hist  #0: ActivityRecord{9084331 com.example.activityscenariobug.test/androidx.test.core.app.InstrumentationActivityInvoker$BootstrapActivity}</pre><ul><li>Go back home</li></ul><pre>* Task{40701c1 type=home com.google.android.apps.nexuslauncher/.NexusLauncherActivity }<br>      * Hist  #0: ActivityRecord{8ec5e9 NexusLauncherActivity}</pre><pre>  * Task{907b4a0 com.example.activityscenariobug }<br>    * Hist  #1: ActivityRecord{7665f51 ActivityB}<br>    * Hist  #0: ActivityRecord{d22f407 ActivityA}</pre><pre>  * Task{a032769 com.example.activityscenariobug.test}<br>    * Hist  #1: ActivityRecord{93f8a9b MainActivity}<br>    * Hist  #0: ActivityRecord{9084331 com.example.activityscenariobug.test/androidx.test.core.app.InstrumentationActivityInvoker$BootstrapActivity}</pre><p>Here we have three different tasks. The active one is the launcher</p><ul><li>Simulate a click on a deeplink by launching the DeepLinkSimulatorActivity that launches C in onCreate()</li></ul><pre>* Task{907b4a0 com.example.activityscenariobug }<br>    * Hist  #2: ActivityRecord{a75af6b ActivityC}<br>    * Hist  #1: ActivityRecord{7665f51 ActivityB}<br>    * Hist  #0: ActivityRecord{d22f407 ActivityA}</pre><pre>  * Task{a032769 com.example.activityscenariobug.test }<br>    * Hist  #1: ActivityRecord{93f8a9b MainActivity}<br>    * Hist  #0: ActivityRecord{9084331 com.example.activityscenariobug.test/androidx.test.core.app.InstrumentationActivityInvoker$BootstrapActivity}</pre><p>Here we have two stacks related to our activities. Pressing back from C will only affect the foreground task ( Task{907b4a0 #156 ).</p><pre>* Task{40701c1 type=home com.google.android.apps.nexuslauncher/.NexusLauncherActivity<br>      * Hist  #0: ActivityRecord{8ec5e9 NexusLauncherActivity}</pre><p>When we are on A, pressing back quits the app instead of going to MainActivity</p><h4>Role and behaviour of FLAG_ACTIVITY_NEW_TASK Intent flag</h4><p>Actually, everything is around the Intent.FLAG_ACTIVITY_NEW_TASK flag and its behaviour. On one hand, starting an activity with this flag put it inside the same stack than the caller. On the other hand, starting an Activity with this flag put it inside another task. There is a bit of magic here. I guess it is related to the task affinity.</p><p>Let’s have a look 👀 to Android <a href="https://developer.android.com/guide/topics/manifest/activity-element">&lt;activity&gt; documentation</a> 📖:</p><blockquote>📖 android:taskAffinity</blockquote><blockquote>The task that the activity has an affinity for. Activities with the same affinity conceptually belong to the same task (to the same “application” from the user’s perspective). The affinity of a task is determined by the affinity of its root activity.</blockquote><blockquote>The affinity determines two things — the task that the activity is re-parented to (see the <a href="https://developer.android.com/guide/topics/manifest/activity-element#reparent">allowTaskReparenting</a> attribute) and the task that will house the activity when it is launched with the <a href="https://developer.android.com/reference/android/content/Intent#FLAG_ACTIVITY_NEW_TASK">FLAG_ACTIVITY_NEW_TASK</a>flag.</blockquote><p>and in <a href="https://developer.android.com/guide/topics/manifest/application-element#aff">&lt;application&gt; documentation</a></p><blockquote>📖 android:taskAffinity</blockquote><blockquote>An affinity name that applies to all activities within the application, except for those that set a different affinity with their own <a href="https://developer.android.com/guide/topics/manifest/activity-element#aff">taskAffinity</a> attributes. See that attribute for more information.</blockquote><blockquote>By default, all activities within an application share the same affinity. The name of that affinity is the same as the package name set by the &lt;<a href="https://developer.android.com/guide/topics/manifest/manifest-element&gt;">manifest</a>&gt; element.</blockquote><p>We can deduce that starting an activity with the Intent.FLAG_ACTIVITY_NEW_TASK flag, rather put the activity in the task where is has the most affinity with instead of putting it in a new task each time it is started.</p><h4>Why it cannot work with ActivityScenario</h4><p>As seen before, ActivityScenario uses a BootstrapActivity to start our activity under test.</p><p>❓Question: why our activity under test resides inside the BootstrapActivity task ?</p><ol><li>BootstrapActivity is started in the test application task</li></ol><pre>* Task{a032769 #155 type=standard A=10154:com.example.activityscenariobug.test }</pre><blockquote><em>👉 com.example.activityscenariobug.test</em></blockquote><ol><li>The affinity of MainActivity is the package name of the application manifest. So it should be started on its own stack, but it is not.</li></ol><p>The reason resides inside the code of BootstrapActivity</p><pre>/* Override and disable FLAG_ACTIVITY_NEW_TASK flag by flagsMask and flagsValue. PendingIntentRecord#sendInner() will mask the original intent flag with the flagsMask then override those bits with the new flagsValue specified here. This override is necessary because if the activity is started as a new task ActivityStarter disposes the originator information and the result is never be delivered. Instead you will get an error &quot;Activity is launching as a new task, so cancelling activity result.&quot; and #onActivityResult() will be invoked immediately with result code Activity#RESULT_CANCELED. */</pre><pre>startIntentSenderForResult(<br>   startTargetActivityIntent.getIntentSender(),<br>   /*requestCode=*/ 0,<br>   /*fillInIntent=*/ null,<br>   /*flagsMask=*/ Intent.FLAG_ACTIVITY_NEW_TASK,<br>   /*flagsValues=*/ 0,<br>   /*extraFlags=*/ 0,<br>   options);</pre><blockquote>👉 Override and disable FLAG_ACTIVITY_NEW_TASK flag by flagsMask and flagsValue.</blockquote><p>This code erases the Intent.FLAG_ACTIVITY_NEW_TASK flag of the intent starting the activity under test. It means that, in our case, MainActivity is started by BootstrapActivity without the Intent.FLAG_ACTIVITY_NEW_TASK flag. This is the reason why it resides in the task of com.example.activityscenariobug.test instead of residing in the task of com.example.activityscenariobug</p><ol><li>When MainActivity starts ActivityA with the Intent.FLAG_ACTIVITY_NEW_TASK flag, ActivityA is put inside the task of com.example.activityscenariobug because of the affinity defined by default for ActivityA.</li></ol><blockquote><em>By default, all activities in an application have the same affinity.</em></blockquote><p><a href="https://developer.android.com/guide/topics/manifest/activity-element">&lt;activity&gt; documentation</a> 📖:</p><h3>We need to keep with ActivityTestRule for now</h3><p>For now, to test this specific use case, we need to keep with ActivityTestRule to be sure that all activities involved in our scenario resides in the same task</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f62ac27563e5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to make a good converter]]></title>
            <link>https://medium.com/@bastienpaul/how-to-make-a-good-converter-cc8ab5a989f6?source=rss-b3cd84d27c3------2</link>
            <guid isPermaLink="false">https://medium.com/p/cc8ab5a989f6</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[architecture]]></category>
            <dc:creator><![CDATA[Bastien Paul]]></dc:creator>
            <pubDate>Fri, 08 Jul 2022 13:59:45 GMT</pubDate>
            <atom:updated>2022-07-08T14:03:59.518Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_Ct73DRCMJxppKUEy7TAAA.jpeg" /><figcaption>Photo de Salah Alawadhi: <a href="https://www.pexels.com/fr-fr/photo/toit-en-acier-bleu-du-nouveau-marche-de-jardin-converti-1012200/">https://www.pexels.com/fr-fr/photo/toit-en-acier-bleu-du-nouveau-marche-de-jardin-converti-1012200/</a></figcaption></figure><h3>Purpose</h3><p>The purpose of the Converter pattern is to provide a generic, common way of bidirectional conversion between corresponding types, allowing a clean implementation in which the types do not need to be aware of each other.</p><p>In plain words, the Converter pattern makes it easy to map instances of one class into instances of another class.</p><p>We’re making use of Converter to map models when they are propagating between layers (API, Data, Domain, Presentation) to make them convenient to work with on a specific layer and do not spread extra dependencies to other layers.</p><h4>DIP</h4><p>Conversion is here to comply with dependency inversion principle. Domain layer only know about itself. UI layer needs to convert UI model into Domain DTO to deal with Domain layer. Data layer needs to convert Data model into Domain dto to deals with Domain layer.</p><h4>SRP</h4><p>We want to extract conversion methods to comply with Single Responsibility Principle. Putting conversion logic in its own scope, makes it easier to test. Extracting conversion logic from other classes, ensure that they focus on their business and not in conversion logic.</p><h3>Implementation</h3><p>Actually, there are different uses cases that we should handle that would trigger different implementations</p><h4>Simple extension method</h4><p>For the simpler cases, it is advised to stick with <a href="https://en.wikipedia.org/wiki/You_aren%27t_gonna_need_it">YAGNI</a> principle and have only an extension method in a file named &lt;source type&gt;To&lt;destination type&gt;Converter.kt because you aren’t gonna need a class.</p><pre>fun MyModel.toMyOtherModel() = MyOtherModel(<br>    attr1 = id,   <br>    attr2 = name,  <br>    //...<br>)</pre><p>👉 But I need to handle lists of items !</p><p>Kotlin is here to help thanks to the map{} extension to collection classes</p><pre>// Given this converter method<br>fun MyModel.toMyOtherModel(): MyOtherModel {}<br>// And the fact that we have a list of objects to convert<br>val myModels = listOf(myModel1, myModel2, myModel3)<br>// Convertion could be done with map extension method.val myOtherModels = myModels.map { it.toMyOtherModel() }</pre><p>❌ Do not call extension method from domain layer.</p><h3>Simple class</h3><p>You can create a converter class if you want to use Injection features or if you need additional contributors. You should always avoid to use kotlin objects because using a Singleton is often a code smell. It is a ressource killer because never destoyed. They are hiding dependencies and states and they are making your application more coupled.</p><h4>Example</h4><p>👉 Create the converter class that can be injected thanks to @Inject</p><pre>class ATypeToAnotherTypeConverter @Inject constructor() {</pre><pre>    fun convert(from: AType): AnotherType = when (this) {<br>       AType.A-&gt; AnotherType.A            <br>       AType.B-&gt; AnotherType.B    <br>    }<br>}</pre><h3>We need an additional contributor</h3><p>Sometimes you’ll need an additional contributor like a LocaleProvider or a DateProvider</p><p>👉 Inject them in the converter class</p><pre>class DomainDtoToUiModel @Inject constructor(    <br>    // here timezone is dynamic, it is retrieved from a provider<br>    timeZoneProvider: TimeZoneProvider<br>) {<br>    // Here date format is static. To make is dynamic, format can be injected in constructor.      <br>    private val simpleDateFormat = SimpleDateFormat(/*...*/)<br>    <br>    fun convert(dto: DomainDto): UiModel {  <br>       return UiModel(<br>            displayDate = simpleDateFormat.format(<br>               dto.currentDate, timeZoneProvider.getLocalTimeZone()<br>            )<br>       )<br>    }<br>}</pre><h3>We need a converter with additional parameters</h3><p>Most of the time, it is an unexpected case. Converters have 1:1 relationship.</p><p>💡 If logic begins to be complex, or you’re creating several implementations of an interface, you should consider using a <a href="https://refactoring.guru/design-patterns/factory-method">Factory</a> or a <a href="https://refactoring.guru/design-patterns/builder">Builder</a> instead.</p><p>You might want to convert a domain DTO in a model of UI or data layer, then use the last model along a factory to create more complex instance.</p><h3>✅ Do</h3><ul><li>Place converter in UI or Data layer (along ViewModel or DataSource)</li><li>Make converter as simple as possible</li></ul><h3>❌ Don’t</h3><ul><li>🧨 Conversion method can crash</li><li>Call converter from Domain layer</li><li>Implement complex logic</li><li>Extend very common classes like String, Long or Int</li></ul><h3>Naming</h3><h4>Class</h4><p>&lt;source type&gt;To&lt;destination type&gt;Converter, e.g.:</p><ul><li>LocalCardToCardConverter (LocalCard 👉 Card)</li><li>RequestToLocalRequestConverter (Request 👉 LocalRequest)</li></ul><p>💡 It should be clear what types converters are converting. This is the reason why the source type and the destination type are mentioned.</p><h4>Extension method</h4><p>The extension method used for converting the extended object into the target one should be named : fun Model.toNameOfTargetedClass(){}</p><p>It should belong to a file named &lt;source type&gt;To&lt;destination type&gt;Converter.kt</p><p>💡 The destination type of the converter extension method should be crystal clear. A model can also be converted in several kind of classes. This is the reason why methods like .toDomainModel() or .toDataModel() are not encouraged.</p><p>Given this data classes:</p><pre>// Data layer<br>data class RemoteTypeOfMyObject()<br>// Domain layer<br>data class MyAwesomeData()<br>// UI layer<br>data class AwesomeUiState()</pre><p>Then we should have these extension methods</p><pre>// Data layer<br>fun RemoteTypeOfMyObject.toMyAwsomeData(): MyAwesomeData<br>fun MyAwesomeData.toRemoteTypeOfMyObject(): RemoteTypeOfMyObject<br>// UI Layer<br>fun AwsomeUiState.toMyAwsomeData(): MyAwesomeData<br>fun MyAwesomeData.toAwesomeUiState(): AwesomeUiState</pre><h3>File</h3><p>Converter class or methods should be placed into their belonging layer, not in the domain one.</p><p>⚠️ Domain layer should not know about classes that are in UI or in Data layer.</p><h3>Layers</h3><h4>Data</h4><p>Converters in data layer should be called from data sources. Repositories are dealing with business models.</p><h4>UI</h4><p>Converters in UI layer should be called from ViewModels. They are the bridge between UI model and business rules (implemented in UseCases)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cc8ab5a989f6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Add a new line at the end of each text files tracked by git]]></title>
            <link>https://medium.com/@bastienpaul/add-a-new-line-at-the-end-of-each-text-files-tracked-by-git-dfa390005730?source=rss-b3cd84d27c3------2</link>
            <guid isPermaLink="false">https://medium.com/p/dfa390005730</guid>
            <category><![CDATA[shell]]></category>
            <category><![CDATA[de]]></category>
            <category><![CDATA[script]]></category>
            <category><![CDATA[git]]></category>
            <category><![CDATA[grep]]></category>
            <dc:creator><![CDATA[Bastien Paul]]></dc:creator>
            <pubDate>Mon, 30 Mar 2020 17:40:10 GMT</pubDate>
            <atom:updated>2020-03-30T18:00:53.424Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IAJh2M_0BwwkWQP3gnkZMQ.jpeg" /><figcaption>Image par <a href="https://pixabay.com/fr/users/44833-44833/?utm_source=link-attribution&amp;amp;utm_medium=referral&amp;amp;utm_campaign=image&amp;amp;utm_content=166543&quot;">Jim Semonik</a> de <a href="https://pixabay.com/fr/?utm_source=link-attribution&amp;amp;utm_medium=referral&amp;amp;utm_campaign=image&amp;amp;utm_content=166543">Pixabay</a></figcaption></figure><p>One of the most anoying thing I meet when I am coding software, is the “ No new line at end of file “ warning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/0*uN7mi2tRYJMccHRO" /></figure><p>For this, I have written a little script based of my research on google. I want to rewrite all text files tracked by git and ensure that a new line is written at the end of file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8c52168240d964ece83d165e2754b40e/href">https://medium.com/media/8c52168240d964ece83d165e2754b40e/href</a></iframe><p>You can execute it from a git repository and commit the result.</p><p><em>Originally published at </em><a href="https://bastienpaulblog.wordpress.com/2020/03/30/add-a-new-line-at-the-end-of-each-text-files-tracked-by-git/"><em>http://bastienpaulblog.wordpress.com</em></a><em> on March 30, 2020.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dfa390005730" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to create a circlular file logger with Timber]]></title>
            <link>https://medium.com/@bastienpaul/how-to-create-a-circlular-file-logger-with-timber-7d5e41dec012?source=rss-b3cd84d27c3------2</link>
            <guid isPermaLink="false">https://medium.com/p/7d5e41dec012</guid>
            <category><![CDATA[timber]]></category>
            <category><![CDATA[logcat]]></category>
            <category><![CDATA[logs]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[treessence]]></category>
            <dc:creator><![CDATA[Bastien Paul]]></dc:creator>
            <pubDate>Fri, 01 Mar 2019 10:42:33 GMT</pubDate>
            <atom:updated>2019-03-01T12:46:35.737Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eOsn2__ZzC6TakF1DuVPWw.jpeg" /><figcaption>Photo par Skitterphoto sur Pixabay</figcaption></figure><h3>How to create a circular file logger with Timber</h3><p>In some applications, I need to store my logs in a file aside of traditional logcat. For this, I am making use of <a href="https://github.com/JakeWharton/timber">Timber</a> library. Because I don’t want to make my device full of logs, I wanted to use circular log files so that I can control the maximum amount of bytes taken by log data. To achieve this, I will use java Logger API to implement a new <em>Timber.Tree</em>. I also want some feature like log formatting and filtering.</p><p>All of this is implemented by <a href="https://github.com/bastienpaulfr/Treessence">Treessence</a> library.</p><h3>Log filtering</h3><p>To implement filtering an interface is defined :</p><pre>public interface Filter {<br><br>    <em>/**<br>     * </em><strong><em>@param </em></strong><em>priority Log priority.<br>     * </em><strong><em>@param </em></strong><em>tag      Tag for log.<br>     * </em><strong><em>@param </em></strong><em>message  Formatted log message.<br>     * </em><strong><em>@param </em></strong><em>t        Accompanying exceptions.<br>     * </em><strong><em>@return </em></strong><em>{</em><strong><em>@code </em></strong><em>true} if the log should be skipped, otherwise {</em><strong><em>@code </em></strong><em>false}.<br>     * </em><strong><em>@see </em></strong><em>timber.log.Timber.Tree#log(int, String, String, Throwable)<br>     */<br>    </em>boolean skipLog(int priority, String tag, String message, Throwable t);<br><br>    boolean isLoggable(int priority, String tag);<br>}</pre><p>Priority filtering is provided by an implementation of this interface</p><pre>public class PriorityFilter implements Filter {<br><br>    private final int minPriority;<br><br>    public PriorityFilter(int minPriority) {<br>        this.minPriority = minPriority;<br>    }<br><br>    @Override<br>    public boolean skipLog(int priority, String tag, String message, Throwable t) {<br>        return priority &lt; minPriority;<br>    }<br><br>    @Override<br>    public boolean isLoggable(int priority, String tag) {<br>        return priority &gt;= minPriority;<br>    }<br><br>    public int getMinPriority() {<br>        return minPriority;<br>    }<br>}</pre><p>We can now create our base class extending <em>Timber.DebugTree</em></p><pre>public class PriorityTree extends Timber.DebugTree {<br><br>    private final PriorityFilter priorityFilter;<br>    private Filter filter = NoFilter.<em>INSTANCE</em>;<br><br>    <em>/**<br>     * </em><strong><em>@param </em></strong><em>priority priority from witch log will be logged<br>     */<br>    </em>public PriorityTree(int priority) {<br>        this.priorityFilter = new PriorityFilter(priority);<br>    }<br><br>    <em>/**<br>     * Add additional {</em><strong><em>@link </em></strong><em>Filter}<br>     *<br>     * </em><strong><em>@param </em></strong><em>f Filter<br>     * </em><strong><em>@return </em></strong><em>itself<br>     */<br>    </em>public PriorityTree withFilter(@NotNull Filter f) {<br>        this.filter = f;<br>        return this;<br>    }<br><br>    @Override<br>    protected boolean isLoggable(int priority) {<br>        return isLoggable(&quot;&quot;, priority);<br>    }<br><br>    @Override<br>    public boolean isLoggable(String tag, int priority) {<br>        return priorityFilter.isLoggable(priority, tag) &amp;&amp; filter.isLoggable(priority, tag);<br>    }<br><br>    public PriorityFilter getPriorityFilter() {<br>        return priorityFilter;<br>    }<br><br>    public Filter getFilter() {<br>        return filter;<br>    }<br><br>    <em>/**<br>     * Use the additional filter to determine if this log needs to be skipped<br>     *<br>     * </em><strong><em>@param </em></strong><em>priority Log priority<br>     * </em><strong><em>@param </em></strong><em>tag      Log tag<br>     * </em><strong><em>@param </em></strong><em>message  Log message<br>     * </em><strong><em>@param </em></strong><em>t        Log throwable<br>     * </em><strong><em>@return </em></strong><em>true if needed to be skipped or false<br>     */<br>    </em>protected boolean skipLog(int priority, String tag, @NotNull String message, Throwable t) {<br>        return filter.skipLog(priority, tag, message, t);<br>    }<br>}</pre><p>This class can filter on two parameters :</p><ul><li>First parameter is obviously log priority. This is done thanks to <em>PriorityFilter</em> instance.</li><li>Second parameter is an additional <em>Filter</em> instance that can be provided by caller.</li></ul><h3>Log formatting</h3><p>Log formatting is obtained thanks to a <em>Formatter</em> class whose interface is defined as follow</p><pre>public interface Formatter {<br><br>    String format(int priority, String tag, String message);<br>}</pre><p>Each formatter can display log to a defined format. For instance, logcat format is <strong><em>« MM-dd HH:mm:ss:SSS {priority}/{tag}({thread id}) : {message}\n »</em></strong>. Another format would be <strong><em>« {tag} : {message} »</em></strong></p><p>Because we want to log in a file what we get in logcat, then we need to implement a logcat formatter</p><pre>public class LogcatFormatter implements Formatter {<br><br>    public static final LogcatFormatter <em>INSTANCE </em>= new LogcatFormatter();<br>    private static final String <em>SEP </em>= &quot; &quot;;<br><br>    private final HashMap&lt;Integer, String&gt; prioPrefixes = new HashMap&lt;&gt;();<br><br>    private LogcatFormatter() {<br>        prioPrefixes.put(Log.<em>VERBOSE</em>, &quot;V/&quot;);<br>        prioPrefixes.put(Log.<em>DEBUG</em>, &quot;D/&quot;);<br>        prioPrefixes.put(Log.<em>INFO</em>, &quot;I/&quot;);<br>        prioPrefixes.put(Log.<em>WARN</em>, &quot;W/&quot;);<br>        prioPrefixes.put(Log.<em>ERROR</em>, &quot;E/&quot;);<br>        prioPrefixes.put(Log.<em>ASSERT</em>, &quot;WTF/&quot;);<br>    }<br><br>    @Override<br>    public String format(int priority, String tag, @NotNull String message) {<br>        String prio = prioPrefixes.get(priority);<br>        if (prio == null) {<br>            prio = &quot;&quot;;<br>        }<br>        return TimeUtils.<em>timestampToDate</em>(System.<em>currentTimeMillis</em>(), &quot;MM-dd HH:mm:ss:SSS&quot;)<br>               + <em>SEP<br>               </em>+ prio<br>               + (tag == null ? &quot;&quot; : tag)<br>               + &quot;(&quot; + Thread.<em>currentThread</em>().getId() + &quot;) :&quot;<br>               + <em>SEP<br>               </em>+ message<br>               + &quot;\n&quot;;<br>    }<br>}</pre><p>Priority class can then be extended to add format functionality</p><pre><em>/**<br> * Base class to format logs<br> */<br></em>public class FormatterPriorityTree extends PriorityTree {<br>    private Formatter formatter = getDefaultFormatter();<br><br>    public FormatterPriorityTree(int priority) {<br>        super(priority);<br>    }<br><br>    <em>/**<br>     * Set {</em><strong><em>@link </em></strong><em>Formatter}<br>     *<br>     * </em><strong><em>@param </em></strong><em>f formatter<br>     * </em><strong><em>@return </em></strong><em>itself<br>     */<br>    </em>public FormatterPriorityTree withFormatter(Formatter f) {<br>        this.formatter = f;<br>        return this;<br>    }<br><br>    <em>/**<br>     * Use its formatter to format log<br>     *<br>     * </em><strong><em>@param </em></strong><em>priority Priority<br>     * </em><strong><em>@param </em></strong><em>tag      Tag<br>     * </em><strong><em>@param </em></strong><em>message  Message<br>     * </em><strong><em>@return </em></strong><em>Formatted log<br>     */<br>    </em>protected String format(int priority, String tag, @NotNull String message) {<br>        return formatter.format(priority, tag, message);<br>    }<br><br>    <em>/**<br>     * </em><strong><em>@return </em></strong><em>Default log {</em><strong><em>@link </em></strong><em>Formatter}<br>     */<br>    </em>protected Formatter getDefaultFormatter() {<br>        return NoTagFormatter.<em>INSTANCE</em>;<br>    }<br><br>    @Override<br>    protected void log(int priority, String tag, @NotNull String message, Throwable t) {<br>        super.log(priority, tag, format(priority, tag, message), t);<br>    }<br>}</pre><h3>File logging</h3><p>We have seen how to filter and format logs. We can now start logging in file.</p><p>For this we need a <em>java.util.logging.Logger</em> instance. It will be used in conjunction with <em>java.util.logging.FileHandler</em> that do actual file logging. We will see how to create a <em>Logger</em> instance later.</p><pre>public class FileLoggerTree extends FormatterPriorityTree {<br>    private final Logger logger;<br>  <br>    private FileLoggerTree(int priority,<br>                           Logger logger) {<br>        super(priority);<br>        this.logger = logger;<br>    }<br>}</pre><p>To activate logcat formatting by default, <em>getDefaultFormatter()</em> method is overridden</p><pre>@Override<br>protected fr.bipi.tressence.common.formatter.Formatter getDefaultFormatter() {<br>    return LogcatFormatter.<em>INSTANCE</em>;<br>}</pre><p>We need to convert logcat level to <em>java.util.logging.Level</em></p><pre>private Level fromPriorityToLevel(int priority) {<br>    switch (priority) {<br>        case Log.<em>VERBOSE</em>:<br>            return Level.<em>FINER</em>;<br>        case Log.<em>DEBUG</em>:<br>            return Level.<em>FINE</em>;<br>        case Log.<em>INFO</em>:<br>            return Level.<em>INFO</em>;<br>        case Log.<em>WARN</em>:<br>            return Level.<em>WARNING</em>;<br>        case Log.<em>ERROR</em>:<br>            return Level.<em>SEVERE</em>;<br>        case Log.<em>ASSERT</em>:<br>            return Level.<em>SEVERE</em>;<br>        default:<br>            return Level.<em>FINEST</em>;<br>    }<br>}</pre><p>Actual logging is done by this method</p><pre>@Override<br>protected void log(int priority, String tag, @NotNull String message, Throwable t) {<br>    if (skipLog(priority, tag, message, t)) {<br>        return;<br>    }<br><br>    logger.log(fromPriorityToLevel(priority), format(priority, tag, message));<br>    if (t != null) {<br>        logger.log(fromPriorityToLevel(priority), &quot;&quot;, t);<br>    }<br>}</pre><p>It is logging in using <em>java.utils.logging</em> API with log level conversion and logcat formatting</p><p>We haven’t seen how to provide the right logger. Let see how to configure it.</p><p>A builder class is defined to create a <em>FileLoggerTree</em> instance. This builder contains some default:</p><pre>public static class Builder {<br>    // 1 mb byte of data<br>    private static final int <em>SIZE_LIMIT </em>= 1048576;<br>    // Max 3 files for circular logging<br>    private static final int <em>NB_FILE_LIMIT </em>= 3;<br><br>    // Base filename. <br>    // log index will be appended so actual file name will be<br>    // &quot;log.0&quot; or &quot;log.1&quot;<br>    // To parametrize where index is put, &quot;%g&quot; can be placed <br>    // in file name. For instance &quot;log%g.logcat&quot; will give<br>    // &quot;log0.logcat&quot;, &quot;log1.logcat&quot; and so on<br>    private String fileName = &quot;log&quot;; <br>    // Directory where files are stored<br>    private String dir = &quot;&quot;;<br>    // Min priority to log from<br>    private int priority = Log.<em>INFO</em>;<br>    private int sizeLimit = <em>SIZE_LIMIT</em>;<br>    private int fileLimit = <em>NB_FILE_LIMIT</em>;<br>    // append log to already existing log file<br>    private boolean appendToFile = true;<br><br>...</pre><p><em>java.util.logging.Logger</em> are created and managed by <em>java.util.logging.LogManager</em>. To bypass this a simple static class is used</p><pre><em>/**<br> * Custom logger class that has no references to LogManager<br> */<br></em>private static class MyLogger extends Logger {<br><br>    <em>/**<br>     * Constructs a {</em><strong><em>@code </em></strong><em>Logger} object with the supplied name and resource<br>     * bundle name; {</em><strong><em>@code </em></strong><em>notifyParentHandlers} is set to {</em><strong><em>@code </em></strong><em>true}.<br>     * &lt;p/&gt;<br>     * Notice : Loggers use a naming hierarchy. Thus &quot;z.x.y&quot; is a child of &quot;z.x&quot;.<br>     *<br>     * </em><strong><em>@param </em></strong><em>name the name of this logger, may be {</em><strong><em>@code </em></strong><em>null} for anonymous<br>     *             loggers.<br>     */<br>    </em>MyLogger(String name) {<br>        super(name, null);<br>    }<br><br>    public static Logger getLogger(String name) {<br>        return new MyLogger(name);<br>    }<br>}</pre><p>Creation of <em>java.util.logging.Logger</em> can start</p><pre>public FileLoggerTree build() throws IOException {<br>  // Log file path<br>  String path = FileUtils.<em>combinePath</em>(dir, fileName);<br>  // File handler that is performing file logging<br>  FileHandler fileHandler;<br>  // Our custom logger<br>  Logger logger = MyLogger.<em>getLogger</em>(<em>TAG</em>);<br>  // We force level to ALL because priority filtering is<br>  // done by our Tree implementation<br>  logger.setLevel(Level.<em>ALL</em>);<br>  // File handler can now be created<br>  fileHandler = new FileHandler(path, sizeLimit, fileLimit,  appendToFile);<br>  // Formating is done by our Tree implementation<br>  fileHandler.setFormatter(new NoFormatter());<br>  // Configure java Logger<br>  logger.addHandler(fileHandler);<br>  // finally we got here !<br>  return new FileLoggerTree(priority, logger);<br>}</pre><p>Full code of FileLoggerTree is here : <a href="https://github.com/bastienpaulfr/Treessence/blob/master/treessence/src/main/java/fr/bipi/tressence/file/FileLoggerTree.java">https://github.com/bastienpaulfr/Treessence/blob/master/treessence/src/main/java/fr/bipi/tressence/file/FileLoggerTree.java</a></p><p>This tree can then be planted like this</p><pre>FileLoggerTree fileTree = FileLoggerTree.Builder()<br>        .withFileName(&quot;log%g.logcat&quot;)<br>        .withMinPriority(Log.<em>VERBOSE</em>)<br>        .build()<br>Timber.plant(fileTree)</pre><p>Thanks for reading this. Full source code is available <a href="https://github.com/bastienpaulfr/Treessence">here</a></p><p><em>Originally published at </em><a href="http://bastienpaul.fr/wordpress/2019/03/01/how-to-create-a-circlular-file-logger-with-timber/"><em>bastienpaul.fr</em></a><em> on March 1, 2019.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7d5e41dec012" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Publish a Kotlin lib with gradle Kotlin DSL]]></title>
            <link>https://medium.com/@bastienpaul/publish-a-kotlin-lib-with-gradle-kotlin-dsl-ec3369464e38?source=rss-b3cd84d27c3------2</link>
            <guid isPermaLink="false">https://medium.com/p/ec3369464e38</guid>
            <category><![CDATA[maven]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[build]]></category>
            <category><![CDATA[bintray]]></category>
            <category><![CDATA[gradle]]></category>
            <dc:creator><![CDATA[Bastien Paul]]></dc:creator>
            <pubDate>Fri, 08 Feb 2019 15:16:09 GMT</pubDate>
            <atom:updated>2019-02-08T15:39:24.455Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hK_Y0DWvpFcT01FFtUp7fQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/8Gg2Ne_uTcM?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">贝莉儿 NG</a> on <a href="https://unsplash.com/search/photos/build?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>I wanted to play more with Kotlin and I wanted to publish <a href="https://github.com/bastienpaulfr/geojson-kotlin">KGeoGson</a> lib to a remote maven repo.</p><p>I was following <a href="https://guides.gradle.org/building-kotlin-jvm-libraries/">gradle guide</a> to build my kotlin project with Kotlin DSL.</p><h3>Bootstrap Kotlin project</h3><p>Create project directory with files of your library you want to build and publish. You may have a directory structure like the following:</p><pre>project<br> ├── build.gradle.kts<br> ├── settings.gradle.kts<br> └── my-kotlin-library<br>     ├── build.gradle.kts<br>     └── src<br>         ├── main<br>         │   └── kotlin<br>         │       └── org<br>         │           └── example<br>         │               └── MyLibrary.kt<br>         └── test<br>             └── kotlin<br>                └── org<br>                    └── example<br>                        └── MyLibraryTest.kt</pre><h3>Setup</h3><p>Root <strong>build.gradle.kts</strong></p><pre>plugins <strong>{<br> </strong><em>`build-scan`<br></em><strong>}</strong></pre><pre><em>buildScan </em><strong>{<br> </strong><em>termsOfServiceUrl </em>= &quot;https://gradle.com/terms-of-service&quot;<br> <em>termsOfServiceAgree </em>= &quot;yes&quot; publishAlways()</pre><pre><strong>}</strong></pre><pre>val clean by <em>tasks</em>.<em>creating</em>(Delete::class) <strong>{<br> </strong>delete(<em>rootProject</em>.<em>buildDir</em>)</pre><pre><strong>}</strong></pre><p>In this file, « build-scan » plugin is activated and a clean task is added. That’s all for it</p><p><strong>settings.gradle.kts</strong></p><pre>include(&quot;lib&quot;)</pre><p>In this file, we define our modules</p><p><strong>lib/build.gradle.kts</strong></p><p>First we are adding some plugins</p><pre>plugins <strong>{<br> </strong>// Add Kotlin plugin to build our Kotlin lib<strong><br> </strong><em>kotlin</em>(&quot;jvm&quot;) <em>version </em>&quot;1.3.21&quot; <br> // Get version from git tags<br> id(&quot;fr.coppernic.versioning&quot;) <em>version </em>&quot;3.1.2&quot;<br> // Documentation for our code <br> id(&quot;org.jetbrains.dokka&quot;) <em>version </em>&quot;0.9.17&quot;<br> // Publication to bintray<br> id(&quot;com.jfrog.bintray&quot;) <em>version </em>&quot;1.8.4&quot;<br> // Maven publication<br> <em>`maven-publish`<br></em><strong>}</strong></pre><p>Then we are defining dependencies and their repositories for our code</p><pre><em>repositories </em><strong>{<br> </strong>jcenter() mavenCentral()</pre><pre><strong>}</strong></pre><pre><em>dependencies </em><strong>{<br> </strong><em>implementation</em>(&quot;org.jetbrains.kotlin:kotlin-stdlib-jdk7&quot;)<br> <em>implementation</em>(&quot;com.google.code.gson:gson:2.8.5&quot;)</pre><pre><em> testCompile</em>(&quot;junit:junit:4.12&quot;)</pre><pre><strong>}</strong></pre><p>We need some more tasks to add sources and javadoc to our lib. We are starting by configuring dokka task:</p><pre><em>tasks </em><strong>{<br> </strong><em>dokka </em><strong>{<br>   </strong>outputFormat = &quot;html&quot;<br>   outputDirectory = &quot;$<em>buildDir</em>/javadoc&quot;<br>   moduleName = <em>rootProject</em>.<em>name<br> </em><strong>}<br>}</strong></pre><p>We can then bundle documentation into a jar</p><pre>val dokkaJar by <em>tasks</em>.<em>creating</em>(Jar::class) <strong>{<br> </strong><em>group </em>= JavaBasePlugin.<em>DOCUMENTATION_GROUP<br> description </em>= &quot;Assembles Kotlin docs with Dokka&quot;<br> <em>archiveClassifier</em>.set(&quot;javadoc&quot;)<br> from(<em>tasks</em>.<em>dokka</em>)<br> dependsOn(<em>tasks</em>.<em>dokka</em>)<br><strong>}</strong></pre><p>We are creating another jar containing sources</p><pre>val sourcesJar by <em>tasks</em>.<em>creating</em>(Jar::class) <strong>{<br> </strong><em>archiveClassifier</em>.set(&quot;sources&quot;)<br> from(<em>sourceSets</em>.getByName(&quot;main&quot;).<em>allSource</em>)<br><strong>}</strong></pre><p>At this stage, you are able to compile your lib. The most important part of this article begins. Let’s see how publication is working. It is very important to configure pom.xml file of maven artifact in a right manner. Otherwise you will not be able to submit your library into JCenter repo.</p><p>Let’s start configuring base of maven publish plugin</p><pre>val artifactName = &quot;libname&quot;<br>val artifactGroup = &quot;org.example&quot;</pre><pre><em>publishing </em><strong>{<br> </strong>publications <strong>{<br>   </strong><em>create</em>&lt;MavenPublication&gt;(&quot;lib&quot;) <strong>{<br>     </strong><em>groupId </em>= artifactGroup<br>     <em>artifactId </em>= artifactName<br>     // version is gotten from an external plugin<br>     <em>version </em>= <em>project</em>.<em>versioning</em>.<em>info</em>.<em>display</em></pre><pre><em>     // This is the main artifact<br>     </em>from(<em>components</em>[&quot;java&quot;]) </pre><pre>     // We are adding documentation artifact <br>     artifact(dokkaJar) <br>     // And sources <br>     artifact(sourcesJar)<br>    <strong>} <br>  }<br>}</strong></pre><p>Now we need to add information about package in <strong>pom.xml</strong> file. You can edit <strong>pom.xml</strong> with <strong><em>pom</em>.withXml {</strong>code</p><pre>val pomUrl = &quot;...&quot;<br>val pomScmUrl = &quot;...&quot;<br>val pomIssueUrl = &quot;...&quot;<br>val pomDesc = &quot;...&quot;<br>val pomScmConnection = &quot;&quot;...&quot;<br>val pomScmDevConnection = &quot;...&quot;<br>val githubRepo = &quot;...&quot;<br>val githubReadme = &quot;...&quot;<br>val pomLicenseName = &quot;The Apache Software License, Version 2.0&quot;<br>val pomLicenseUrl = &quot;http://www.apache.org/licenses/LICENSE-2.0.txt&quot;<br>val pomLicenseDist = &quot;repo&quot;<br>val pomDeveloperId = &quot;...&quot;<br>val pomDeveloperName = &quot;...&quot;</pre><pre><em>publishing </em><strong>{<br> </strong>publications <strong>{<br>    </strong><em>create</em>&lt;MavenPublication&gt;(&quot;lib&quot;) <strong>{<br>    </strong>[...]</pre><pre>    pom.withXml <strong>{<br>       </strong>asNode().apply <strong>{<br>          </strong>appendNode(&quot;description&quot;, pomDesc)<br>          appendNode(&quot;name&quot;, rootProject.name) <br>          appendNode(&quot;url&quot;, pomUrl)</pre><pre>          appendNode(&quot;licenses&quot;).appendNode(&quot;license&quot;).apply <strong>{<br>            </strong>appendNode(&quot;name&quot;, pomLicenseName)<br>            appendNode(&quot;url&quot;, pomLicenseUrl)<br>            appendNode(&quot;distribution&quot;, pomLicenseDist)<br>          <strong>}</strong></pre><pre><strong>          </strong>appendNode(&quot;developers&quot;).appendNode(&quot;developer&quot;).apply <strong>{<br>               </strong>appendNode(&quot;id&quot;, pomDeveloperId)<br>               appendNode(&quot;name&quot;, pomDeveloperName)<br>          <strong>}<br> <br>          </strong>appendNode(&quot;scm&quot;).apply <strong>{<br>             </strong>appendNode(&quot;url&quot;, pomScmUrl)<br>             appendNode(&quot;connection&quot;, pomScmConnection)<br>          <strong>}<br>        } <br>      } <br>    } <br>  }<br>}</strong></pre><p>Now that your maven publication is well configured, you can configure bintray plugin</p><pre><em>bintray </em><strong>{</strong><br><strong>  </strong>// Getting bintray user and key from properties file or command line<strong><br> </strong><em>user </em>= if (<em>project</em>.hasProperty(&quot;bintray_user&quot;)) <em>project</em>.property(&quot;bintray_user&quot;) as String else &quot;&quot;<br> <em>key </em>= if (<em>project</em>.hasProperty(&quot;bintray_key&quot;)) <em>project</em>.property(&quot;bintray_key&quot;) as String else &quot;&quot; <br> <br> // Automatic publication enabled<br> <em>publish </em>= true<br> <br> // Set maven publication onto bintray plugin<br> setPublications(&quot;lib&quot;) // Configure package</pre><pre><em> pkg</em>.<em>apply </em><strong>{<br>   </strong><em>repo </em>= &quot;maven&quot;<br>   <em>name </em>= <em>rootProject</em>.<em>name<br>   </em>setLicenses(&quot;Apache-2.0&quot;) <br>   setLabels(&quot;Gson&quot;, &quot;json&quot;, &quot;GeoJson&quot;, &quot;GPS&quot;, &quot;Kotlin&quot;)<br>   <br>   <em>vcsUrl </em>= pomScmUrl<br>   <em>websiteUrl </em>= pomUrl<br>   <em>issueTrackerUrl </em>= pomIssueUrl<br>   <em>githubRepo </em>= <em>githubRepo<br>   githubReleaseNotesFile </em>= githubReadme </pre><pre>   // Configure version<br>   <em>version</em>.<em>apply </em><strong>{<br>     </strong><em>name </em>= <em>project</em>.<em>versioning</em>.<em>info</em>.<em>display<br>     desc </em>= pomDesc<br>     <em>released </em>= Date().toString()<br>     <em>vcsTag </em>= <em>project</em>.<em>versioning</em>.<em>info</em>.<em>tag<br>    </em><strong>}<br>  }<br>}</strong></pre><p>Here we is ! Happy publication !</p><p><a href="https://bastienpaulblog.wordpress.com/author/bastienfamillepaul/">Voir tous les articles par Bastien Paul</a></p><p><em>Originally published at </em><a href="http://bastienpaul.fr/wordpress/2019/02/08/publish-a-kotlin-lib-with-gradle-kotlin-dsl/">http://bastienpaul.fr/</a><em> on February 8, 2019.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ec3369464e38" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Use Dagger Provider with Android Material Stepper]]></title>
            <link>https://medium.com/@bastienpaul/use-dagger-provider-with-android-material-stepper-ba3b6c458779?source=rss-b3cd84d27c3------2</link>
            <guid isPermaLink="false">https://medium.com/p/ba3b6c458779</guid>
            <category><![CDATA[dagger]]></category>
            <category><![CDATA[stepper]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Bastien Paul]]></dc:creator>
            <pubDate>Thu, 24 Jan 2019 12:58:35 GMT</pubDate>
            <atom:updated>2019-02-08T15:59:46.931Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CapYQYJPUjSL0zEzXuTJ_A.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/VwO622jf9ws?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Ksenia Makagonova</a> on <a href="https://unsplash.com/search/photos/dagger?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>On an Android project, I am using <a href="https://github.com/stepstone-tech/android-material-stepper">android-material-stepper</a> from StepStone. I am also using dependency injection with <a href="https://google.github.io/dagger/">dagger</a>.</p><p>I was facing the following problem : How to properly inject <em>Fragment</em>s without the need to create a <em>DaggerComponent</em> for each of them ?</p><p>Providers are here to help. This is how I am doing</p><pre>class StepFragmentBL @Inject constructor() :<br> Fragment(), Step, BlView {<br><br>    @Inject<br>    lateinit var blPresenter: BlPresenter<br><br>    ...<br>}</pre><p>This is one of the Fragment I am creating. We can see the <em>@Inject constructor</em> with <em>@Inject lateinit var</em> that shows that this object is injectable by dagger. It is also implementing <em>Step</em> to be used by <em>StepperLayout</em> and implements another interface.</p><pre>class BlPresenter @Inject constructor</pre><p><em>BlPresenter</em> is a simple injectable class</p><pre>@Singleton<br>@Component(modules = [(DeliveryModule::class)])<br>interface DeliveryComponents {<br><br>    fun inject(deliveryActivity: DeliveryActivity)<br>}</pre><p>This is the component injecting my Activity</p><pre>@Module<br>class DeliveryModule(private val activity: DeliveryActivity) {<br><br>    @Named(&quot;Activity&quot;)<br>    @Provides<br>    internal fun providesContext(): Context {<br>        return activity<br>    }<br><br>    @Provides<br>    fun providesFragmentManager(): FragmentManager {<br>        return activity.<em>supportFragmentManager<br>    </em>}<br>}</pre><pre>class DeliveryActivity : AppCompatActivity() {<br><br>    @Inject<br>    lateinit var deliveryPresenter: DeliveryPresenter<br><strong><br>    </strong>private lateinit var deliveryComponents: DeliveryComponents<br><br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        setContentView(R.layout.<em>activity_home</em>)<br><br>        di()<br>        ui()<br>    }<br><br>    private fun di() {<br>        deliveryComponents = DaggerDeliveryComponents.builder()<br>                .deliveryModule(DeliveryModule(this))<br>                .build()<br>        deliveryComponents.inject(this)<br>    }<br><br>    private fun ui() {<br>        Timber.v(Info.getMethodName())<br>        stepperLayout.<em>adapter </em>= deliveryPresenter.stepperAdapter<strong><br>    </strong>}<br>}</pre><p>We are creating the component into the Activity here. Then, presenter for this activity is also injected</p><pre>class DeliveryPresenter @Inject constructor() {<br><br>    @Inject<br>    lateinit var stepperAdapter: PickingStepperAdapter<br><br>}</pre><p>We are arriving to a StepperAdapter instance, also injected</p><pre>private const val <em>NB_FRAG </em>= 2<br><br>class PickingStepperAdapter @Inject constructor(<br>        fm: FragmentManager, <br>        @Named(&quot;Activity&quot;) context: Context) :<br>            AbstractFragmentStepAdapter(fm, context) {<br><br>    /**<br>    * Provider for Fragment<br>    */<br>    @Inject<br>    lateinit var blFragmentProvider: Provider&lt;StepFragmentBL&gt;<br><br>    /**<br>    * Provider for Fragment<br>    */<br>    @Inject<br>    lateinit var pdtFragmentProvider: Provider&lt;StepFragmentPdt&gt;<br><br>    override fun getCount(): Int {<br>        return <em>NB_FRAG<br>    </em>}<br><br>    override fun createStep(position: Int): Step {<br>        Timber.v(&quot;${Info.getMethodName()} $position&quot;)<br><br>        return when (position) {<br>            0 -&gt; blFragmentProvider.get()<br>            else -&gt; pdtFragmentProvider.get()<br>        }<br>    }<br>}</pre><p>Here, we are just using</p><pre>@Inject<br>    lateinit var blFragmentProvider: Provider&lt;StepFragmentBL&gt;</pre><p>to tell dagger to create the code that will provide an instance of fragment each time <em>blFragmentProvider.get()</em> will be called. Indeed, this is called here</p><pre>return when (position) {<br>            0 -&gt; blFragmentProvider.get()<br>            else -&gt; pdtFragmentProvider.get()<br>        }</pre><p>Like this, dagger is injecting fragment for us, and we don’t have to care about objects creation</p><p><em>Originally published at </em><a href="http://bastienpaul.fr/wordpress/2019/01/24/use-dagger-provider-with-android-material-stepper/"><em>bastienpaul.fr</em></a><em> on January 24, 2019.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ba3b6c458779" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>