<?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 Silas Candiolli on Medium]]></title>
        <description><![CDATA[Stories by Silas Candiolli on Medium]]></description>
        <link>https://medium.com/@candiolli?source=rss-7e346e98c1fe------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*BeQf2kdDTLso82RPWVo_Sg.png</url>
            <title>Stories by Silas Candiolli on Medium</title>
            <link>https://medium.com/@candiolli?source=rss-7e346e98c1fe------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 22:11:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@candiolli/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[A Guide to Execute Quarkus Applications on Kubernetes]]></title>
            <link>https://medium.com/abbeal/a-guide-to-execute-quarkus-applications-on-kubernetes-2ab9fb49716b?source=rss-7e346e98c1fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/2ab9fb49716b</guid>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[quarkus]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[could]]></category>
            <dc:creator><![CDATA[Silas Candiolli]]></dc:creator>
            <pubDate>Thu, 19 Oct 2023 00:52:52 GMT</pubDate>
            <atom:updated>2023-11-23T09:00:13.608Z</atom:updated>
            <content:encoded><![CDATA[<h4>Kubernetes native application with Quarkus</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gc_J7LorG6FHziOL" /><figcaption>Photo by <a href="https://unsplash.com/@enginakyurt?utm_source=medium&amp;utm_medium=referral">engin akyurt</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Java turned 28 in 2023, it is a big milestone for a platform that has already had its death prophesied so many times. The fact is that people trust Java and what it delivers, trust the evolution it has been undergoing and the way it solves problems.</p><p>Java has a very strong community that knows how to make the right decisions so that Java will not die. This community also contributed to language and virtual machine improvements.</p><p>Java has also gained the trust of large companies around the world. Most large banks in Brazil and Latin America use Java in the back-end, such as Banco do Brasil and Itaú. BNY Melon, from New York, is a bank that provides loans to other banks around the world and uses Java as well. Of course, the biggest companies in technology like IBM, Red Hat, Amazon, Google and Microsoft are using Java as well.<br>So, these are some examples of those who are interested in making Java run on the Cloud, because it is simple: knowledge and money.</p><h3>Some challenges on the way</h3><p>Anyone who has known Java long enough knows that running Java in the Cloud is a considerable challenge. While reliable, Java was created in a context where large monoliths were a necessity.<br>But when we talk about microservices the context changes, now there is independence between services, and a low startup time and low memory requirement are expected.<br>Also, portability matters too. Nowadays there is a lot of competition between Cloud servers, and there is also talk about multi-cloud, so having the power to run your App on AWS today and tomorrow on Google Cloud is also becoming a necessity. I haven’t particularly seen it happen in the big clients I’ve worked with, maybe it takes a while for it to be something normal, but it seems to be a trend.</p><h3>Kubernetes extension for Quarkus</h3><p>Because of that, I would like to write about <strong>Quarkus</strong> and its extension for <strong>Kubernetes, </strong>and how it came to help the teams to run <strong>Java on the Cloud.</strong></p><p>Some people call <a href="https://medium.com/abbeal/quarkus-why-you-should-explore-f5c14dc3c80a"><strong>Quarkus </strong></a>a framework, but I see some refer to it as a platform. I really like it and I also see Quarkus as a platform, it is more than a framework.<br>When adding extensions to your application they will already be pre-configured to be used, it’s good because it doesn’t require a lot of prior knowledge about the libraries you choose to use, you can use and learn during development, make improvements and configure adjustments later when you have more clarity of what you want.</p><p>So what does a Kubernetes extension offer to you:</p><h4>Single-step Deployment</h4><blockquote>Quarkus makes it easy to deploy microservice applications to Kubernetes without having to understand the intricacies of the underlying Kubernetes framework</blockquote><blockquote>— quarkus.io</blockquote><p>The strong integration of Quarkus with Kubernetes makes possible something that is not simple, nor normal, for most developers, and I include myself in that group.<br>Nowadays it is very normal to have teams focused on infrastructure, so the developer doesn’t have to worry about how and where the application will run. But on the other hand, the more experienced we become as developers, the more important it is to understand these details.</p><p>Having Quarkus as a ready-made platform to build a Docker image of your Java app and deploy it to Kubernetes is amazing. From my point of view, this opens many doors for those who are starting and need to see things running quickly. Maybe someone who is starting in the area of programming and studying Java, or an entrepreneur who wants to have his product in a cloud. But, making this integration simpler to do helps to popularize the technology, and that is good for everyone.</p><h4>Tracing, Debugging, Health Check and Metric</h4><p>Quarkus also has an extension for observability. <a href="https://quarkus.io/guides/opentelemetry">Opentelemetry</a> is used to get metrics and logging by your software and has faster troubleshooting.</p><p>For health checks and metrics, you can use the <a href="https://quarkus.io/guides/smallrye-health">SmallRye</a>. Can you imagine the chaos that could be to not know what is happening with specific microservices in production on Black Friday night?</p><h4>Application configuration</h4><p>Did you already need to config credentials to consume an API or connect to Databases? Well, the right way to do that is by using Secrets and ConfigMap as a configuration source, to avoid having passwords in your properties files. To help you with that there is the <a href="https://quarkus.io/guides/kubernetes-config">Kubernetes Config</a></p><h4>Remote development</h4><p>Using the Kubernetes extension together with that of your cloud provider, it is possible to configure Remote Development, which makes it possible to use Living Code by deploying in the cloud.<br>Maybe this makes more sense for small projects. Where you have fewer processes, environments and cycles.</p><h3>Hands-on</h3><p>To follow the steps and execute this project on your machine, we will use these tools:</p><ul><li><a href="https://docs.docker.com/engine/install/">Docker</a></li><li><a href="https://minikube.sigs.k8s.io/docs/start/">Minikube</a></li><li><a href="https://quarkus.io/guides/cli-tooling">Quarkus</a></li></ul><p>Now, let&#39;s see how easy it is to deploy a Quarkus App on Kubernetes.</p><ol><li>First, start the Docker and Minikube. Then, after that, you can create a new project and add new extensions:</li></ol><pre>// Start docker<br>docker start<br><br>// Start Minikube<br>minikube start<br><br>// Create a new Quarkus project<br>quarkus create app com.silascandiolli:qstart<br><br>// Add new extensions<br>quarkus extension add &#39;quarkus-kubernetes&#39;<br>quarkus extension add &#39;smallrye-health&#39;</pre><p>2. Now, you should open your new project <strong>application.properties </strong>file, and add the Kubernetes properties. It is important to say that you have to replace “<em>youruser”</em> for your current Docker Hub <strong>username</strong>:</p><pre>quarkus.container-image.group=youruser<br>quarkus.container-image.username=youruser<br>quarkus.container-image.tag=latest</pre><p>3. Once your project is ready, you could package the code, build the <strong>Docker image</strong> and push it to your <strong>Docker hub (do not forget to log in to Docker Hub)</strong>:</p><pre>./mvnw package -DskipTests<br>docker build -f src/main/docker/Dockerfile.jvm -t silasca/qstart .<br>docker login<br>docker image push silasca/qstart</pre><p>4. Now it is time to <strong>deploy </strong>on Minikube, and make it available on port 8080:</p><pre>kubectl apply -f target/kubernetes/kubernetes.yml<br>kubectl port-forward pod/qstart-xxxx 8080:8080</pre><p>5. Checking the Minikube running pods:</p><pre>kubectl get pods -w</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/559/1*hyR5kL6gcunXEqXjZsM9AA.png" /></figure><p>6. Testing the resources:</p><pre>curl localhost:8080/hello/silas<br>curl localhost:8080/hello<br>curl localhost:8080/q/health</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/351/1*hasBUWOaBTr5QmL_SOyU-A.png" /></figure><h3>Final considerations</h3><p>I hope this guide can help you to start and go deep into Quarkus. If you have any questions, please let me know, I will be pleased to help you in your journey.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2ab9fb49716b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/abbeal/a-guide-to-execute-quarkus-applications-on-kubernetes-2ab9fb49716b">A Guide to Execute Quarkus Applications on Kubernetes</a> was originally published in <a href="https://medium.com/abbeal">abbeal’s tech blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating my first App with Quarkus]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/abbeal/creating-my-first-app-with-quarkus-bba28603221f?source=rss-7e346e98c1fe------2"><img src="https://cdn-images-1.medium.com/max/2600/0*ZLZSHqLKs4HUT4XO" width="5760"></a></p><p class="medium-feed-snippet">A guide to getting started with Quarkus, using the CLI</p><p class="medium-feed-link"><a href="https://medium.com/abbeal/creating-my-first-app-with-quarkus-bba28603221f?source=rss-7e346e98c1fe------2">Continue reading on abbeal’s tech blog »</a></p></div>]]></description>
            <link>https://medium.com/abbeal/creating-my-first-app-with-quarkus-bba28603221f?source=rss-7e346e98c1fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/bba28603221f</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[quarkus]]></category>
            <dc:creator><![CDATA[Silas Candiolli]]></dc:creator>
            <pubDate>Thu, 17 Aug 2023 15:59:14 GMT</pubDate>
            <atom:updated>2023-09-26T18:04:16.867Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[An Introduction to Project Reactor]]></title>
            <link>https://medium.com/abbeal/an-introduction-to-project-reactor-4a1729dc6eda?source=rss-7e346e98c1fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/4a1729dc6eda</guid>
            <category><![CDATA[reactive-programming]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[reactor-project]]></category>
            <dc:creator><![CDATA[Silas Candiolli]]></dc:creator>
            <pubDate>Fri, 07 Jul 2023 20:58:25 GMT</pubDate>
            <atom:updated>2023-08-14T14:02:20.959Z</atom:updated>
            <content:encoded><![CDATA[<h4>Creating Efficient Reactive Systems with Java</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aj_kAusFjD2rtmZDqE4pYg.jpeg" /></figure><p><a href="https://projectreactor.io/">Project Reactor</a> is a powerful open-source library for building reactive applications in Java. It provides an extensive set of tools and abstractions that enable developers to write asynchronous, event-driven, and non-blocking code.</p><p>Reactor is based on the Reactive Streams specification, which defines a standard for building reactive systems. It embraces the reactive programming paradigm, where applications are designed to react to incoming events and efficiently handle concurrent and asynchronous operations.</p><p>At its core, Reactor introduces two fundamental data types: <strong>Flux</strong> and <strong>Mono</strong>. <strong>Flux </strong>represents a stream of zero to N elements, while <strong>Mono </strong>represents a stream that emits either zero or one element. These types provide a rich set of operators to perform various transformations and operations on data streams, such as mapping, filtering, and combining.</p><h3>Features</h3><p>One of the key features of Reactor is its support for backpressure. <strong>Backpressure </strong>is a mechanism that allows consumers to control the rate at which data is produced by publishers. Reactor provides strategies and operators to handle backpressure, ensuring that data flows smoothly through the system, preventing overload or resource exhaustion.</p><p>Error handling and resilience are also essential aspects of <strong>Reactor</strong>. The library provides operators to handle errors, such as retrying operations or falling back to alternative sources. It also integrates well with existing error-handling mechanisms in Java, making it easy to handle exceptions in reactive applications.</p><h3>Benefits</h3><p>With Reactor, developers can write scalable and efficient applications that are responsive and resilient to failures. Its functional and declarative programming style promotes code readability and maintainability, making it easier to reason about complex asynchronous workflows.</p><p>Project Reactor has gained significant popularity in the Java ecosystem and is widely used in various domains, including microservices, data streaming, and web development. It continues to evolve with regular updates, enhancements, and new features, staying at the forefront of reactive programming in Java.</p><p>Whether you’re building small-scale applications or large-scale distributed systems, Reactor empowers you to harness the power of reactive programming and unlock the benefits of asynchronous, event-driven development in Java.</p><h3>Hello Word</h3><p>To have a better understanding, the following code introduces you to how to create your first Mono and Flux.</p><pre>@Test<br>public void hello_world_mono() {<br>  // Create a Mono from String, but it could be a call to another function or reactive web service<br>  Mono&lt;String&gt; serviceResult = Mono.just(&quot;Hello World!&quot;);<br> <br>  // Use the block method to stop de flow and get results from serviceResult<br>  String result = serviceResult.block();<br> <br>  assertEquals(&quot;Hello World!&quot;, result);<br>}<br> <br>@Test<br>public void hello_world_flux() {<br>  // Create a Flux from String, but it could be a call to another function or reactive web service<br>  Flux&lt;String&gt; serviceResult = Flux.just(&quot;Hello World 1&quot;, &quot;Hello World 2&quot;);<br> <br>  // Use the block method to stop de flow and get results from serviceResult<br>  List&lt;String&gt; result = serviceResult.collectList().block();<br> <br>  for (int i = 1; i &lt; 3; i++) {<br>    assertEquals(&quot;Hello World &quot;+i, result.get(i-1));<br>  }<br>}</pre><p>Look at how I’m using the <em>block</em> method to get results from <em>Mono</em> and <em>Flux</em>. That is a very simple example, if you are working on a real project you will use the <em>StepVerifier</em> to test. <strong>StepVerifier </strong>is an interface that provides a declarative way to test async Publisher’s sequence, by expressing expectations.<br>Let&#39;s see how it works:</p><pre>@Test<br>public void hello_world_mono() {<br>  // Create a Mono from String, but it could be a call to another function or reactive web service<br>  Mono&lt;String&gt; serviceResult = Mono.just(&quot;Hello World!&quot;);<br><br>  StepVerifier<br>    .create(serviceResult)<br>    .expectNext(&quot;Hello World!&quot;)<br>    .expectComplete()<br>    .verify();<br>}<br><br>@Test<br>public void hello_world_flux() {<br>  // Create a Flux from String, but it could be a call to another function or reactive web service<br>  Flux&lt;String&gt; serviceResult = Flux.just(&quot;Hello World 1&quot;, &quot;Hello World 2&quot;);<br><br>  StepVerifier<br>    .create(serviceResult)<br>    .expectNext(&quot;Hello World 1&quot;)<br>    .expectNext(&quot;Hello World 2&quot;)<br>    .expectComplete()<br>    .verify();<br>}</pre><p>This way, you will subscribe to the Mono and Flux to verify the results when they arrive.</p><p>I hope this post helps you to know the Project Reactor and get started with reactive programming in Java. Enjoy!</p><p>Over the next <strong>10 weeks</strong>, I’ll be sharing content about <strong>Project Reactor</strong>. If you are interested, follow me there: <a href="https://github.com/candiolli/10WeeksOfProjectReactor">repository</a> and <a href="https://silascandiolli.com/">blog</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a1729dc6eda" width="1" height="1" alt=""><hr><p><a href="https://medium.com/abbeal/an-introduction-to-project-reactor-4a1729dc6eda">An Introduction to Project Reactor</a> was originally published in <a href="https://medium.com/abbeal">abbeal’s tech blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Quarkus, why you should explore it]]></title>
            <link>https://medium.com/abbeal/quarkus-why-you-should-explore-f5c14dc3c80a?source=rss-7e346e98c1fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/f5c14dc3c80a</guid>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[quarkus]]></category>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[containers]]></category>
            <dc:creator><![CDATA[Silas Candiolli]]></dc:creator>
            <pubDate>Fri, 19 May 2023 18:17:44 GMT</pubDate>
            <atom:updated>2023-06-02T13:16:09.017Z</atom:updated>
            <content:encoded><![CDATA[<h4>Supersonic Subatomic Java</h4><h4>Or how it can help <strong>you launch your product faster</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8Hu0HkPj7LOLRvJRgVB1PQ.png" /><figcaption><a href="https://quarkus.io/">https://quarkus.io/</a></figcaption></figure><p>When we work with enterprise applications it&#39;s essential to have great tools to help development teams create their apps, and focus on the business rules, without losing time.</p><p>But, to choose a new framework, platform, language, or library, we need more than “because it’s cool and everyone is talking about it.”. After choosing we will use it in-depth and explore all the benefits of this tool. Precisely because many problems have already been solved there, problems we shouldn’t get involved with.</p><blockquote>Modern tools for Java applications must be safe, continue to evolve with Java, and be ready for the cloud era.</blockquote><h4>What Makes Quarkus Different</h4><p>I hope to summarize for you why Quarkus is one of the best options on the market for creating your Java applications. Introducing below its characteristics and why they are important.</p><p><strong>Developer Joy: </strong>Because it is a fantastic tool to work with, helping the developer in small and big pains of the day.</p><p><strong>Kubernetes-native: </strong>Enabled to create native images for the most used container orchestrator today.</p><p><strong>Best of Breed Libraries and Standards: </strong>It offers integration with the best libraries with minimal configuration.</p><p><strong>Imperative and reactive code: </strong>No matter your programming paradigm, you can use Quarkus.</p><h3>About Quarkus</h3><h3>Container First</h3><blockquote>The central idea behind Quarkus is to do at build-time what traditional frameworks do at runtime: configuration parsing, classpath scanning, feature toggle based on classloading, and so on.</blockquote><blockquote>— quarkus.io</blockquote><p>Quarkus was designed and created to be a container-first platform. It’s one of its most striking features, which actually means creating applications for low memory usage and fast startup time.<br>For this to be possible, some strategies are taken, such as processing as many things as possible at build time, not at runtime.</p><p>Initializing as many extensions as possible while building the native image also results in a quick start.</p><p>The use of Reflection is also reduced to a minimum. Arc, the dependency injection framework used by Quarkus, is responsible for identifying the use of reflection and replacing it with regular calls.</p><h3>Kubernetes Native</h3><blockquote>The combination of Quarkus and Kubernetes provides an ideal environment for creating scalable, fast, and lightweight applications. Quarkus significantly increases developer productivity with tooling, pre-built integrations, application services, and more.</blockquote><blockquote>— quarkus.io</blockquote><p>You can get your application running on Kubernetes quickly because there are a lot of extensions on Quarkus. Extensions that will make the orchestration of your application possible with tracing, debugging, health checks, metrics, and configurations.<br><a href="https://quarkus.io/guides/deploying-to-kubernetes">See the guide for more details</a>.</p><h3>GraalVM</h3><blockquote>Build faster, smaller, leaner applications.</blockquote><blockquote>— <a href="https://www.graalvm.org/">graalvm.org</a></blockquote><p>GraalVM support is an essential part of Quarkus. With this, it is possible to build your application faster and smaller, with only what is necessary.<br>This considerably impacts the startup of your application, which becomes faster than in the traditional JVM. For the context of container and microservices, this is fantastic!!!<br>Quarkus has <em>first-class support for GraalVM native images</em>, and that’s one of the differentiators that has guided its road map so far.</p><h3>Reactive</h3><blockquote>Quarkus is designed to seamlessly combine the familiar imperative style code and the non-blocking, reactive style when developing applications.</blockquote><blockquote>— quarkus.io</blockquote><p>So no matter what your programming paradigm is, it’s possible to write reactive or imperative code, both will respond in a non-blocking way.<br>This makes the applications have a continuous flow. This is very important nowadays with modern software using architectures like microservices, reactive applications, event-driven architecture, and serverless.</p><h3>Developer Joy</h3><blockquote>Beyond simply working, we’re aiming for Joy.</blockquote><blockquote>— quarkus.io</blockquote><p>Quarkus is more than a framework, it&#39;s a development platform, and one of its goals is to make the developer experience the best possible. This means that every feature is done to work well, simply, with little or no configuration, and as intuitively as possible.</p><p>Using Quarkus on your projects, your teams can enjoy features like:</p><p>Live Coding: Change the code and test, a developer experience without build time and deploy time.</p><p>Unified Config: The configuration is in one place.</p><p>Dev UI: The developers are able to configure extensions, monitor the application, and test components.</p><p>Dev Services: Quarkus may support the automatic configuration of some services for development and testing purposes. Examples: Kafka, MongoDB, Neo4j, etc…</p><p>Command Line Interface (CLI): Using the command line it&#39;s possible to create projects, manage extensions and build applications.</p><p>Continuous Testing: Similar to Live Coding, change the code and get instant feedback from tests run.</p><p>Remote Development: Run local changes in a container environment remotely with <em>dev mode.</em></p><h3>Important links to read more and stay on top of Quarkus news</h3><p>Get started: <a href="https://quarkus.io/get-started/">https://quarkus.io/get-started/</a></p><p>Standards: <a href="https://quarkus.io/standards/">https://quarkus.io/standards/</a></p><p>Roadmap: <a href="https://github.com/orgs/quarkusio/projects/13/views/1">https://github.com/orgs/quarkusio/projects/13/views/1</a></p><p>Quarkus Newsletter: <a href="https://quarkus.io/newsletter/32/">https://quarkus.io/newsletter/32/</a></p><p>Blog: <a href="https://quarkus.io/blog/">https://quarkus.io/blog/</a></p><p>Discussion: <a href="https://quarkus.io/discussion/">https://quarkus.io/discussion/</a></p><h3>If you have any questions or want to know more, I am at your disposal.</h3><p>You can connect with me on <a href="https://www.linkedin.com/in/silascandiolli/"><strong>LinkedIn</strong></a><strong> or </strong><a href="https://twitter.com/silasca"><strong>Twitter</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f5c14dc3c80a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/abbeal/quarkus-why-you-should-explore-f5c14dc3c80a">Quarkus, why you should explore it</a> was originally published in <a href="https://medium.com/abbeal">abbeal’s tech blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[First steps to using JUnit 5]]></title>
            <link>https://medium.com/abbeal/first-steps-to-using-junit-5-797e0df4c357?source=rss-7e346e98c1fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/797e0df4c357</guid>
            <category><![CDATA[junit]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[test]]></category>
            <dc:creator><![CDATA[Silas Candiolli]]></dc:creator>
            <pubDate>Fri, 12 May 2023 02:08:51 GMT</pubDate>
            <atom:updated>2023-06-02T13:16:35.176Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*t2Z-mAdPAQMDM3FrUh3LfQ.png" /><figcaption><a href="https://junit.org/junit5/">https://junit.org/junit5/</a></figcaption></figure><p>In my previous article on <a href="https://medium.com/@candiolli/testing-your-java-code-with-mockito-f38135994d6f">Unit Tests and Mockito</a>, I discussed the advantage of using Mockito to manipulate object instances to focus on testing just what you want. That is awesome, you can use many combinations of returns and test all possibilities your method needs.</p><p>The latest versions of JUnit and Mockito brings some syntax and behavior changes. In this article, I want to explain how to start using <strong>JUnit 5</strong> and hope to answer the following questions:</p><h4><strong>1. How can I update my project without changing all the tests simultaneously?</strong></h4><h4>2. How can I use the new features?</h4><p>First of all, I’m checking the release notes. It’s essential to do this because I can look directly into this library&#39;s primary source of knowledge, the documentation, what’s new, and what’s deprecated. Here I can find the <a href="https://junit.org/junit5/docs/5.9.2/release-notes/"><em>Release Notes of JUnit 5.9.2</em></a></p><h3>1. How can I update my project without changing all the tests simultaneously?</h3><p>Let’s say I want to upgrade the JUnit, but I can’t change all tests within my project. I must adjust by taking baby steps because that takes some time and I can’t stop all my features and bug fixes just to adjust the tests.</p><p>Then I must add this Jupiter JUnit dependency:</p><pre>&lt;dependency&gt;<br>  &lt;groupId&gt;org.junit.vintage&lt;/groupId&gt;<br>  &lt;artifactId&gt;junit-vintage-engine&lt;/artifactId&gt;<br>  &lt;version&gt;${junit.jupiter.version}&lt;/version&gt;<br>  &lt;scope&gt;test&lt;/scope&gt;<br>&lt;/dependency&gt;</pre><h3>2. How can I use the new features?</h3><p>Thinking in baby steps, I’m starting with syntax changes. For example, if I remove the <strong>junit-vintage-engine</strong> dependency, some errors will happen on my tests.</p><h4>2.1. RunWith, Before, and Test annotations</h4><p>Like the RunWith, Before, and Test annotations. Note that the first change is the packages path.</p><p>On <strong>JUnit 4 </strong>it was <em>org.junit.*</em>, now in <strong>JUnit 5</strong> it is <em>org.junit.jupiter.* .</em></p><p>To execute the test using Mockito, the annotation <em>@RunWith(MockitoJUnitRunner.class)</em>changes to <em>@ExtendWith(MockitoExtension.class) .</em></p><p>When I need to execute code before each test, in <strong>JUnit 4</strong> I use <em>@Before</em>, now on <strong>JUnit 5</strong> I use <em>@BeforeEach .</em></p><p>I also need to change the class that makes the assertions of my test. That class will compare the values and return a positive or negative value. Change from <em>Assert.assertEquals to </em><em>Assertions.asserEquals .</em></p><p>It is possible to compare the following two blocks.</p><p><strong>JUnit 4</strong></p><pre>import org.junit.*;<br>import org.junit.runner.RunWith;<br><br>@RunWith(MockitoJUnitRunner.class)<br>class MyTest {<br>  <br>  Customer myCustomer = null;  <br>  CustomerRegisterUseCase registerUseCase = null;<br><br>  @Before<br>  public void setUp() {<br>    myCustomer = new Customer();<br>    registerUseCase = new CustomerRegisterUseCase();<br>  }<br><br>  @Test<br>  public void should_validade_customer_data() {<br>    ...<br>    Assert.assertEquals(true, registerUseCase.register(myCustomer));<br>  }<br>}</pre><p><strong>JUnit 5</strong></p><pre>import org.junit.jupiter.api.*;<br>import org.junit.jupiter.api.extension.ExtendWith;<br><br>@ExtendWith(MockitoExtension.class)<br>class MyTest {<br>  <br>  Customer myCustomer = null;  <br>  CustomerRegisterUseCase registerUseCase = null;<br><br>  @BeforeEach<br>  public void setUp() {<br>    myCustomer = new Customer();<br>    registerUseCase = new CustomerRegisterUseCase();<br>  }<br><br>  @Test<br>  public void should_validade_customer_data() {<br>    ...<br>    Assertions.assertEquals(true, registerUseCase.register(myCustomer));<br>  }<br>}</pre><h4>2.2. DisplayName</h4><p>Ok, moving forward with new features of JUnit 5. Let’s say I want to have a better name for my test method, to identify it better when running the tests using an IDE. For that I may use <a href="http://twitter.com/DisplayName">@DisplayName</a>:</p><pre>@Test<br>@DisplayName(&quot;Should register a new customer with success&quot;)<br>public void register_success() throws InvalidValueException {<br>    ...<br>}</pre><p>My test output should be the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/556/1*PXf2I3ucv1Nt7QDSN98bNg.png" /></figure><h4>2.3. ParameterizedTest</h4><p>Since JUnit version 5.7 we can take advantage of the facilities of the Parameterized Tests. And why not save time and lines of code using this feature?</p><p>A parametrized test is a manner to run a test several times with different values.</p><p>According to the <a href="https://junit.org/junit5/docs/current/api/org.junit.jupiter.params/org/junit/jupiter/params/ParameterizedTest.html">documentation</a>:</p><blockquote>@ParameterizedTest is used to signal that the annotated method is a <em>parameterized test</em> method.</blockquote><p>And it works in conjunction with another annotation:</p><blockquote>@ParameterizedTest methods must specify at least one <a href="https://junit.org/junit5/docs/current/api/org.junit.jupiter.params/org/junit/jupiter/params/provider/ArgumentsProvider.html">ArgumentsProvider</a> via <a href="https://junit.org/junit5/docs/current/api/org.junit.jupiter.params/org/junit/jupiter/params/provider/ArgumentsSource.html">@ArgumentsSource</a> or a corresponding composed annotation (e.g., @ValueSource, @CsvSource, etc.). The provider is responsible for providing a <a href="https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/stream/Stream.html">Stream</a> of <a href="https://junit.org/junit5/docs/current/api/org.junit.jupiter.params/org/junit/jupiter/params/provider/Arguments.html">Arguments</a> that will be used to invoke the parameterized test method.</blockquote><p>So, basically, we mark in the test method that it will receive parameters to execute, and these parameters will come from other annotations, such as @ValueSourceor @CsvSource .</p><p>To start using the @ParameterizedTest you should first add the following dependency:</p><pre>&lt;dependency&gt;<br>  &lt;groupId&gt;org.junit.jupiter&lt;/groupId&gt;<br>  &lt;artifactId&gt;junit-jupiter-params&lt;/artifactId&gt;<br>  &lt;version&gt;${junit.jupiter.version}&lt;/version&gt;<br>  &lt;scope&gt;test&lt;/scope&gt;<br>&lt;/dependency&gt;</pre><p>Considering the class CustomerRegister , where there is the use case method to register a new Customer, and another method to validate if the Customer CPF is real.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c9e80b0a58f8594cfcd706b00e1b7aeb/href">https://medium.com/media/c9e80b0a58f8594cfcd706b00e1b7aeb/href</a></iframe><p>The junit-jupiter-param library brings us some options for using parameterized tests, which are:</p><h4>ValueSource</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a7c22de25109225dfdbae9c72a513ede/href">https://medium.com/media/a7c22de25109225dfdbae9c72a513ede/href</a></iframe><h4>CsvSource</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c0d3e4836efdd988e41e94f6aa2c21b9/href">https://medium.com/media/c0d3e4836efdd988e41e94f6aa2c21b9/href</a></iframe><h4>CsvFileSource</h4><p>To use this feature, I should create a csv file to store my tests cases, something like that:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/515/1*VaNqIEfkoL7aqI8ILRzlYA.png" /></figure><p>And my test should be something like that:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c2ac45e86d34e827dd8c4583476d91e9/href">https://medium.com/media/c2ac45e86d34e827dd8c4583476d91e9/href</a></iframe><h3>Conclusion</h3><p>These are some of the new features you can use, exists more than that, but I hope that would be the first step for you to start using JUnit 5.</p><p>Keeping your JUnit up to date will speed up the creation of your tests, and also maintain compatibility with the latest versions of Java.</p><p>I hope you’ve learned something, but don’t stop there. Go ahead, create more tests, and increase the quality of your software.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=797e0df4c357" width="1" height="1" alt=""><hr><p><a href="https://medium.com/abbeal/first-steps-to-using-junit-5-797e0df4c357">First steps to using JUnit 5</a> was originally published in <a href="https://medium.com/abbeal">abbeal’s tech blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Testing your Java code with Mockito]]></title>
            <link>https://medium.com/abbeal/testing-your-java-code-with-mockito-f38135994d6f?source=rss-7e346e98c1fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/f38135994d6f</guid>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[software-testing]]></category>
            <category><![CDATA[unit-test-framework]]></category>
            <dc:creator><![CDATA[Silas Candiolli]]></dc:creator>
            <pubDate>Wed, 22 Mar 2023 20:10:19 GMT</pubDate>
            <atom:updated>2023-04-04T16:02:39.766Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PO_kEKpk_iWSDpdRjN-ipQ.jpeg" /><figcaption><a href="http://twitter.com/LightFieldStudios">@LightFieldStudios</a></figcaption></figure><p>I’ve been using Mockito for a few years now, and I find it to be a very powerful tool. I see that it would be very complicated to create tests without it. But it wasn’t always easy to use it, not because of Mockito, but because of me. Because test-oriented thinking is difficult at first.</p><p>In a practical way, I want to bring examples of using Mockito in real cases of my day-to-day and show how it can help us to test complex code.</p><h3><strong>What is Mockito?</strong></h3><p>Mockito is a unit testing framework and its main objective is to instantiate classes and control the behavior of methods. This is called a mock. By mocking the dependency of a class, I make the class I’m testing think it’s actually invoking the method, but in fact, it’s not. As the drawing below tries to explain.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/888/1*NOUuvp3-GXyA6fz_dzpDYQ.png" /></figure><h3>Setting up</h3><p>Installing Mockito in your project is very simple, as is its use. Following the how-to of the site is very easy to do.</p><p>After Mockito is in your project’s dependencies, you can annotate your classes and create mocks. And then you have some ways to test your methods, which may vary depending on your implementation.</p><p>For the following examples I used the following libraries:</p><ul><li>Java 11</li><li>Mockito 4.7.0</li><li>JUnit 4.13.2</li></ul><h3>Summary</h3><ul><li>Mock: creates an instance of a class, but mocked. If you call a method it won’t call the real method unless you want to.</li><li>Spy: creates an instance of a class, which you can mock or call the real methods. It is an alternative to InjectMocks when you need to mock the methods of the class being tested.</li><li>InjectMocks: create an instance and inject the necessary dependencies which are annotated with @Mock.</li><li>Verify: verifies the number of times and which parameters are used to access a given method.</li><li>When: After a mock is created, you can direct a return to a method given an input parameter.</li><li>Given: Same purpose as when, but used for BDD. Being part of BDDMockito.</li><li>Before or BeforeEach: They are annotations used to mark a method that must execute before each test of the class. Typically used for default behaviors across all tests. <a href="http://twitter.com/Before">@Before</a> is for JUnit until version 4 and <a href="http://twitter.com/BeforeEach">@BeforeEach</a> is for JUnit 5 or later.</li></ul><h3>Practicing</h3><p>At this point, I want to demonstrate the use of Mock/@Mock. With this method, it is possible to instantiate a class dependent on the class you are testing and mock its methods. This is important for unit testing. Because we can isolate the behavior of a method, that’s why they are called unit tests.</p><p>When we create tests it is possible to see how complex our code was. Generally, if there are many dependencies in a class, it means that it could be broken into more than one. The same goes for methods.</p><p>The division of layers and packages of software exists to reduce coupling and maintain cohesion, making classes and methods have a single responsibility. This makes reading and maintaining the code simpler.</p><h3>1. Mock | When</h3><p>In the example below, I created a mock() of the CustomerRegister class to test the behavior of the validateRealCpf method. Evidently, I will get a positive result, regardless of the value I pass to be validated. This is because I used when().</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/1*Jp8qNEYPXjziXb8zazFs-w.png" /></figure><p>Now, if I call the real method, using Mockito’s thenCallRealMethod(), the test fails. Because the CPF entered is invalid, and my test actually went through the validateRealCpf() method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/1*47FYM77R5u9gnvsONMNxbw.png" /></figure><h3>2. InjectMocks</h3><p>I can use mock() in other slightly more complex contexts, such as to get a positive result from repository.save(), regardless of what it receives as an input parameter. In the example below I used the @InjectMocks, @Mock and @Before annotations:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bMdNJsDI_4qVIOO2eo64Tg.png" /></figure><h3>3. Spy</h3><p>In the following example, I will test using the Spy()/@Spy function, which makes it possible to mock the class being tested. Something you can’t do using just @InjectMocks.</p><p>I mean, you can call the real method of the class using <a href="http://twitter.com/Mock">@Mock</a> annotation and the when .thenCallRealMethod() function. But this way, you will not create a real instance of the class. Like this:</p><pre>when(customerRegister.save()).thenCallRealMethod();</pre><p>But it doesn’t make sense in my case to use <a href="http://twitter.com/Mock">@Mock</a>, because I want to mock a method of the same class I’m testing.</p><p>Let’s see the example below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2je4TXsynmdLemhLN-JfRw.png" /></figure><h3>4. Verify</h3><p>In the example below, I’ll explore some use cases of verify().</p><p>You can check the amount of interaction:</p><pre>verify(customerRegister, times(1)).register(vo);</pre><p>Check when there is no interaction:</p><pre>verifyNoInteractions(repository);</pre><p>Check when there is no interaction other than the ones I already checked, use verifyNoMoreInteractions(), for example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/1*TbkLcJr1pudugdxtQCc9Hw.png" /></figure><h3>Conclusion</h3><p>To conclude, I would like to emphasize the importance of this framework for our daily lives. We all know that testing is necessary, and Mockito is a great tool for that, as being able to isolate behaviors and testing small parts is a great strategy to ensure quality.</p><p>The project used in this article is on <a href="https://github.com/candiolli/articles/tree/main/testando-java-c-mockito">GitHub</a>. Any questions or feedback about the article, I’m at your disposal.</p><h3>References</h3><p><a href="https://site.mockito.org/">Mockito framework site</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f38135994d6f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/abbeal/testing-your-java-code-with-mockito-f38135994d6f">Testing your Java code with Mockito</a> was originally published in <a href="https://medium.com/abbeal">abbeal’s tech blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Testando seu código Java com o Mockito framework]]></title>
            <link>https://medium.com/@candiolli/testando-seu-c%C3%B3digo-java-com-o-mockito-framework-8bea7287460a?source=rss-7e346e98c1fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/8bea7287460a</guid>
            <category><![CDATA[test]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[mockito]]></category>
            <category><![CDATA[junit-5]]></category>
            <dc:creator><![CDATA[Silas Candiolli]]></dc:creator>
            <pubDate>Thu, 12 Nov 2020 16:18:56 GMT</pubDate>
            <atom:updated>2022-09-01T13:01:11.659Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Geliad9bjwlnh2moys_YrA.jpeg" /><figcaption><a href="https://www.engadget.com/2019-07-30-facebook-fact-checker-more-work-is-needed-to-curb-fake-news.html">Engadget</a></figcaption></figure><p>Utilizo o Mockito faz alguns anos, e considero uma ferramenta muito poderosa. Eu vejo que seria muito complicado criar testes sem ele. Mas nem sempre foi facil utiliza-lo, não por causa do Mockito, mas sim por minha causa. Pois <strong>pensar orientado a testes é dificil </strong>no começo.</p><p>De forma prática, quero trazer exemplos de utilização do Mockito em casos reais do meu dia a dia, e mostrar como ele pode nos ajudar a testar codigo complexos.</p><h3>O que é o Mockito?</h3><p>O Mockito é um framework de testes unitários e o seu principal objetivo é instanciar classes e controlar o comportamento dos métodos. Isso é chamado de <em>mock, </em>na tradução livre quer dizer <em>zombar, </em>e talvez seja mesmo o termo que melhor o define. Pois ao <em>mockar</em> a dependencia de uma classe, eu faço com que a classe que estou testando pense estar invocando o metodo realmente, mas de fato não está. Conforme o desenho abaixo tenta explicar.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/882/1*Y5OEPlXdLblECPh3jRjoTw.png" /><figcaption>Fluxo quando chamar o metodo mockado</figcaption></figure><h3>Configurando</h3><p>A instalação do Mockito no seu projeto é muito simples, assim como sua utilização. Seguindo o <em>how to</em> do <a href="https://site.mockito.org/#how">site</a> é bem facil de fazer.</p><p>Após o Mockito estar nas dependencias do seu projeto, ja é possível anotar suas classes e criar <em>mocks. </em>E ai você tem algumas formas de testar seus metodos, que podem variar conforme a sua implementação.</p><p>Para os exemplos a seguir utilizei as seguintes bibliotecas:</p><ul><li>Java 11</li><li>Mockito 4.7.0</li><li>JUnit 4.13.2</li></ul><h3>Resumo</h3><ul><li>Mock: cria uma instancia de uma classe, porém Mockada. Se você chamar um metodo ele não irá chamar o metodo real, a não ser que você queira.</li><li>Spy: cria uma instancia de uma classe, que você pode mockar ou chamar os metodos reais. É uma alternativa ao <em>InjectMocks, </em>quando é preciso mockar metodos da propria classe que esta sendo testada.</li><li>InjectMocks: criar uma intancia e injeta as dependências necessárias que estão anotadas com <em>@Mock.</em></li><li>Verify: verifica a quantidade de vezes e quais parametros utilizados para acessar um determinado metodo.</li><li>When: Após um mock ser criado, você pode direcionar um retorno para um metodo dado um paremetro de entrada.</li><li>Given: Mesmo propósito que o <em>when</em>, porém é utilizado para BDD. Fazendo parte do BDDMockito.</li></ul><h3>Praticando</h3><p>Nesse ponto quero desmostrar a utilização do <em>Mock/@Mock. </em>Com esse metodo, é possível instanciar uma classe dependente da classe que voce esta testando, e mockar seus metodos. Isso é importante para, <strong>testar a unidade. </strong>Pois conseguimos isolar o comportamento de um metodo, por isso são chamados de testes unitários.</p><p>Quando criamos testes é possível perceber o quão complexo ficou nosso código. <strong>Geralmente, se existes muitas dependencias em uma classe, significa que ela poderia ser quebrada em mais de uma. O mesmo vale para os metodos.</strong></p><p>A divisão de camadas e pacotes de um software existe para diminuir o acoplamento e manter a coesão, fazendo com que as classes e metodos tenham uma unica responsabilidade. Isso torna a leitura e manutenção do código mais simples.</p><p><strong>1. Mock | When</strong></p><p>Nesse exemplo abaixo, criei um <em>mock() </em>da classe <em>CustomerRegister </em>para testar o comportamento do metodo <em>validateRealCpf </em>. Evidentemente, eu terei um resultado positivo, independente do valor que eu passar para ser validado. Isso ocorre porque eu utilizei o <em>when().</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4dde3ef8c71e7e30c12db260a30470da/href">https://medium.com/media/4dde3ef8c71e7e30c12db260a30470da/href</a></iframe><p>Agora, se eu chamar o metodo real, utilizando o <em>thenCallRealMethod() </em>do Mockito, o teste falha. Porque o CPF informado é inválido, e o meu teste passou pelo metodo <em>validateRealCpf()</em> de fato.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/70526043456a72e2408c32636410f09c/href">https://medium.com/media/70526043456a72e2408c32636410f09c/href</a></iframe><p><strong>2. InjectMocks</strong></p><p>Eu posso usar o <em>mock()</em> em outros contextos pouco mais complexos, como para obter um resultado positivo do <em>repository.save(), </em>independente do que este receba como parametro de entrada. No exemplo abaixo utilizei as anotações <em>@InjectMock</em>s, <em>@Mock</em> e <em>@BeforeEach</em> conforme codigo abaixo:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/44c0da242db5fe7d824d51d84549112b/href">https://medium.com/media/44c0da242db5fe7d824d51d84549112b/href</a></iframe><p><strong>3. Spy</strong></p><p>No exemplo seguinte, farei um teste utilizando a função S<em>py()/@Spy, </em>que possibilita <em>mockar</em> a classe que está sendo testada. Algo que você não consegue fazer utilizando somente o <em>@InjectMocks. </em>Vejamos o exemplo abaixo:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bd6f750432671690322bc54eda9aa2b4/href">https://medium.com/media/bd6f750432671690322bc54eda9aa2b4/href</a></iframe><p><strong>3. Verify</strong></p><p>No exemplo abaixo, vou explorar alguns casos de uso do <em>verify().</em></p><p>É possível fazer verificar por quantidade de interação:</p><pre><em>verify</em>(customerRegister, <em>times</em>(1)).register(vo);</pre><p>Verificar quando não houver interação:</p><pre><em>verifyNoInteractions</em>(repository);</pre><p>Verificar quando não houver outras interações além das que eu ja verifiquei, utilizar o <em>verifyNoMoreInteractions(), </em>por exemplo:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4474675312ecdccbab2b2d047998a807/href">https://medium.com/media/4474675312ecdccbab2b2d047998a807/href</a></iframe><h3>Conclusão</h3><p>Para concluir, eu gostaria de ressaltar a importancia desse framework para o nosso dia a dia. Todos sabemos que é necessário testar, e o Mockito é uma ótima ferramenta para isso, pois é a possibilidade de isolar comportamentos e testar pequenas partes é uma grande estratégia para garantir a qualidade.</p><p>O projeto utilizado nesse artigo esta no <a href="https://github.com/candiolli/articles/tree/main/testando-java-c-mockito">GitHub</a>. Qualquer dúvida e feedback sobre o artigo, estou a disposição.</p><h3>Referências</h3><p><a href="https://site.mockito.org/">Mockito framework site</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8bea7287460a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Começando com Spring Security]]></title>
            <link>https://medium.com/@candiolli/come%C3%A7ando-com-spring-security-86a3caec8c40?source=rss-7e346e98c1fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/86a3caec8c40</guid>
            <category><![CDATA[spring-security]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[security]]></category>
            <dc:creator><![CDATA[Silas Candiolli]]></dc:creator>
            <pubDate>Mon, 13 Jul 2020 16:18:29 GMT</pubDate>
            <atom:updated>2020-07-24T14:25:00.457Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*1-13QxXfUE1mdrK_MfqonQ.png" /><figcaption>Figura 1 — Spring Security <a href="https://spring.io/projects">https://spring.io/projects</a></figcaption></figure><p>O Spring Security, existente desde 2003, é um projeto muito conhecido e bastante utilizado em aplicações com Spring. Espero com esse artigo esclarecer algumas questões e talvez trazer novidades para alguns. Mas meu principal objetivo é responder duas perguntas…</p><p><strong>Do que o Spring Security nos protege? O que ele faz além de proteger?</strong></p><h3>Introdução</h3><p>De fato, o Spring Security é uma biblioteca que fornece proteção, mas também autenticação, autorização e armazenamento de senhas. Sendo que, para autenticação, ele trabalha com vários protocolos. Para armazenar senhas em um banco de dados, ele tem opção de vários <em>encoders</em>. Também é possível utilizá-lo em projetos com Java EE, Spring <a href="https://spring.io/reactive">Webflux</a>, e Kotlin. Além disso, ele protege de ataques mais comuns como CSRF ou XSS.</p><p>Verificando atentamente a documentação do projeto Spring Security, é possível constatar que ele fornece um kit completo para proteger uma aplicação, bem como um kit flexível no qual pode-se selecionar e “plugar” os módulos que desejar.</p><p>Para facilitar o entendimento, foi criado um <a href="https://github.com/candiolli/spring-security/tree/master/demo-basic-auth">projeto de demonstração</a>, utilizando Basic Auth para autenticação, armazenamento de senhas em banco de dados e autorização.</p><h3>1. Configuração</h3><p>Para habilitar o Spring Security em um projeto é necessário, além das dependências, criar a classe de configuração. É nessa classe que é definido quais protocolos de autenticação, autorização, proteção e armazanamento. Essas configurações são melhor detalhadas no decorrer do artigo.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/456a29306c8516653dd24517a38928ff/href">https://medium.com/media/456a29306c8516653dd24517a38928ff/href</a></iframe><h4><strong>Autenticação</strong></h4><p>A autenticação é a porta de entrada da aplicação e essa porta precisa estar protegida, tanto em uma aplicação externa quanto interna. Para isso, o Spring Security disponibiliza alguns mecanismos que podemos utilizar na nossa aplicação. São eles:</p><ul><li><a href="https://docs.spring.io/spring-security/site/docs/5.3.2.BUILD-SNAPSHOT/reference/html5/#servlet-authentication-unpwd">Username and Password</a>: quando se utiliza usuário e senha para logar. Para esse mecanismos podemos utilizar três formas: <em>Form login</em>, <em>Basic Authentication</em> e <em>Digest Authentication</em>.</li><li><a href="https://docs.spring.io/spring-security/site/docs/5.3.2.BUILD-SNAPSHOT/reference/html5/#oauth2login">OAuth2</a>: quando se utiliza <em>OpenID connect,</em> é possível se autenticar em uma aplicação usando uma conta e servidor externo, como github.</li><li>SAML2: é um padrão que surgiu antes do OAuth e que serve para compartilhamento de informações de login, podendo também atender o padrão <em>Single Sign On</em> (SSO).</li><li><a href="https://docs.spring.io/spring-security/site/docs/5.3.2.BUILD-SNAPSHOT/reference/html5/#servlet-rememberme">Remember Me</a>: mecanismo utilizado para salvar a sessão do usuário logado na aplicação.</li><li>Outros: <a href="https://docs.spring.io/spring-security/site/docs/5.3.2.BUILD-SNAPSHOT/reference/html5/#servlet-jaas"><em>JAAS Authentication</em></a><em>, </em><a href="https://docs.spring.io/spring-security/site/docs/5.3.2.BUILD-SNAPSHOT/reference/html5/#servlet-cas"><em>Central Authentication Server (CAS)</em></a><em>, </em><a href="https://docs.spring.io/spring-security/site/docs/5.3.2.BUILD-SNAPSHOT/reference/html5/#servlet-openid"><em>OpenID</em></a><em>, </em><a href="https://docs.spring.io/spring-security/site/docs/5.3.2.BUILD-SNAPSHOT/reference/html5/#servlet-preauth"><em>Pre-Authentication Scenarios</em></a><em> </em>e<em> </em><a href="https://docs.spring.io/spring-security/site/docs/5.3.2.BUILD-SNAPSHOT/reference/html5/#servlet-x509"><em>X509 Authentication</em></a><em>.</em></li></ul><p><strong>No projeto de demonstração desse artigo está sendo utilizado <em>Basic Auth. É </em>possível ver no trecho de código abaixo que foi extraído da linha 11 da classe </strong><a href="https://github.com/candiolli/spring-security/blob/master/demo-basic-auth/src/main/java/com/example/springsecurity/config/WebSecurityConfig.java"><strong><em>SecurityConfig.java</em>.</strong></a></p><pre>http <br>   .httpBasic()</pre><h4>Autorização</h4><p>Para autorização, o Spring Security se baseia nas <em>Authorities </em>do usuário que se autentica na aplicação. É possível usar credencias registradas i<em>nMemory (usuário e senha definido no arquivo de propriedades do projeto, sem acesso externo) </em>para testes ou implementar a estrutura de <em>UserDetailService (usuários, grupos e permissões salvas na base de dados). </em>Porém, para cada endpoint, é preciso informar quais ROLEs poderão acessá-lo; do contrário, todos poderão.</p><p>As <em>Authorities </em>representam as autoridades que foram concedidas ao<em> principal (</em>usuário logado na aplicação). Elas são lidas em forma de uma lista de objetos <em>GrantedAuthority, </em>que são inseridos no objeto <em>AuthenticationManager </em>do <em>SecurityContext </em>e são lidos posteriormente pelo <em>AccessDecisionManager.</em></p><p>Existem outras funcionalidades legais, como <em>Pre-invocatio</em>n ou <em>After-invocation</em> para tratar as <em>Authorities</em>, ou trabalhar com <em>Hierarchical Roles</em>, onde se define uma hierarquia para as roles. Dessa forma, o usuário que tem a role ADMIN acessa também as informações da role USER, sem precisar estar vinculado a ela.</p><h4>Proteção</h4><p>O Spring Security também fornece proteção contra vulnerabilidades comuns em aplicações web, que podem ser exploradas de diferentes formas. São elas: o <a href="https://en.wikipedia.org/wiki/Cross-site_request_forgery"><em>Cross Site Request Forgery</em> (CSRF)</a>, <a href="https://owasp.org/www-project-secure-headers/"><em>Security HTTP Response Headers</em></a>, <a href="https://docs.spring.io/spring-security/site/docs/5.3.2.BUILD-SNAPSHOT/reference/html5/#http">HTTP</a> e <a href="https://docs.spring.io/spring-security/site/docs/5.3.2.BUILD-SNAPSHOT/reference/html5/#servlet-httpfirewall">HTTP <em>Firewall</em></a>.</p><p>Não é o objetivo desse artigo entrar em detalhes sobre cada vulnerabilidade, pois é um assunto mais extenso. Porém, foram adicionadas referências para quem tiver interesse em estender a pesquisa.</p><h4>Armazenamento de senhas</h4><p>Outra funcionalidade legal do Spring Security é a <a href="https://docs.spring.io/spring-security/site/docs/5.3.2.BUILD-SNAPSHOT/reference/html5/#appendix-schema">estrutura para armazenamento de senhas</a>. É possível salvar usuários, senhas e grupos no banco, e encriptar as senhas com sistemas de criptografias bem avançados como <a href="https://docs.spring.io/spring-security/site/docs/5.3.2.BUILD-SNAPSHOT/reference/html5/#authentication-password-storage-bcrypt">bcrypt</a>, <a href="https://docs.spring.io/spring-security/site/docs/5.3.2.BUILD-SNAPSHOT/reference/html5/#authentication-password-storage-pbkdf2">PBKDF2</a>, <a href="https://docs.spring.io/spring-security/site/docs/5.3.2.BUILD-SNAPSHOT/reference/html5/#authentication-password-storage-scrypt">scrypt</a> ou <a href="https://docs.spring.io/spring-security/site/docs/5.3.2.BUILD-SNAPSHOT/reference/html5/#authentication-password-storage-argon2">argon2</a>.</p><p>Para isso, é preciso implementar o <em>UserDetailsService, </em>que vai fornecer métodos para consultar os usuários na base de dados. Conforme a classe <a href="https://github.com/candiolli/spring-security/blob/master/demo-basic-auth-db/src/main/java/com/example/springsecurity/security/MyUserDetailsService.java"><em>MyUserDetailsService.java</em></a> abaixo:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8f027a01df4cb1855b1569adcecf82cc/href">https://medium.com/media/8f027a01df4cb1855b1569adcecf82cc/href</a></iframe><p>Após criar a classe <a href="https://github.com/candiolli/spring-security/blob/master/demo-basic-auth-db/src/main/java/com/example/springsecurity/security/MyUserDetailsService.java"><em>MyUserDetailsService.java</em></a><em>,</em> é preciso informar na configuração que será utilizado um <em>userDetailsService, </em>conforme linha 37 da classe <a href="https://github.com/candiolli/spring-security/blob/master/demo-basic-auth-db/src/main/java/com/example/springsecurity/config/SecurityConfig.java"><em>SecurityConfig.java</em></a>.</p><pre>builder<br>  .userDetailsService(userDetailsService)<br>  .passwordEncoder(new BCryptPasswordEncoder())</pre><p>Lembrando que é preciso criar as classes de repositórios e domínios. Porém, a estrutura de banco de dados pode ser criada e alimentada automaticamente, conforme o projeto de demonstração está fazendo. Isso ocorre porque, no arquivo <a href="https://github.com/candiolli/spring-security/blob/master/demo-basic-auth-db/src/main/resources/application.yml">application.yml</a>, linha 12, existe a configuração <em>ddl-auto: create-drop.</em></p><pre>jpa:<br>  hibernate:<br>    ddl-auto: create-drop</pre><p>Para o projeto alimentar as tabelas do banco de dados, é necessário criar o arquivo <a href="https://github.com/candiolli/spring-security/blob/master/demo-basic-auth-db/src/main/resources/import.sql"><em>/resources/import.sql</em></a><em>, </em>e nele por o script necessário.</p><h3>2. Execução</h3><p>Agora que está entendido o que cada parte do código esta fazendo, é possível executar o projeto e ver o resultado. O projeto de demonstração de encontra no <a href="https://github.com/candiolli/spring-security/tree/master/demo-basic-auth-db">GitHub</a>, e pode ser clonado e executado localmente.</p><p>Na raíz do projeto, execute os comandos:</p><pre>$ ./gradlew build<br>$ ./gradlw bootRun</pre><p>Assim, sua aplicação deve estar disponível na porta 8080, mais ou menos como mostra o log abaixo:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bl29M_E-o-IpDHWRw3A4mA.png" /><figcaption>Figura 2— Log exibido ao rodar o projeto</figcaption></figure><p>Para testar, execute o seguinte comando em algum terminal bash. Antes, é preciso gerar o <em>Authorization </em>baseado no usuário e senha que podem acessar os <em>endpoints. </em>Para gerar o <em>Authorization</em>, existem opções na internet como o <a href="https://www.blitter.se/utils/basic-authentication-header-generator/">blitter.se</a> (você pode utilizar usuário silas, senha 123).</p><pre>curl --location --request GET &#39;localhost:8080/books&#39; \<br>--header &#39;Authorization: Basic c2lsYXM6MTIz&#39; \<br>--header &#39;Cookie: JSESSIONID=56AD4F472FF75F792FD0F2415ED82A6D&#39;</pre><p>O resultado que você deve receber será como o abaixo:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/318/1*4B6od5_awa6FqpaFZqT9sw.png" /><figcaption>Figura 3— Resposta retornada do serviço /books</figcaption></figure><h3>3. Considerações finais</h3><p>Espero que esse artigo te ajude a entender o <em>Spring Security, </em>e dê uma perspectiva de onde ele pode chegar. O objetivo era introduzir o assunto e, assim, ter uma base para testar recursos mais avançados.</p><p>Segurança é algo essencial para todas as aplicações, e baseado nos estudos realizados nesse artigo, ficou evidente que o <em>Spring Security</em> é uma biblioteca que pode suprir essa necessidade.</p><h3>Referências</h3><p><a href="https://docs.spring.io/spring-security/site/docs/5.3.2.BUILD-SNAPSHOT/reference/html5/#servlet-applications">Spring Security Reference</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=86a3caec8c40" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Criando uma API com Spring Data REST e auditando com Hibernate Envers]]></title>
            <link>https://medium.com/@candiolli/criando-uma-api-com-spring-data-rest-e-auditando-com-hibernate-envers-ad6d8f759f4c?source=rss-7e346e98c1fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/ad6d8f759f4c</guid>
            <category><![CDATA[hibernate]]></category>
            <category><![CDATA[rest]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[auditing]]></category>
            <dc:creator><![CDATA[Silas Candiolli]]></dc:creator>
            <pubDate>Wed, 27 Mar 2019 17:14:54 GMT</pubDate>
            <atom:updated>2023-06-30T17:14:57.769Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*LXRfVdPeqTgnul2w7yJK3Q.jpeg" /></figure><p>À medida que a linguagem de programação Java vai evoluindo a quantidade de código e configuração que escrevemos tende a diminuir juntamente. Antes havia muito XML para configurações do projeto, hoje em dia em projetos mais modernos isso é raro. Se você utiliza Spring é possível diminuir mais ainda porque muitas coisas já são transparentes para nós desenvolvedores, e por convenção ele se entende facilitando muito nossas vidas.</p><p>Agora pense na possibilidade de você definir suas entidade e repositórios baseado no seu modelo de dados, e magicamente seus métodos GET, POST, PUT, DELETE serem criados automaticamente. E poder auditar suas tabelas de forma simples, anotando suas entidades. Parece ótimo não é mesmo?!</p><p>Neste artigo pretendo apresentar essas duas bibliotecas para sabermos quando, como e porque utilizá-las no nosso dia-a-dia. Também espero que o projeto que utilizaremos nesse artigo possa servir como um ponto de partida para os que estão iniciando com Java ou Spring Boot, que ainda não conhecem bem a sua arquitetura mas que querem subir um serviço e ver as coisas funcionando.</p><p>Nesse projeto utilizaremos as seguintes bibliotecas:</p><ul><li><a href="https://spring.io/projects/spring-boot">Spring Boot</a></li><li><a href="https://spring.io/projects/spring-data">Spring Data</a></li><li><a href="https://spring.io/projects/spring-data-rest"><strong>Spring Data Rest</strong></a></li><li><a href="https://hibernate.org/orm/envers/"><strong>Hibernate Envers</strong></a></li><li><a href="https://projectlombok.org/">Lombok</a></li></ul><p>Eu adicionei o link para a página de cada biblioteca, porém irei focar em explicar somente as duas principais deste artigo.</p><p><strong>Hibernate Envers</strong></p><p>O Envers é um módulo que faz parte do projeto Hibernate ORM (Mapeamento objeto relacional), e ele provê uma maneira fácil de fazer auditoria e versionamento de suas classes entidades.</p><p><strong>Spring Data REST</strong></p><p>O Spring Data REST faz parte do projeto guarda-chuva Spring Data, e facilita a criação de serviços da Web REST baseados em hipermídia sobre os repositórios Spring Data;</p><p>Ele se baseia nos repositórios do Spring Data, analisa o modelo de domínio de seu aplicativo e expõe recursos HTTP orientados por hipermídia para agregados contidos no modelo.</p><p><strong>O projeto</strong></p><p>Para trabalharmos com algo mais real, criei um projeto que visa organizar uma biblioteca musical, onde poderei criar músicas, álbuns e produtores musicais.</p><p>Para o nosso projeto de fato funcionar, ainda precisaremos de outras dependências que não veem ao caso explicar. Partindo do pressuposto que você já conhece o <a href="https://maven.apache.org/">Maven</a>, é possível baixar o projeto e ver o pom.xml completo <a href="https://github.com/candiolli/music-library">aqui</a>.</p><p>A estrutura do projeto ficará desta forma:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/0*rQdwnkQ5MT7FcwAF" /></figure><p>É possível ver que temos classes e arquivos de configuração criados. O que está dentro do pacote ‘<strong><em>br.com.candiolli.musiclibrary</em></strong>’ são classes Java. No pacote <strong><em>‘resources’ </em></strong>são configurações, e na raiz do projeto o arquivo pom.xml é para as dependências do maven, ou seja, bibliotecas que vamos utilizar nesse projeto. Os outros arquivos podem ser ignorados no momento.</p><p><strong>Hibernate Envers funcionando</strong></p><p>Para exemplificar, falarei da entidade Music.java que representa uma tabela do banco de dados e que está anotada para ser auditada. Sabemos isso por causa da anotação @Audited e @AuditTable.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/42cd57ee885ef5aa4dc2864a7a99228b/href">https://medium.com/media/42cd57ee885ef5aa4dc2864a7a99228b/href</a></iframe><p>Dessa forma, três tabelas serão criadas no banco de dados: <strong><em>‘music’</em></strong>, <strong><em>‘music_audit’ </em></strong>e <strong><em>‘revinfo’</em></strong>. A <strong><em>‘revinfo’ </em></strong>é para versionar todas as alterações que as tabelas auditadas sofrem, e o que muda de fato fica registrado na tabela <strong><em>‘music_audit’</em></strong>. Conforme imagem abaixo:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/391/0*mjENdBEEwcNa-eqt" /></figure><p>Isso pode se dar automaticamente ou previamente, dependendo da estratégia do hibernate. No meu caso, que está create-drop, será recriada toda vez que eu executar meu micro serviço.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fba7ac270bf6cb11c32b55f0d0f3df28/href">https://medium.com/media/fba7ac270bf6cb11c32b55f0d0f3df28/href</a></iframe><p>Sabendo disso, podemos ver abaixo e entender as linhas das nossas tabelas. Temos uma música adicionada que depois sofreu uma alteração do seu nome, e isso tudo ficou logado. Lembrando que a tabela <strong><em>‘revinfo’ </em></strong>versiona todas as tabelas <strong><em>‘_audit’</em></strong>, por isso estamos vendo alguns rev que não estão na nossa tabela <strong><em>‘music_audit’</em></strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/454/0*-wZx2VHM0lAdIcov" /></figure><p><strong>Spring Data REST funcionando</strong></p><p>Como vimos anteriormente, a responsabilidade dessa biblioteca é descobrir nossas entidades e repositórios para expor nossos métodos de consumo REST.</p><p>Por exemplo, vamos ver a entidade Album.java e seu respectivo repositório:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1123385732ebd9515ec26b6b872686cf/href">https://medium.com/media/1123385732ebd9515ec26b6b872686cf/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/18a8aa68df2ffa73310d02e1cbaeb863/href">https://medium.com/media/18a8aa68df2ffa73310d02e1cbaeb863/href</a></iframe><p>As anotações que o Spring Data REST leva em consideração são @Entity e @Table. Assim ele sabe que essa classe é uma entidade que representa uma tabela do banco. Também é necessário ter um repositório criado para essa entidade, sem necessidade obrigatória de ser anotado.</p><p>Agora, vamos construir o projeto e depois executar. É preciso abrir o console na raiz do projeto:</p><pre>$ mvn clean install<br>$ java -jar target/music-library-1.0-SNAPSHOT.jar</pre><p>Você também pode executar com o próprio maven, dessa forma:</p><pre>$ mvn spring-boot:run</pre><p>E assim, você poderá acessar seu serviço com a url <a href="http://localhost:8080/api">http://localhost:8080/api</a></p><p>Se tudo der certo, você deverá visualizar a resposta com os seus links disponíveis:</p><pre>{<br>  &quot;_links&quot; : {<br>    &quot;albums&quot; : {<br>      &quot;href&quot; : &quot;http://localhost:8080/api/albums{?page,size,sort}&quot;,<br>      &quot;templated&quot; : true<br>    },<br>    &quot;productors&quot; : {<br>      &quot;href&quot; : &quot;http://localhost:8080/api/album-productor{?page,size,sort}&quot;,<br>      &quot;templated&quot; : true<br>    },<br>    &quot;musics&quot; : {<br>      &quot;href&quot; : &quot;http://localhost:8080/api/musics{?page,size,sort}&quot;,<br>      &quot;templated&quot; : true<br>    },<br>    &quot;profile&quot; : {<br>      &quot;href&quot; : &quot;http://localhost:8080/api/profile&quot;<br>    }<br>  }<br>}</pre><p>Agora é possível entrar em cada ramificação, para criar, alterar, buscar ou excluir registros. Por exemplo, se você executar os request’s abaixo com cUrl, você irá adicionar um novo produtor e um novo album.</p><pre>curl -X POST \<br>http://localhost:8080/api/album-productor \<br>-H &#39;Content-Type: application/json&#39; \<br>-H &#39;Postman-Token: e180e099-ac14-4e7d-9042-d5ed1ac45f8f&#39; \<br>-H &#39;cache-control: no-cache&#39; \<br>-d &#39;{<br>     &quot;name&quot;:&quot;Gerge Martin&quot;<br>}&#39;</pre><pre>curl -X POST \<br>http://localhost:8080/api/albums \<br>-H &#39;Content-Type: application/json&#39; \<br>-H &#39;Postman-Token: d1613266-86a1-46d9-9927-9c816414682a&#39; \<br>-H &#39;cache-control: no-cache&#39; \<br>-d &#39;{<br>     &quot;title&quot; :&quot;Help!&quot;,<br>     &quot;author&quot;:&quot;The Beatles&quot;,<br>     &quot;dateCreate&quot;:&quot;01/01/1965 00:00:00&quot;,<br>     &quot;productor&quot;:{<br>        &quot;id&quot;:1<br>     }<br>}&#39;</pre><p>Outro exemplo, para buscar todos álbuns que temos é só executar o seguinte:</p><pre>curl -X GET \<br>http://localhost:8080/api/albums \<br>-H &#39;Content-Type: application/json&#39; \<br>-H &#39;Postman-Token: 220818fe-1ea1-42ec-9c23-97c9cdfac0a9&#39; \<br>-H &#39;cache-control: no-cache&#39;</pre><p>Gostaria de agradecer a você por fazer a leitura e espero ter ajudado a esclarecer o funcionamento dessas bibliotecas. Se puderem me mandem o feedback e dúvidas, eu agradeço muito.</p><p>Forte abraço, até a próxima.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ad6d8f759f4c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>