<?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 Fede Lopez on Medium]]></title>
        <description><![CDATA[Stories by Fede Lopez on Medium]]></description>
        <link>https://medium.com/@fede.lopez?source=rss-4be7a9d6b0a5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*fpa0VXrLPcSPCHqDDle5vg.jpeg</url>
            <title>Stories by Fede Lopez on Medium</title>
            <link>https://medium.com/@fede.lopez?source=rss-4be7a9d6b0a5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 13:40:47 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@fede.lopez/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[How serious is your organization about Digital Transformation?]]></title>
            <link>https://medium.com/@fede.lopez/how-serious-is-your-organisation-about-digital-transformation-9de10743f879?source=rss-4be7a9d6b0a5------2</link>
            <guid isPermaLink="false">https://medium.com/p/9de10743f879</guid>
            <category><![CDATA[lean-software-development]]></category>
            <category><![CDATA[agile]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[leadership]]></category>
            <category><![CDATA[digital-transformation]]></category>
            <dc:creator><![CDATA[Fede Lopez]]></dc:creator>
            <pubDate>Tue, 28 Aug 2018 14:06:46 GMT</pubDate>
            <atom:updated>2018-08-29T06:59:39.032Z</atom:updated>
            <content:encoded><![CDATA[<p>Ever since I was a kid I have been a vivid reader of the french comic book <em>The Adventures of Asterix</em>. In one of the books (<em>The Twelve Tasks of Asterix</em>), Julius Caesar, puzzled about the supernatural strength of Asterix, challenges him to complete 12 impossible tasks to confirm whether he is a god or an impostor. In one of the tasks Asterix must obtain a permit from the most bureaucratic building in the Roman Empire. Each unhelpful employee from the building directs all their clients to other similarly unhelpful people elsewhere in the building, making the task of getting the permit impossible.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/411/1*6FCq-Sayc9RmoJU28hAxVQ.png" /><figcaption>Julius Caesar, the archenemy of Asterix</figcaption></figure><p>Have you ever felt like Asterix whenever you try to fight against the sea of red tape that slowly drowns your organization? How easily can you deploy workloads in production in a quick and secure way?</p><p>Mary Poppendieck once asked the $64,000 question: How long would it take your organization to deploy a change that involves just one single line of code?</p><p>Not many CIOs know the answer to it and yet releasing often to production means being able to make more experiments which its results may turn into your next competitive advantage.</p><p>Today tech giants in the software industry are well known to execute rapid release at massive scale. Facebook releases new updates every few hours, rolled out to 100 percent of their production systems. Netflix deploys 100 times a day thanks to their own in-built PaaS that allows each team to deploy their software whenever they want. Amazon takes it to the extreme and handles production releases every second.</p><p>What do these companies learn from all the feedback they gather in a single day?</p><p>To achieve such scale and speed in your release cycle you must operate with zero red tape and no manual processes. It’s not just about modernizing technology stacks or launching press releases about your digital transformation initiatives. It’s about embracing Agile and Lean, empower your teams and have the courage to not going back to the old waterfall habits.</p><p>I see every day organisations full of talented individuals not being able to deploy often to production because the amount of red tape involved in deploying workloads makes the task as difficult as the ones performed by our hero Asterix.</p><p>Getting approval from different architecture committees, filling forms, onboarding the API endpoints to the load balancer, providing the perfect Swagger documentation... After getting through all the hoops and deploying one microservice to production, the team just runs out of gas. Soon, this microservice will turn into a monolith because it is just easier to keep adding code to it rather than embarking again into the process of beating the red tape to onboard subsequent microservices.</p><p>Next time before you ask yourself the $64,000 question do the following: go to the field and talk to the teams. Pair with them for a couple of days and see what are their struggles. Very quickly you will find out the problems they face every day and you will be able to truly start with them the Digital Transformation journey your organisation is waiting for.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9de10743f879" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Thank you Kotlin for re-animating operator overloading]]></title>
            <link>https://medium.com/@fede.lopez/thank-you-kotlin-for-re-animating-operator-overloading-ba98ab0cc8c?source=rss-4be7a9d6b0a5------2</link>
            <guid isPermaLink="false">https://medium.com/p/ba98ab0cc8c</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Fede Lopez]]></dc:creator>
            <pubDate>Fri, 02 Mar 2018 13:51:45 GMT</pubDate>
            <atom:updated>2018-03-02T13:51:45.876Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*oVK11y-rrDC1JdimkbA8bA.jpeg" /></figure><p>Remember the film Re-Animator? in this classic 80s movie a distressed scientist discovers a way to bring dead bodies back to life again.</p><p>I have been writing programs in Java for many years, and quite often I wished this scientist to use his solution on Java and bring operator overloading from the dead into the language, as C++, Scala and other languages have.</p><p>Fortunately Kotlin provides operator overloading provided that you follow some conventions. But first of all, what is operator overloading?</p><p>Operator overloading enables developers to write code using a higher level of abstraction. Suddenly you can use operators such as <strong>+</strong> to sum not only numbers but more complex types like Point, String or List. This technique if used wisely lets you seamlessly integrate operators to your types and reason in domain terms.</p><p>Imagine that you have a class that represents vectors, in terms of magnitude and position.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/1*3H1kI8QDuxm0l92Or_UvAg.png" /></figure><p>If you want to sum two vector instances, the classic approach in OO languages without operator overloading is to provide a sum operation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yFyQu2zZoFyGVS_1Q7yo8g.png" /></figure><p>And you would use this function as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5-09HD50vfydHLWYuTqaFg.png" /></figure><p>However, Kotlin allows you to overload a list of valid operators by adding the keyword modifier <strong>operator</strong> to the function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1016/1*h4AVMTRe5dElZu5mA6HRxQ.png" /></figure><p>Now you can express your code closer to the domain you are working on and sum vectors using the + symbol:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5_L_iGxncvyojaNzZDKRtQ.png" /></figure><p>There are a number of conventions you should be aware of when overloading operators in Kotlin.</p><p>For instance calling the function <strong>sum</strong> and adding the <strong>operator</strong> modifier would result in a compilation error:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XYixYN5JwC33AMJaZI74nA.png" /><figcaption><em>‘operator’ modifier is inapplicable on this function: illegal function name</em></figcaption></figure><p>Indeed, Kotlin will only allow you to name those functions you want to use operator overloading with a fixed name, for the corresponding type, like for instance <strong>plus</strong>,<strong> minus </strong>and<strong> times</strong>.</p><p>Check out this <a href="https://kotlinlang.org/docs/reference/operator-overloading.html#operator-overloading">link</a> for more information on what conventions you have to follow to enable operator overloading to your methods.</p><p>Happy re-animating!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ba98ab0cc8c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tail Recursion in Kotlin]]></title>
            <link>https://medium.com/@fede.lopez/tail-recursion-in-kotlin-a017fc23001b?source=rss-4be7a9d6b0a5------2</link>
            <guid isPermaLink="false">https://medium.com/p/a017fc23001b</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Fede Lopez]]></dc:creator>
            <pubDate>Fri, 02 Mar 2018 12:50:19 GMT</pubDate>
            <atom:updated>2018-03-02T12:50:19.394Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/608/1*etAEOm1ZJHWua6sg-iYdwg.jpeg" /></figure><p>When Kotlin was released it joined the exclusive list of programming languages that provides tail recursion like Scala or Racket.</p><p>This programming technique allows the compiler to optimize the bytecode by treating the recursion as if it was a plain loop. This optimization however, can only be done if the final action of the recursive function calls itself as the last operation it performs.</p><p>This language feature has 2 big advantages over standard recursion:</p><ul><li>there is <strong>no risk of stack overflow</strong> as the stack does not have to keep track of each intermediate recursion state</li><li>you can write your code as using recursion but the compiler will transform it into a fast and <strong>efficient loop</strong></li></ul><p>For this, Kotlin provides a modifier function keyword named <strong>tailrec</strong> which marks the function as tail-recursive to hint the compiler to replace recursion with iteration.</p><p>Consider the classic factorial function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/756/1*Wa3XHJ8oxN_xfV82haBxAQ.png" /></figure><p>This function yields the correct factorial for the given input parameter:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/492/1*n6Eyu7_PW_bsPCDhbe_VBQ.png" /></figure><p>But the function is not tail recursive. As you can see on line 4, the final action of the recursive function does not just call itself, but instructs the compiler to store the accumulator of the result in the stack:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*1uMGdMr1KlORY4RnGYgftQ.png" /></figure><p>If you invoke call factorial(5), the stack will look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/896/1*w7IgdEmwMFy3k0fsUBGoQw.png" /></figure><p>Now let’s see how you write the factorial function as tail recursive:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*zZyV199kEtH3Gcuf0C8png.png" /></figure><p>Notice the following:</p><ul><li>the tailrec keyword modifier has been added to the function signature</li><li>the recursive call keeps track of the intermediate results with an accumulator variable that is passed as second argument</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a017fc23001b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Retrofit your apps to achieve resiliency]]></title>
            <link>https://medium.com/@fede.lopez/retrofit-your-apps-to-achieve-resiliency-18f17c5c245c?source=rss-4be7a9d6b0a5------2</link>
            <guid isPermaLink="false">https://medium.com/p/18f17c5c245c</guid>
            <category><![CDATA[cloud-native]]></category>
            <category><![CDATA[cloud-foundry]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[cloud-services]]></category>
            <dc:creator><![CDATA[Fede Lopez]]></dc:creator>
            <pubDate>Wed, 27 Dec 2017 13:04:17 GMT</pubDate>
            <atom:updated>2017-12-27T13:04:17.171Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N6ccv4-2DKBPIjfNUni5hg.jpeg" /><figcaption>San Francisco City Hall has been seismic retrofitted</figcaption></figure><p>A couple of weeks ago I went to the Morrison Planetarium in San Francisco to see “Earthquake: evidence of a restless planet”. This show is a geological journey on how this natural phenomenon constantly shapes the Earth’s layout.</p><p>At one point the show focuses on how the City of San Francisco has performed seismic retrofit on many of the public buildings such as the City Hall and the Ferry Terminals to avoid damage on these iconic landmarks in the in the event of an earthquake.</p><p>Take the City Hall, this is a massive structure with more than 100 years, which has been through multiple renovations and where its fabric is in constant maintenance. One could say in software terms that it is a legacy codebase, except that surely San Franciscans would not want it to be re-written or decommissioned. The retrofit work was done while the building was in operation and without disrupting the architectural beauty.</p><p>What they have done makes sense right? they know that earthquakes do not happen every day but the city is built in the San Andreas fault so it will eventually arrive; and when the time will come these structures will be ready for the worse. They have retrofitted the design to make sure they are resilient because they have learned from the past.</p><p>The software industry is still a bit immature in terms of resilience. When earthquakes occur (e.g. a downstream service you consume keeps on failing) the design of the application rapidly uncovers its flaws and then everybody goes through sleepless nights of support, monkey patches, server restarts and countless workarounds. Everyone knows that all this hard work will solve the problem for now but the app will still lack resilience.</p><p>But this is not the worse. A few hours of unavailability could damage badly the company you represent and cause massive losses of income and reputation.</p><p>So how do you ensure that your application is resilient?</p><h3>Getting ready for production</h3><p>As Michael Nygard once said, “developers mostly focus on implementing the features but the software is not ready for production”.</p><p>Achieving resiliency is a journey that will take you time and effort. It covers the whole spectrum of the development workflow. From the codebase to the infrastructure were the workloads run.</p><p>But you still can get the Michael Nygard resiliency stamp on your current workloads, just make sure you start retrofitting them by implementing the following patterns:</p><h3>Circuit breakers</h3><p>Circuit breakers allow you to stop cascading failures and fail fast by monitoring your calls to downstream services. As Martin Fowler <a href="https://martinfowler.com/bliki/CircuitBreaker.html">describes in his blog</a>:</p><blockquote>The basic idea behind the circuit breaker is very simple. You wrap a protected function call in a circuit breaker object, which monitors for failures. Once the failures reach a certain threshold, the circuit breaker trips, and all further calls to the circuit breaker return with an error, without the protected call being made at all. Usually you’ll also want some kind of monitor alert if the circuit breaker trips.</blockquote><p>Today is extremely simple to retrofit your calls to downstream services. If you deploy JVM workloads <a href="https://github.com/Netflix/Hystrix">Netflix Hystrix</a> is probably your best choice as it is currently the most popular OSS circuit breaker. It embraces the fact that failure is inevitable when communicating with distributed services. Just with one annotation and a little bit of configuration you can gracefully stop those cascading errors that could quickly bring down your entire system.</p><h3>Application redundancy</h3><p>Also known as high availability (HA). You can accomplish this by scaling VMs and locating them in multiple Availability Zones (AZs), so that their distribution minimizes downtime during ongoing operation, product and OS updates. Also, by deploying your app across many AZs you avoid app downtime if one of the AZs is down.</p><p>Today many platform as a service (PaaS) vendors offer this capability for your workloads. <a href="https://www.cloudfoundry.org/">Cloud Foundry</a> is an open source platform that provides <a href="https://docs.pivotal.io/pivotalcf/2-0/concepts/high-availability.html">HA</a> out of the box.</p><p>If you are looking to test your HAs, you may probably want to have a look at the Simian Army tools that Netflix offers. For instance <a href="https://medium.com/netflix-techblog/chaos-engineering-upgraded-878d341f15fa">Chaos Kong</a> allows testing your redundancies across AWS Regions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/384/1*ljHLZVBs1vlbCbedJNew4Q.jpeg" /><figcaption>Netflix Simian Army runs experiments in production environments</figcaption></figure><h3>Dynamic scalability</h3><p>Sometimes your application will need scaling up or down to meet changes in traffic or demand. There are 2 types app scalability: horizontal and vertical.</p><p>Horizontally scaling an application creates or destroys instances of your application whereas vertical scaling upgrades the disk space or memory limit.</p><p>Whether you scale horizontally or vertically is entirely up to you. What you should look is a PaaS that scales automatically based on rules you set such as CPU consumption or HTTP latency. Having a good auto scaler will minimise the cost of your running workloads while giving you an optimal application performance.</p><h3>Stateless servers</h3><p>This is one of the <a href="https://12factor.net/processes">12-factor</a> App mantras drafted by Heroku in 2011. As they summarise in their webpage:</p><blockquote>Twelve-factor processes are stateless and share-nothing. Any data that needs to persist must be stored in a stateful backing service, typically a database.</blockquote><p>Indeed, if your workloads keep internal state in the application for future jobs then you should refactor them so that data is persisted in databases or other types of data structures. This simple pattern will allow you to perform hassle free app maintenance and think about your deployments as disposable stateless processes (i.e. they can be started or stopped at any time).</p><h3>Fast application deployment</h3><p>This is another 12-factor which states that:</p><blockquote>Processes should strive to minimize startup time. Ideally, a process takes a few seconds from the time the launch command is executed until the process is up and ready to receive requests or jobs. Short startup time provides more agility for the release process and scaling up; and it aids robustness, because the process manager can more easily move processes to new physical machines when warranted.</blockquote><p>Have you ever worked on apps with slow startup times? how did you and the other members of your team describe them? There is nothing more frustrating than waiting for your app to start up. The feedback loop becomes unbearable. Tests are slow, the build pipeline is slow and then productivity plummets. Suddenly you wake up and realise that you have to maintain a monster app. One of the last projects I worked on, the backend API was taking more than 30 seconds to startup. App startup time was not something the team took care of until it became a problem.</p><h3>Wrap up</h3><p>As I mentioned before, app resiliency is achieved after many iterations of experimentation and repeated failures. It is a daunting process, but you can retrofit any type of app by doing one step at a time. If you are using Java, try applying the Circuit breaker pattern first. It will be a quick win because it’s dead simple to use and gives enormous benefits. Some HTTP clients such as <a href="https://github.com/OpenFeign/feign">Feign</a> come with Hystrix out of the box.</p><p>There are a few books about application resiliency you can reach out to. <a href="https://pragprog.com/book/mnee/release-it">Release it!</a> is one of the most popular ones. <a href="http://shop.oreilly.com/product/0636920038252.do">Cloud Native Java</a> provides good advice on how to develop resilient apps on the Spring and Cloud Foundry ecosystem.</p><p>Hopefully this blog post gave you enough insights to get started and kick-off your cloud native journey. I have personally just started it and would love to hear from your experiences. Good luck.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=18f17c5c245c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Take Reactive programming with Spring to the infinity and beyond]]></title>
            <link>https://medium.com/@fede.lopez/take-reactive-programming-with-spring-to-the-infinity-and-beyond-965a4c15b26?source=rss-4be7a9d6b0a5------2</link>
            <guid isPermaLink="false">https://medium.com/p/965a4c15b26</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[reactive-programming]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Fede Lopez]]></dc:creator>
            <pubDate>Wed, 20 Sep 2017 04:02:41 GMT</pubDate>
            <atom:updated>2017-09-20T04:02:41.466Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*eYPD6Nie7QROiA6n0uPSTQ.png" /></figure><p>Spring 5 has a new functional web framework that changes the way we develop applications. With this new release you will be able to develop non-blocking, event-driven services leveraging on the open source reactive framework <a href="https://projectreactor.io/">Project Reactor</a>.</p><p>In this blog post I am going to show you how to develop a Spring Boot app that serves infinite streams of Bitcoin prices and how to display them on a web browser as they get updated every second.</p><h3>Building the backend</h3><p>Go to <a href="https://start.spring.io/">https://start.spring.io</a> and generate a <strong>Gradle</strong> project for <strong>Kotlin</strong> and <strong>Spring Boot</strong> version 2.0.0 M4. Add the dependency <strong>Reactive Web</strong>. Name the application <strong>web-flux-reactive</strong>.</p><p>Open the project in your IDE and navigate to the main application class generated by the initializr: <strong>WebFluxReactiveApplication</strong>.</p><p>Enable the application to be a Restful service using the RestController annotation:</p><pre>@SpringBootApplication<br><strong>@RestController</strong><br>class WebFluxReactiveApplication<br>...</pre><p>Create a data class representing a Bitcoin price. This class will hold 2 properties, the update time and the rate, it does not matter in which currency. Instances of this class will be sent to the web client:</p><pre>data class BitCoinPrice(val updated: Date, val rate: BigDecimal)</pre><p>Create a <strong>GetMapping</strong> function to retrieve a <strong>Flux</strong> stream of Bitcoin prices, leave the body of the method blank for the moment:</p><pre>@CrossOrigin<br>@GetMapping(value = &quot;/bitcoinprices&quot;, produces = <em>arrayOf</em>(MediaType.<em>TEXT_EVENT_STREAM_VALUE</em>))<br>fun getBitcoinPrices(): Flux&lt;BitCoinPrice&gt; {<br>    <strong><br></strong>}</pre><p>Notice the following:</p><ul><li>The get endpoint produces a response of MIME type <strong>text/event-stream</strong>. This is needed when you want to return to the client server-side events.</li><li>The body of the response is a Flux&lt;BitCoinPrice&gt;. This type is a reactive stream publisher that emits 0 to N elements, and then completes. In our case we will continuously emit events forever.</li><li>We have enabled the endpoint to allow cross-origin requests so that our web app can call directly the service from a different origin.</li></ul><p>Now let’s implement the body of the function <strong>getBitcoinPrices</strong>. What we are going to do is to emit a Flux of Bitcoin prices every second. For that we will create two flux objects and combine them.</p><p>The first one is an <strong>interval</strong> that emits an event every second:</p><pre>val interval = Flux.interval(Duration.ofSeconds(1))</pre><p>The second one creates a <strong>stream</strong> of random Bitcoin prices:</p><pre>val bitCoinPrice = Flux.fromStream&lt;BitCoinPrice&gt;(Stream.generate(<strong>{<br>       </strong>BitCoinPrice(Date(), BigDecimal.valueOf(Math.abs(Random().nextLong())))<br><strong>}</strong>))</pre><p>Now we zip them together so that we can generate a random Bitcoin price every second:</p><pre>val bitCoinEvents = Flux.zip(interval, bitCoinPrice).map <strong>{ it</strong>.<em>t2 </em><strong>}</strong></pre><p>the result Rest endpoint looks like this:</p><pre>@CrossOrigin<br>@GetMapping(value = &quot;/bitcoinprices&quot;, produces = <em>arrayOf</em>(MediaType.<em>TEXT_EVENT_STREAM_VALUE</em>))<br>fun getBitcoinPrices(): Flux&lt;BitCoinPrice&gt; {<br>    val interval = Flux.interval(Duration.ofSeconds(1))<br>    val bitCoinPrice = Flux.fromStream&lt;BitCoinPrice&gt;(Stream.generate(<strong>{<br>           </strong>BitCoinPrice(Date(), BigDecimal.valueOf(Math.abs(Random().nextLong())))<br>    <strong>}</strong>))<br>    val bitCoinEvents = Flux.zip(interval, bitCoinPrice).map <strong>{ it</strong>.<em>t2 </em><strong>}<br>    </strong>return bitCoinEvents<br>}</pre><p>To test that this works, start the app:</p><pre>./gradlew bootRun</pre><p>Now call the <strong>bitcoinprices </strong>GET endpoint from the command line using curl:</p><pre>curl http://localhost:8080/bitcoinprices -H &quot;Accept:text/event-stream&quot;</pre><p>You should see a response that produces random Bitcoin prices every second:</p><pre>data:{&quot;updated&quot;:1505872373787,&quot;rate&quot;:4031582811327568277}</pre><pre>data:{&quot;updated&quot;:1505872374793,&quot;rate&quot;:6041308289908491586}</pre><pre>data:{&quot;updated&quot;:1505872375791,&quot;rate&quot;:3622194130843937061}</pre><pre>data:{&quot;updated&quot;:1505872376789,&quot;rate&quot;:8362185520184618113}</pre><h3>Building the frontend</h3><p>Consuming server-sent events from a web app is fairly straightforward. For this example we are going to build a very simple web page that uses an <a href="https://developer.mozilla.org/en-US/docs/Web/API/EventSource">EventSource</a> object to receive the Bitcoin prices. This class allows us to connect to the server over HTTP and receive events in text/event-stream format, which is the MIME type that our endpoint uses.</p><p>One interesting feature that EventSource provides is that it does not close the connection and it will re-connect automatically if for some reason the communication with the server drops.</p><p>Now create anywhere on your file system a blank <strong>index.html</strong> page that pulls the latest JQuery dependency:</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br>&lt;head&gt;<br>    &lt;title&gt;Event Source Client&lt;/title&gt;<br>    &lt;script src=&quot;https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js&quot;&gt;&lt;/script&gt;<br>    &lt;script src=&quot;app.js&quot;&gt;&lt;/script&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>Add the following <strong>div</strong> to the <strong>body</strong> tag:</p><pre>...<br>&lt;body&gt;<br>    &lt;div&gt;<br>        &lt;h1&gt;Real time Bitcoin prices&lt;/h1&gt;<br>        &lt;p id=&quot;updated&quot;&gt;Updated: &lt;/p&gt;<br>        &lt;p id=&quot;rate&quot;&gt;Rate: &lt;/p&gt;<br>        &lt;button id=&quot;start&quot;&gt;Start&lt;/button&gt;<br>        &lt;button id=&quot;cancel&quot;&gt;Cancel&lt;/button&gt;<br>    &lt;/div&gt;<br>&lt;/body&gt;<br>...</pre><p>This <strong>div</strong> has four elements that are worth mentioning:</p><ul><li>a paragraph that will show the update time of the Bitcoin price</li><li>another paragraph that will show the Bitcoin rate</li><li>a start button to instruct when to start receiving Bitcoin prices</li><li>a cancel button to stop receiving Bitcoin prices</li></ul><p>Now create a file named <strong>app.js</strong> in the same folder as the index.html. This file will be used to add the logic needed to update the web page index.html.</p><p>Add a ready callback so that we can manipulated safely the page using JavaScript:</p><pre>(document).ready(<strong>function </strong>() {<br><br>});</pre><p>Add a function inside the callback named <strong>createEventSource. </strong>This function<strong> </strong>returns an EventSource object that establishes a connection with our restful endpoint:</p><pre><strong>function </strong>createEventSource() {<br>    <strong>var </strong>eventSource = <strong>new </strong>EventSource(&quot;http://localhost:8080/bitcoinprices&quot;);<br>    <br>    <strong>return </strong>eventSource;<br>}</pre><p>Now attach a callback to the EventSource object before returning it so that whenever a message is sent by the server we update the HTML components with the latest information:</p><pre>eventSource.addEventListener(&#39;message&#39;, <strong>function </strong>(e) {<br>        <strong>const </strong>body = JSON.parse(e.data);<br>        $(&quot;#updated&quot;).text(&quot;Updated: &quot; + body.updated);<br>        $(&quot;#rate&quot;).text(&quot;Rate: &quot; + body.rate);<br>    }, <strong>false</strong>);</pre><p>Create an EventSource variable inside the <strong>ready</strong> callback:</p><pre><strong>var </strong>eventSource;</pre><p>Now add a JQuery callback to the <strong>start</strong> button. This will cancel the previous connection (if any) and we will establish a new one to receive Bitcoin prices:</p><pre>$(&quot;#start&quot;).click(<strong>function</strong>() {<br>    <strong>if </strong>(eventSource) {<br>        eventSource.close();<br>    }<br>    eventSource = createEventSource();<br>});</pre><p>Similarly, we want to stop listening for server-sent Bitcoin prices whenver the user clicks the cancel button:</p><pre>$(&quot;#cancel&quot;).click(<strong>function</strong>() {<br>    eventSource.close();<br>});</pre><p>The final <strong>app.js</strong> should look like this:</p><pre>$(document).ready(<strong>function </strong>() {<br><br>    <strong>function </strong>createEventSource() {<br>        <strong>var </strong>eventSource = <strong>new </strong>EventSource(&quot;http://localhost:8080/events&quot;);<br>        eventSource.addEventListener(&#39;message&#39;, <strong>function </strong>(e) {<br>            <strong>const </strong>body = JSON.parse(e.data);<br>            $(&quot;#updated&quot;).text(&quot;Updated: &quot; + body.updated);<br>            $(&quot;#rate&quot;).text(&quot;Rate: &quot; + body.rate);<br>        }, <strong>false</strong>);<br>        <strong>return </strong>eventSource;<br>    }<br><br>    <strong>var </strong>eventSource;<br><br>    $(&quot;#start&quot;).click(<strong>function</strong>() {<br>        <strong>if </strong>(eventSource) {<br>            eventSource.close();<br>        }<br>        eventSource = createEventSource();<br>    });<br><br>    $(&quot;#cancel&quot;).click(<strong>function</strong>() {<br>        eventSource.close();<br>    });<br>});</pre><h3>Testing the client</h3><p>Now that we have an index.html and an app.js ready to be served, let’s spin up a local server so that the web app can be accessed from your browser.</p><p>Install <strong>local-web-server</strong> using <a href="https://www.npmjs.com/">npm</a>:</p><pre>npm install -g local-web-server</pre><p>Go to the folder where reside the index.html and the app.js files.</p><p>Run the following command:</p><pre>ws --spa index.html</pre><p>Open your browser and navigate to <a href="http://127.0.0.1:8000/">http://127.0.0.1:8000</a>.</p><p>You should see the Bitcoin prices updated every second:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/1*LBtX2OsBXbEGm_7BffmVTQ.gif" /></figure><h3>Take aways</h3><p>Today we have learned that:</p><ul><li>Spring 5 gives you the tools to create async, non-blocking Restful endpoints that can serve streams of data over HTTP connections.</li><li>Your web client can easily consume these streams of data and be notified whenever there are new updates.</li><li>All this can be achieved with just a few lines of code thanks to the sleek functions provided by the Project Reactor and available in Spring 5.</li></ul><p>Hopefully this will help you to embark on the reactive journey and bring your apps to the infinity and beyond!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=965a4c15b26" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Service discovery in Pivotal Cloud Foundry]]></title>
            <link>https://medium.com/@fede.lopez/service-discovery-in-pivotal-cloud-foundry-d1c81f5ade59?source=rss-4be7a9d6b0a5------2</link>
            <guid isPermaLink="false">https://medium.com/p/d1c81f5ade59</guid>
            <category><![CDATA[netflixoss]]></category>
            <category><![CDATA[cloud-native]]></category>
            <category><![CDATA[cloud-foundry]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Fede Lopez]]></dc:creator>
            <pubDate>Thu, 14 Sep 2017 00:54:47 GMT</pubDate>
            <atom:updated>2017-09-14T02:16:51.297Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/641/1*SWFvZjLlAsemVsIbgFdw7g.png" /></figure><p>In this blog post I am going to show you how to enable your Spring Boot apps to talk to each other in Pivotal Cloud Foundry without knowing each other’s physical address.</p><p>Recently PCF published a free service called <a href="https://docs.pivotal.io/spring-cloud-services/1-4/common/service-registry/">Service Registry</a> which allows you to dynamically discover and call registered services with minimal code changes. This service is backed up by <a href="https://github.com/Netflix/eureka">Eureka</a>, Netflix open source framework for locating services in the cloud.</p><h3>What we are going to build today</h3><p>To illustrate this, we are going to build 2 micro-services, a producer and a consumer. The producer will expose a web endpoint which will return a random translation to another language of the word “hello”. The consumer service will call every second the producer to get the word hello translated to a random language at each call.</p><p>Both apps are going to be registered to the PCF service registry so they can be discovered at runtime.</p><h3>Creating the producer</h3><p>Go to <a href="https://start.spring.io/">https://start.spring.io</a> and setup an application named “producer”, for maven, Kotlin and with no dependencies. Click on “Generate project”.</p><p>Open the pom.xml from your downloaded project in your IDE.</p><p>Ensure the parent group points to the following starter dependency:</p><pre>&lt;parent&gt;<br>   &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>   &lt;artifactId&gt;spring-boot-starter-parent&lt;/artifactId&gt;<br>   &lt;version&gt;1.5.2.RELEASE&lt;/version&gt;<br>   &lt;relativePath/&gt; <br>&lt;/parent&gt;</pre><p>Add the following compile dependencies to the project:</p><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;io.pivotal.spring.cloud&lt;/groupId&gt;<br>    &lt;artifactId&gt;spring-cloud-services-starter-service-registry&lt;/artifactId&gt;<br>&lt;/dependency&gt;<br>&lt;dependency&gt;<br>    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>    &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt;<br>&lt;/dependency&gt;</pre><p>then add the following dependencies to the dependencyManagement block:</p><pre>&lt;dependencyManagement&gt;<br>    &lt;dependencies&gt;<br>        &lt;dependency&gt;<br>            &lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;<br>            &lt;artifactId&gt;spring-cloud-dependencies&lt;/artifactId&gt;<br>            &lt;version&gt;Dalston.SR1&lt;/version&gt;<br>            &lt;type&gt;pom&lt;/type&gt;<br>            &lt;scope&gt;import&lt;/scope&gt;<br>        &lt;/dependency&gt;<br>        &lt;dependency&gt;<br>            &lt;groupId&gt;io.pivotal.spring.cloud&lt;/groupId&gt;<br>            &lt;artifactId&gt;spring-cloud-services-dependencies&lt;/artifactId&gt;<br>            &lt;version&gt;1.5.0.RELEASE&lt;/version&gt;<br>            &lt;type&gt;pom&lt;/type&gt;<br>            &lt;scope&gt;import&lt;/scope&gt;<br>        &lt;/dependency&gt;<br>    &lt;/dependencies&gt;<br>&lt;/dependencyManagement&gt;</pre><p>Open the <strong>ProducerApplication.kt</strong> file that has been generated by the initializr website.</p><p>Create a GET mapping that returns a salutation in a random language:</p><pre>@SpringBootApplication<br>@EnableDiscoveryClient<br>@RestController<br>class ProducerApplication {<br><br>    @GetMapping(&quot;/hello&quot;)<br>    fun getHello(): String = randomHello()<br><br>    private fun randomHello(): String {<br>        val values = &quot;Hola,Kaixo,Guten Tag,Ciao,Namaste,ᎣᏏᏲ,Halito,Salute,Aluu,Bonjour&quot;.<em>split</em>(&quot;,&quot;)<br>        return values[Random().nextInt(values.size)]<br>    }<br>}<br><br>fun main(args: Array&lt;String&gt;) {<br>    SpringApplication.run(ProducerApplication::class.<em>java</em>, *args)<br>}</pre><p>Now open the application.yml (or application.properties) and add the following keys:</p><pre><strong>spring:<br>  cloud:<br>    services:<br>      registrationMethod: </strong>route<br><br><strong>security:<br>  basic:<br>    enabled: </strong>false</pre><p>The last thing we need to do is to assign a name to our app, so it can be discovered by the consumer at runtime. Add a <strong>bootstrap.yml</strong> file in the same folder of the application.yml with the following key:</p><pre><strong>spring:<br>  application:<br>    name: </strong>producer-app</pre><p>Now the producer is capable to register to the PCF service registry backed by Eureka.</p><h3>Deploying the producer</h3><p>Let’s deploy the producer to PCF. To do this, go to the root folder of the maven project and create an executable:</p><pre>$ mvn package</pre><p>Now the jar artifact will be created under the target directory.</p><p>Login to PCF using the cf-cli and push the app:</p><pre>$ cf push producer-app -p target/producer-0.0.1-SNAPSHOT.jar</pre><h3>Creating the consumer</h3><p>Go to <a href="https://start.spring.io/">https://start.spring.io</a> and setup an application named “consumer”, for maven, Kotlin and with no dependencies. Click on “Generate project”.</p><p>Open the pom.xml from your downloaded project in your IDE.</p><p>Ensure the parent group also looks also like this:</p><pre>&lt;parent&gt;<br>   &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>   &lt;artifactId&gt;spring-boot-starter-parent&lt;/artifactId&gt;<br>   &lt;version&gt;1.5.2.RELEASE&lt;/version&gt;<br>   &lt;relativePath/&gt; <br>&lt;/parent&gt;</pre><p>Add the spring cloud service compile dependency to the project:</p><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;io.pivotal.spring.cloud&lt;/groupId&gt;<br>    &lt;artifactId&gt;spring-cloud-services-starter-service-registry&lt;/artifactId&gt;<br>&lt;/dependency&gt;</pre><p>then add the following dependencies to the dependencyManagement block:</p><pre>&lt;dependencyManagement&gt;<br>    &lt;dependencies&gt;<br>        &lt;dependency&gt;<br>            &lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;<br>            &lt;artifactId&gt;spring-cloud-dependencies&lt;/artifactId&gt;<br>            &lt;version&gt;Dalston.SR1&lt;/version&gt;<br>            &lt;type&gt;pom&lt;/type&gt;<br>            &lt;scope&gt;import&lt;/scope&gt;<br>        &lt;/dependency&gt;<br>        &lt;dependency&gt;<br>            &lt;groupId&gt;io.pivotal.spring.cloud&lt;/groupId&gt;<br>            &lt;artifactId&gt;spring-cloud-services-dependencies&lt;/artifactId&gt;<br>            &lt;version&gt;1.5.0.RELEASE&lt;/version&gt;<br>            &lt;type&gt;pom&lt;/type&gt;<br>            &lt;scope&gt;import&lt;/scope&gt;<br>        &lt;/dependency&gt;<br>    &lt;/dependencies&gt;<br>&lt;/dependencyManagement&gt;</pre><p>Open the <strong>ConsumerApplication.kt</strong> file that has been generated by the initializr website.</p><p>Let’s add the ability to the consumer to talk to the producer. Implement a bean that returns a <strong>CommandLineRunner </strong>and assign a timer that will call the producer app every second:</p><pre>@SpringBootApplication<br>@EnableDiscoveryClient<br>class ConsumerApplication {<br><br>    @Autowired<br>    private lateinit var restTemplate: RestTemplate<br><br>    @Bean<br>    fun commandLineRunner(): CommandLineRunner {<br>        return <em>CommandLineRunner </em><strong>{<br>            </strong><em>timer</em>(name = &quot;test&quot;, period = 1000, action = <strong>{<br>                </strong>val uri = UriComponentsBuilder.<em>fromUriString</em>(&quot;//producer-app/hello&quot;).build().toUri()<br>                val greeting = restTemplate.getForObject(uri, String::class.<em>java</em>)<br>                <em>println</em>(greeting)<br>            <strong>}</strong>)<br>        <strong>}<br>    </strong>}<br><br>    @Bean<br>    @LoadBalanced<br>    fun restTemplate(): RestTemplate = RestTemplate()<br>}<br><br>fun main(args: Array&lt;String&gt;) {<br>    SpringApplication.run(ConsumerApplication::class.<em>java</em>, *args)<br>}</pre><p>Notice two things:</p><ul><li>the URI we use to call the producer is based on the <strong>name </strong>of the Spring Boot app, instead of the IP or physical address to the server where the producer is deployed:</li></ul><pre>val uri = UriComponentsBuilder.<em>fromUriString</em>(&quot;//<strong>producer-app</strong>/hello&quot;).build().toUri()</pre><ul><li>the <strong>RestTemplate</strong> is annotated as a load balanced rest template meaning that is equipped with a client-side load balancer.</li></ul><p>This is a major improvement to the way services talk to each other in the cloud. You can now forget about passing the host name or IP address of the service you want to consume, instead you only need to know the name.</p><h3>Deploying the consumer</h3><p>Let’s deploy the consumer to PCF. To do this, go to the root folder of the maven project and create an executable:</p><pre>$ mvn package</pre><p>push the app to PCF:</p><pre>$ cf push consumer-app -p target/consumer-0.0.1-SNAPSHOT.jar</pre><h3>Binding the discovery registry service</h3><p>Ensure you are <a href="https://docs.cloudfoundry.org/cf-cli/getting-started.html#login">logged in to PCF</a> using the cf-cli.</p><p>Add the Eureka Service Registry to your PCF instance, we will call it <em>my-service-registry</em>:</p><pre>$ cf create-service p-service-registry standard my-service-registry</pre><p>Now bind it to the producer app:</p><pre>$ cf bind-service producer-app my-service-registry</pre><p>And to the consumer app:</p><pre>$ cf bind-service consumer-app my-service-registry</pre><p>Now both the producer and consumer apps are discoverable and can talk to each other without knowing the physical location where they are deployed.</p><h3>Now you are closer to a cloud native architecture</h3><p>In addition, by using the Service Registry you will get load balancing for free, so no matter how many producer or consumer instances you deploy they will all register to the Eureka server and will use a built-in load balancer that does basic round-robin.</p><p>Having the ability to discover services gives by name instead of physical address brings you closer to a cloud native architecture. Now your apps can embrace the fact that in the cloud, because of its inherent nature, servers come and go and there is no longer the need to keep track of IP addresses and host names.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d1c81f5ade59" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Parser generators for developers in a hurry]]></title>
            <link>https://medium.com/@fede.lopez/parser-generators-for-developers-in-a-hurry-39f1c0dacfc1?source=rss-4be7a9d6b0a5------2</link>
            <guid isPermaLink="false">https://medium.com/p/39f1c0dacfc1</guid>
            <category><![CDATA[antlr]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Fede Lopez]]></dc:creator>
            <pubDate>Tue, 12 Sep 2017 07:02:53 GMT</pubDate>
            <atom:updated>2017-09-12T07:02:53.011Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/516/1*p34i8WCjl5qwm0s8VoCgnA.png" /></figure><p>I have been developing software since 2001. Up until last year, I was not very familiar about parser generators, nor did I care much.</p><p>But last December I was assigned on a client project to develop a calculator to help end users establish the likely rebuild cost of their house. The formulae that defined the rebuild costs were stored in a database. In order to evaluate a final dollar value for a given property we would have to load the formulae, parse them and then evaluate them at runtime.</p><p>Just to give you an idea, this is a formula that describes the rebuild cost just for the external walls of a property:</p><pre>(1 + (bool(answ(302185) &gt;= 2) * 0.33)) * var(1061) * (grid(3903) * grid(3860))</pre><p>We had to evaluate hundreds of these to yield the final cost of an entire house.</p><p>The formula doesn’t make sense at all without the business context behind, but the underlying issue was the following: how do we parse this text and yield the calculation result from the expression?</p><p>After some research, I realized that what we needed was a parser generator.</p><p>Parser generators are a tool that you will probably not need for most of your career as software engineer, but the day you will face a similar problem as this one, they will come in very handy as they solve this kind of problem very elegantly and without much coding effort.</p><h3>So what does a parser generator do?</h3><p>Parser generators take a grammar file as input and they produce source code as output that can parse streams of characters using the grammar.</p><p>The generated code is the <em>parser</em>, which takes a sequence of characters and tries to match them against the grammar.</p><p>The parser produces a <em>parse tree. </em>This object captures how the parser recognized the structure of the input sentence and component phrases and allows to be walked so that you can actually do stuff about the parsed elements.</p><h3>Let’s use a parser generator!</h3><p>Today we are going to implement a parser that knows how to calculate numerical expressions like the following ones:</p><ul><li>2 * 5 /2</li><li>(1 + (1 + (1)))</li></ul><p>For this demo we will use <a href="http://www.antlr.org/">ANTLR</a>, the king of kings of the parser generators in the JVM space. We are also going to use the ANTLR maven plugin to generate the parsers.</p><h3>Setting up the development environment</h3><p>Add the ANTLR 4 dependency to your pom:</p><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;org.antlr&lt;/groupId&gt;<br>    &lt;artifactId&gt;antlr4-runtime&lt;/artifactId&gt;<br>    &lt;version&gt;4.7&lt;/version&gt;<br>&lt;/dependency&gt;</pre><p>Then configure the ANTLR plugin to generate a visitor instead of a listener:</p><pre>&lt;build&gt;<br>    &lt;plugins&gt;<br>        &lt;plugin&gt;<br>            &lt;groupId&gt;org.antlr&lt;/groupId&gt;<br>            &lt;artifactId&gt;antlr4-maven-plugin&lt;/artifactId&gt;<br>            &lt;version&gt;4.7&lt;/version&gt;<br>            &lt;configuration&gt;<br>                &lt;arguments&gt;<br>                    &lt;argument&gt;-no-listener&lt;/argument&gt;<br>                    &lt;argument&gt;-visitor&lt;/argument&gt;<br>                &lt;/arguments&gt;<br>            &lt;/configuration&gt;<br>        &lt;/plugin&gt;<br>        ...<br>    &lt;/plugins&gt;<br>&lt;/build&gt;</pre><h3>The grammar file</h3><p>Create a file named Calculator.g4 under the folder <em>src &gt; main &gt; antlr101</em>.</p><p>Add the following line:</p><pre><strong>grammar </strong>Calculator ;</pre><p>Now if try to run the ANTLR maven plugin from the command line you should get an exception:</p><pre>$ mvn antlr4:antlr4 </pre><pre>[ERROR] /.../antlr101/Calculator.g4 [-1:-1]: grammar Calculator has no rules</pre><p>Great, this exception is expected since our grammar file is empty… the good thing is that the ANTLR development environment is properly set so let’s start adding rules!</p><h3>Parse integer numbers</h3><p>Now that we have the grammar file let’s modify it to teach the parser how to parse integer numbers.</p><p>First add a top level root node, call it <em>expression </em>and underneath it add a child named <em>INT</em>, followed with the label <em>#Int</em>:</p><pre><strong>grammar </strong>Calculator ;<br><br>expression<br>    :   INT #Int ;</pre><p>This is telling ANTLR that we want to parse something that for the moment we call <em>INT</em>. The <em>#Int</em> instructs ANTLR to generate a visitor function that can be overriden to do stuff. This function will be automatically called by the parse tree whenever an integer number is matched.</p><p>Now let’s tell ANTLR what are integers. Place down below the following regex to tell that ints are sequences of one or more decimal characters:</p><pre><strong>grammar </strong>Calculator ;<br><br>expression<br>    :   INT #Int ;</pre><pre>INT : [0-9]+ ;</pre><p>Invoke the ANTLR maven plugin again, if the build is successful you should see a number of files under the <em>generated-sources</em> folder:</p><ul><li>CalculatorBaseVisitor.java</li><li>CalculatorLexer.java</li><li>CalculatorParser.java</li><li>CalculatorVisitor.java</li></ul><h3>Implementing the visitor</h3><p>Create a class named <strong>Calculator</strong> that extends <strong>CalculatorBaseVisitor</strong>:</p><pre>class Calculator extends CalculatorBaseVisitor&lt;Integer&gt; {</pre><pre>}</pre><p>We have typed the class as an Integer visitor. This means that any function that will be subsequently added to this class by ANTLR will yield an Integer as result. This makes sense for this example as any expression we will parse is an integer, but you could return more complex objects if needed more control.</p><p>Implement the <em>visitInt</em> method that is offered by the superclass:</p><pre>@Override<br>public Integer visitInt(CalculatorParser.IntContext ctx) {<br>    String value = ctx.INT().getText();<br>    return Integer.<em>valueOf</em>(value);<br>}</pre><p>So what we have done here is the following: we have told ANTLR that whenever an integer value is matched, our function <em>visitInt</em> will convert the string into an integer.</p><h3>Testing the visitor</h3><p>Our parser should be able to parse numeric values passed in an expression. In order to test the visitor tree, you can create a parse tree and visiting the tree from the root expression as this code snippet shows:</p><pre>public static void main(String[] args) {<br>    String expression = &quot;42&quot;;</pre><pre>    CharStream stream = CharStreams.<em>fromString</em>(expression);<br>    CalculatorLexer lexer = new CalculatorLexer(stream);<br>    TokenStream tokenStream = new CommonTokenStream(lexer);<br>    CalculatorParser parser = new CalculatorParser(tokenStream);<br>    ParseTree tree = parser.expression();<br>    Integer result = new Calculator().visit(tree);<br>    System.out.println(result); // prints &quot;42&quot;<br>}</pre><h3>Parse parenthesis</h3><p>Now that we know how to parse integers, let’s teach our parser how to parse expressions with parenthesis such as this one:</p><pre>(1(1(1(1))))</pre><p>Go to the grammar file and add the following rule below INT:</p><pre><strong>   </strong> :   INT #Int ;<br>    |   LPAREN expression RPAREN #Parenthesis ;</pre><p>And explain what is a LPAREN and RPAREN below the INT definition:</p><pre>INT   : [0-9]+ ;<br>LPAREN: &#39;(&#39;;<br>RPAREN: &#39;)&#39;;</pre><p>Here we just have told the parser that an expression could be wrapped between parenthesis. The good thing about ANTLR is that it handles recursion for us so we don’t have to be more specific about nested parenthesis.</p><p>Invoke the ANTLR maven plugin once more so that a new visitor function will be generated to handle parenthesis.</p><p>Now on your <strong>Calculator</strong> class implement the <em>visitParenthesis</em> method offered by the superclass CalculatorBaseVisitor.</p><p>The implementation is dead simple, the only thing needed to do when encountering a parenthesis is just ignore the left and right brackets and evaluate the underlying expression!</p><pre>@Override<br>public Integer visitParenthesis(CalculatorParser.ParenthesisContext ctx) {<br>    return visit(ctx.expression());<br>}</pre><p>Now the parser is armed to handle parenthesis.</p><h3>Parse additions and subtractions</h3><p>Let’s start to add arithmetic functions to our parser. We are going to add the capability of adding and subtracting.</p><p>Open the grammar file and add a new rule for adding and subtracting:</p><pre><strong>grammar </strong>Calculator ;<br><br>expression<br><em>      </em>:   left=expression (ADD|SUB) right=expression # AddSub<br><em>      </em>|   INT #Int<br>      <br>...<br>ADD : &#39;+&#39; ;<br>SUB : &#39;-&#39; ;<br>...</pre><p>A couple of things to notice:</p><pre>left=expression ... right=expression ...</pre><p>By adding the labels “left” and “right” we are telling ANTLR to generate fields which will actually contain the left expression and the right expression. This will come in handy when implementing the visitor function.</p><pre>(ADD|SUB)</pre><p>In here we are telling that an expression could be followed by an ADD symbol or a SUB symbol (that’s the role of the pipe “|” operator).</p><p>Now generate again the parser files using maven.</p><p>A new function will be created on the <strong>CalculatorBaseVisitor</strong> named <em>visitAddSub</em>. Overwrite it on your <strong>Calculator</strong> class and implement the addition or subtraction depending of what is coming int the context object:</p><pre>@Override<br>public Integer visitAddSub(CalculatorParser.AddSubContext ctx) {<br>    if (ctx.ADD() != null) {<br>        return visit(ctx.left) + visit(ctx.right);<br>    } else {<br>        return visit(ctx.left) - visit(ctx.right);<br>    }<br>}</pre><h3>Parse multiplications and divisions</h3><p>Now that we have implemented addition and subtraction, is very easy to add multiplication and division capabilities to the grammar.</p><pre><strong>grammar </strong>Calculator ;<br><br>expression<br>    :   left=expression (MUL|DIV) right=expression # MulDiv<br>    |   left=expression (ADD|SUB) right=expression # AddSub</pre><p>Notice how I have added the multiplication and division rule above the sum and subtraction. This is intentional and it is because multiplications and divisions have more precedence than sums and subtractions. So if the parser encounters:</p><pre>2 * 3 + 1</pre><p>The result yielded will be 7 instead of 8. The Abstract Syntax Tree produced would be:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/331/1*5Uhb9vhsJC0n8JrBKL8FjA.png" /><figcaption>AST giving precedence to multiplications and divisions</figcaption></figure><p>instead of:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/289/1*FCcgDxbRGEln-WSvF4RE9g.png" /><figcaption>AST giving precedence to additions and subtractions</figcaption></figure><p>Now let’s generate again the parser files using maven.</p><p>A new function will be created on the <strong>CalculatorBaseVisitor</strong> named <em>visitMulDiv</em>. Overwrite it on your <strong>Calculator</strong> class and implement the multiplication or division depending of what is coming int the context object:</p><pre>@Override<br>public Integer visitMulDiv(CalculatorParser.MulDivContext ctx) {<br>    if (ctx.MUL() != null) {<br>        return visit(ctx.left) * visit(ctx.right);<br>    } else {<br>        return visit(ctx.left) / visit(ctx.right);<br>    }<br>}</pre><p>That’s it! you have a calculator that can perform additions, subtractions, multiplications and divisions and also handle parenthesis, with just a few lines of code.</p><h3>Skipping whitespaces</h3><p>You can tell ANTLR to skip processing any blank character such as tabs and whitespaces. Just add this line at the end of your grammar to instruct ANTLR to ignore any of these characters:</p><pre>WS : [ \t\r\n\f]+ -&gt; skip ;</pre><h3>See the parse tree</h3><p>ANTLR has a very nice feature which allows you to see the AST (Abstract Syntax Tree) produced for a given expression. You just have to take out the dust to the Swing libraries and add a TreeViewer panel to a JFrame:</p><pre>public static void main(String[] args) {<br>    String expression = &quot;3 * (2 + 1) + 10&quot;;<br>    CalculatorParser parser = <em>createParser</em>(expression);<br>    ParseTree tree = parser.expression();<br>    System.<em>out</em>.println(&quot;String tree = &quot; + tree.toStringTree());<br><br>    //show AST in GUI<br>    JFrame frame = new JFrame(&quot;AST for expression: &quot; + expression);<br>    TreeViewer treeViewer = new TreeViewer(Arrays.<em>asList</em>(parser.getRuleNames()), tree);<br>    treeViewer.setScale(1.5);//scale a little<br>    frame.add(treeViewer);<br>    frame.setSize(640, 480);<br>    frame.setVisible(true);<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/449/1*k0mO4kJyQvPCyyev0nn_EQ.png" /></figure><p>The source code for this article can be found on Github:</p><p><a href="https://github.com/fedelopez/antlr101">https://github.com/fedelopez/antlr101</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=39f1c0dacfc1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Make your Spring Boot Apps resilient with Hystrix]]></title>
            <link>https://medium.com/@fede.lopez/make-your-spring-boot-apps-resilient-with-hystrix-dc9ba8733e9c?source=rss-4be7a9d6b0a5------2</link>
            <guid isPermaLink="false">https://medium.com/p/dc9ba8733e9c</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[cloud-native]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[netflixoss]]></category>
            <dc:creator><![CDATA[Fede Lopez]]></dc:creator>
            <pubDate>Thu, 06 Jul 2017 12:53:13 GMT</pubDate>
            <atom:updated>2017-07-06T12:53:13.569Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/264/1*5G_B_l9woZIHnnWAZ0QQmw.png" /></figure><p>In this post I am going to show you how to apply the <a href="https://martinfowler.com/bliki/CircuitBreaker.html">Circuit Breaker</a> pattern in your Spring Boot apps using <a href="https://github.com/Netflix/Hystrix">Hystrix</a>, Netflix latency and fault tolerance library.</p><p>Hystrix is a library that can help you making your applications more responsive in a world where system failures do happen (remember the <a href="https://www.geekwire.com/2017/amazon-web-services-trouble-us-east-taking-lambda-lex/">AWS outage</a> in June 2017?) and make no mistake, they will happen again because there is no single piece of hardware that can be guaranteed to be up 100% of the time.</p><p>With Hystrix, you are going to be able to do the following:</p><ul><li>Fail fast instead of queueing</li><li>Provide fallback logic when a request fails</li><li>Use real time monitoring dashboards instead of checking the logs</li><li>Take quick decisions on the services that are misbehaving</li></ul><p>As an example we are going to create a very simple REST API that returns the top grossing film for the year passed as parameter in the URL:</p><pre>&gt; curl <a href="http://resilient-movie-app.cfapps.io/movies/2015">http://localhost:8080/movies/2016</a><br>&gt; Finding Dory</pre><p>To spice things up, we are going to use a very flaky third party service that only knows the top grossing movies of the last few years, so invoking our API with an unknown year will cause the service we depend on to throw an exception that will cascade all the way to our API:</p><pre>&gt; curl <a href="http://localhost:8080/movies/1984">http://localhost:8080/movies/1984</a><br>&gt; {&quot;timestamp&quot;:1499255230949,&quot;status&quot;:500,&quot;error&quot;:&quot;Internal Server Error&quot;,&quot;exception&quot;:&quot;java.lang.IllegalArgumentException&quot;,&quot;message&quot;:&quot;Boom!&quot;,&quot;path&quot;:&quot;/movies/1984&quot;}</pre><p>Our goal is to defend our API from 3rd party failures like this one by applying the Circuit Breaker pattern in our Spring Boot app. Anytime the service will fail we will gracefully handle the exception by returning a default movie title.</p><p>Let’s build the app!</p><h4>Bootstrapping the project</h4><p>Go to <a href="http://start.spring.io/">http://start.spring.io</a> and fill in the initializer form with the following:</p><ul><li>Gradle Project with Kotlin and Spring Boot 1.5.4</li><li>Group: <em>com.example</em> (or anything you like)</li><li>Artifact: <em>resilient-movie-app</em></li><li>Selected Dependencies: <em>Circuit Breaker (PCF)</em></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mgh1t2OuQfpRWZNf1BSK0Q.png" /></figure><p>Click on “Generate Project”.</p><p>Unzip the downloaded file and open the Gradle project in your IDE.</p><h4>Adding the API Endpoint</h4><p>Go to the main class ResilientMovieAppApplication.</p><p>Annotate your app as a RestController.</p><pre>@SpringBootApplication<br>@RestController<br><strong>class</strong> ResilientMovieAppApplication {<br><br>}</pre><p>Add a GET mapping endpoint named “getTopGrossingMovie” as follows:</p><pre>@SpringBootApplication<br>@RestController<br><strong>class</strong> ResilientMovieAppApplication {<br>    @Autowired<br>    <strong>lateinit</strong> <strong>var</strong> movieService: MovieService<br><br>    @GetMapping(&quot;/movies/{year}&quot;)<br>    <strong>fun</strong> getTopGrossingMovie(@PathVariable year: Int): String {<br>        <strong>return</strong> movieService.getTopGrossingMovieByYear(year)<br>    }<br>}</pre><p>This is the API endpoint that will allow us to get the top grossing movie for a given year.</p><h4>Enabling Hystrix</h4><p>Now add the MovieService class right below:</p><pre>@Service<br><strong>class</strong> MovieService {<br>  <br>  @HystrixCommand(fallbackMethod = &quot;fallback&quot;)<br>  <strong>fun</strong> getTopGrossingMovieByYear(year: Int): String {<br>    <strong>when</strong> (year) {<br>      2016 -&gt; <strong>return</strong> &quot;Finding Dory&quot;<br>      2015 -&gt; <strong>return</strong> &quot;The Force Awakens&quot;<br>      2014 -&gt; <strong>return</strong> &quot;Guardians of the Galaxy&quot;<br>      2013 -&gt; <strong>return</strong> &quot;Iron Man 3&quot;<br>      2012 -&gt; <strong>return</strong> &quot;The Avengers&quot;<br>      <strong>else</strong> -&gt; <strong>throw</strong> IllegalArgumentException(&quot;Boom!&quot;)<br>    }<br>  }<br><br>  <strong>fun</strong> fallback(year: Int): String {<br>    <strong>return</strong> &quot;Beauty and the Beast&quot;<br>  }<br>}</pre><p>There are a few important aspects about this service.</p><ol><li>Whenever an exception is thrown because the year can’t be found, the fallback method will be automatically called and will return “Beauty and the Beast”, the top grossing movie of 2017.</li><li>Because the method is annotated with “@HystrixCommand” you won’t have to worry about timeouts; if the method takes more than 1 second to execute, Hystrix will interrupt the execution and the fallback method will be called instead. This of course is <a href="https://github.com/Netflix/Hystrix/wiki/Configuration">configurable</a>.</li><li>The fallback method must have the same exact signature than the Hystrix command, but you can call it anything you want.</li></ol><p>In order to wire-up your Hystrix command in your app, you have to tell Spring Boot to scan for Hystrix commands by adding the “@EnableCircuitBreaker” annotation to your main Spring Boot app:</p><pre><strong>import</strong> org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker</pre><pre>@SpringBootApplication<br>@RestController<br>@EnableCircuitBreaker<br><strong>class</strong> ResilientMovieAppApplication {<br>   ...<br>}</pre><p>Your app is now armed with Hystrix.</p><p>Start your application and go to <a href="http://localhost:8080/movies/2016">http://localhost:8080/movies/2016</a></p><pre>&gt; curl <a href="http://resilient-movie-app.cfapps.io/movies/2015">http://localhost:8080/movies/2016</a><br>&gt; Finding Dory</pre><p>If you provide an unknown year, the fallback method will kick in and return “Beauty and the Beast” instead of producing an error:</p><pre>&gt; curl <a href="http://resilient-movie-app.cfapps.io/movies/2015">http://localhost:8080/movies/1984</a><br>&gt; Beauty and the Beast</pre><p>As you can see, arming your app with Hystrix is quite straight forward as there is minimal plumbing to be done. For so little code the advantages are massive as suddenly adding timeouts or fallback methods becomes relatively easy.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dc9ba8733e9c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>