<?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 Niyazi Ozdinc Celikel on Medium]]></title>
        <description><![CDATA[Stories by Niyazi Ozdinc Celikel on Medium]]></description>
        <link>https://medium.com/@ozdinc-celikel?source=rss-4efa543f78f2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*9gDdgPIunLAVnPY7McGrvw.png</url>
            <title>Stories by Niyazi Ozdinc Celikel on Medium</title>
            <link>https://medium.com/@ozdinc-celikel?source=rss-4efa543f78f2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 22:10:58 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ozdinc-celikel/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[Go Tooling Essentials]]></title>
            <link>https://ozdinc-celikel.medium.com/go-tooling-essentials-7df967f02965?source=rss-4efa543f78f2------2</link>
            <guid isPermaLink="false">https://medium.com/p/7df967f02965</guid>
            <category><![CDATA[golang-tools]]></category>
            <category><![CDATA[golang-tutorial]]></category>
            <category><![CDATA[go]]></category>
            <dc:creator><![CDATA[Niyazi Ozdinc Celikel]]></dc:creator>
            <pubDate>Tue, 09 Feb 2021 18:45:34 GMT</pubDate>
            <atom:updated>2021-02-09T18:49:11.894Z</atom:updated>
            <content:encoded><![CDATA[<p>Before deep diving into <a href="https://rakyll.org/go-tool-flags/">essentials</a> of Go tooling, let’s mention some of these awesome features.</p><p><strong>Compiled language: </strong>By using <em>build </em>command, go source files are compiled to machine code. After linking process, one single file (executable) can be generated from go packages.</p><p><strong>Strongly-typed language: </strong>It’s not permitted to assign a type to variable with another type, literals and types should be in alignment.</p><p><strong>Statically-typed language:</strong> Performs type checking at <em>compile time</em>, not during runtime/execution time.</p><p><strong>Garbage Collection: </strong>Since we highly use dynamic memory allocation, <a href="https://medium.com/a-journey-with-go/go-how-does-the-garbage-collector-watch-your-application-dbef99be2c35">some metrics </a>are observed for releasing memory by cleaning unused objects in heap area.</p><p><strong>Has Pointers: </strong>By default, has pointers -I heard the “Hell Yeah!” sounds of C++ developers, btw- but has no pointer arithmetic.</p><p><strong>Concurrency Model: </strong>This is the most thrilling point. Go has its own concurrency model, which means having unique primitives for implementing it, such as <em>goroutines</em> and <em>channels</em>, which will be discussed in detail later on.</p><p><strong>Favor Composition over Inheritance: </strong>There are no class-object architecture, friend class or friend function. We have interfaces and structs for building excellent programs!</p><p>In theoretically, escape analysis is a <a href="https://people.csail.mit.edu/rinard/paper/pldi01.pdf">compiler optimization technique</a>, but in Go, it is meant as one of the stages of the compilation phase. Basically, it proposes a decision mechanism for projecting which objects will be stored on heap, which objects will be stored on stack and which of them will be <a href="https://dave.cheney.net/2020/04/25/inlining-optimisations-in-go">inlined</a> by analyzing source code. Only thing to do is passing <strong>-race </strong>flag while building/running your go package.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/577/1*2Ea5qzbPwcUlk4YixNh3Sw.png" /><figcaption><a href="https://github.com/celikelozdinc/logger/blob/main/Makefile">Escape Analysis</a></figcaption></figure><p>As stated earlier, Go has its own built-in primitives which are ready-to-use for developing concurrent applications. Let’s have a look at concurrency primitives that are mentioned above.<br><em>Goroutines </em>can be defined as<em> lightweight </em><a href="https://www.studytonight.com/operating-system/multithreading"><em>threads</em></a><em>. </em>Go implements these goroutines as <em>functions -</em>as can be seen from <a href="https://github.com/celikelozdinc/logger/blob/2e460d9923e08201893065298948d756eba74adc/cmd/main.go#L25">this</a> function<em>- </em>and maps these goroutines to operating system threads by using <a href="https://en.wikipedia.org/wiki/Thread_(computing)#M:N_(hybrid_threading)">m:n threading model</a>.<br><em>Channels </em>are synchronization primitives and can be thought as <a href="http://web.cse.ohio-state.edu/~mamrak.1/CIS762/pipes_lab_notes.html"><em>pipes</em></a><em> -Let’s s</em>ay hello to our Unix folks!<em>- </em>between goroutines.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/440/1*f54LbDNIQm40DZWxtoFSVg.png" /><figcaption><a href="https://github.com/celikelozdinc/logger/blob/main/Makefile">Race Detection Example</a></figcaption></figure><p>Golang has built-in <a href="https://golang.org/doc/articles/race_detector.html">features </a>for detecting <a href="https://yourbasic.org/golang/detect-data-races/">data races</a> on both go source and go test files, which also means detecting Concurrent Read/Concurrent Write problems beforehand.</p><p><em>Go modules</em> are the essential component which is designed for the source code distribution, we may think of a logical container of our source code which help us being ready-to-distribute/package/ship for our newly-developed components. We can remind <em>“jar packages for the Java source code” </em>here for an analogy for a better description of purpose of the usage of go modules. <br>Once we go deeper, go modules can contain one or more go packages which may indicate potential dependencies, it is highly encouraged you to have a look at this <a href="https://medium.com/swlh/semantic-version-tags-in-go-mod-file-f6ad903a972d">story</a> for a better explanation. As a best practice, it is recommended that designing packages as atomic units while designing modules as an enveloping structure for the packages. For summing up, as per Go <a href="https://github.com/golang/go/wiki/Modules">wiki</a>, while each Go module contains one or more Go packages, each Go package contains one ore more source files within a directory.</p><p>As stated above, analogy between <em>“jar packages”</em> and <em>“go modules” </em>may help us for better understanding the purpose of usage. But the point is, while there is a need for a <a href="https://www.baeldung.com/java-create-jar">compilation stage</a> for creating jar files, there are no such restriction for the go modules, if you have a bunch of files (go source files, go test files, configuration files, etc.) under your repository configured with a version control system(such as git), you may prepare a go module for distributing your repository with one or two simple steps! Go has decentralized approach once we compare to official registry/repository approach, such as PyPI(Python), npm, etc, please have a look at this <a href="https://www.makeworld.gq/2020/11/go_modules.html">article</a>. Everything you <a href="https://blog.golang.org/publishing-go-modules">committed/tagged to your upstream repository </a>by obeying the s<a href="https://semver.org/">emantic versioning rules</a> are the actual versions of your software distribution.</p><p>The first step is, initializing your go module via <em>go mod init</em> command, we can make an analogy here with the <em>git init</em> command.</p><pre>go mod init github.com/celikelozdinc/logger</pre><p>Once we initialized our module, a file named as <em>go.mod</em> is created under the project directory. Once we review this file, it indicates the import path of our module, by using this statement, other modules can import our modules by using statement <em>import github.com/celikelozdinc/logger</em></p><p>Besides this, <em>go.mod</em> also indicates the dependent modules of our logger module as indicated by <em>require</em> statement. For this <a href="https://github.com/celikelozdinc/logger/blob/main/go.mod">example</a>, <em>logger </em>module needs two different versions of <em>formatter</em> module.</p><pre>module github.com/celikelozdinc/logger</pre><pre>go 1.15</pre><pre>require (<br>github.com/celikelozdinc/formatter v1.1.0 github.com/celikelozdinc/formatter/v2 v2.0.0<br>)</pre><p>So, our module is ready. After we tagged and committed our recent changes to upstream repository, one can use the command below for injecting the dependency to her/his repository and use it as well :</p><pre>go get github.com/celikelozdinc/formatter</pre><p>To be more concrete, all these explanations aredemonstrated by <a href="https://github.com/celikelozdinc/logger/">this </a>and <a href="https://github.com/celikelozdinc/formatter">this </a>repository.</p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7df967f02965" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hands-On unit testing with Go : High Order Functions]]></title>
            <link>https://ozdinc-celikel.medium.com/hands-on-unit-testing-with-go-high-order-functions-878b44673701?source=rss-4efa543f78f2------2</link>
            <guid isPermaLink="false">https://medium.com/p/878b44673701</guid>
            <category><![CDATA[go]]></category>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[functional-programming]]></category>
            <dc:creator><![CDATA[Niyazi Ozdinc Celikel]]></dc:creator>
            <pubDate>Mon, 16 Nov 2020 18:05:25 GMT</pubDate>
            <atom:updated>2020-11-16T18:06:53.046Z</atom:updated>
            <content:encoded><![CDATA[<h3>Hands-On unit testing with Go : High Order Functions</h3><p>Have you ever heard about the term “TDD”? Did ever your “tests” failed on the pipeline on the CI server -Gitlab, Jenkins, CircleCI- ? Does your sonarqube report indicate that your line/branch coverage is lower than your company’s standards? Welcome onboard!</p><p>Writing effective unit tests is one of the most attractive topics in the <a href="https://the-report.cloud/the-age-of-devops">Age of Devops </a>and there are many approaches which explains how to handle this. This story is not aimed to review all of these, however, strictly focused on one of these approaches: <strong>high-order functions</strong>.</p><p>There is a perfect <a href="https://medium.com/cbi-engineering/mocking-techniques-for-go-805c10f1676b">article</a> which visualizes how to use this concept for writing unit tests, it is highly recommend to review <a href="https://medium.com/cbi-engineering/mocking-techniques-for-go-805c10f1676b">this </a>first. I will not be referring the Wikipedia in order to narrate what the high order functions are and how to use them, let me try to explain with my own words: declaring <strong>high order functions</strong> -which are simply, functions- which <em>uses </em>other functions by using reusable function signatures, which also means that <em>functions can be used as arguments to the functions</em>. Within the scope of this concept, a <strong>higher order function</strong> can use other functions as arguments -means accepting functions as a type- and return values.</p><p>High-order function concept is inherited from functional programming paradigm, one may have a look at this <a href="http://learnyouahaskell.com/higher-order-functions">Haskell </a>and this <a href="https://docs.scala-lang.org/tour/higher-order-functions.html">Scala</a> examples for further explanation.</p><p>So, why not use Go with high-order functions?</p><p>Go is not only a <em>strongly typed language</em>, but also a<em> multi-paradigm language</em> so that we can simply apply some of functional programming concepts, such as <a href="https://lotz84.github.io/haskellbyexample/ex/multiple-return-values">multiple return values</a>, <a href="https://www.tutorialspoint.com/functional_programming/functional_programming_function_types.htm">user-defined function types</a>, high-order functions, <a href="https://dzone.com/articles/functional-programming-recursion">recursion</a>, etc.</p><p>Enough explanation, let’s explain with a use case.</p><p>Assume that your team is heavily working on the UNIX environment and your code base consists of multiple wrapper functions of the system calls. Once you directly execute shell commands without mocking/defining interfaces for them, it will be challenging for writing unit tests that covers these lines/branches. Suppose you are removing <em>config </em>folder under /etc mountpoint during <a href="https://linux4one.com/questions/cron-job-to-auto-delete-folder-older-than-7-days-linux">crontab execution</a>, are you sure you want to permanently remove <em>/etc/config </em>folder during your unit test phase? Or, assume that you are restarting your <em>proxy service</em> within your backend service, will you be able to do same thing on your unit test execution without having necessary permissions? Really?</p><p>So what should be done in order to cover these situations?</p><p>Recipe is below, whole example can be seen on this <a href="https://gitlab.com/celikelozdinc/resizer">repository</a> which is prepared for this story:</p><p>First of all, declare a reusable function signature as a<strong> type, </strong>named as<strong> Execute</strong>:</p><pre>type (<br>	//Execute is declared as reusable function signature as type<br>	<strong>Execute </strong>func(query string) ([]byte,error)<br>)</pre><p>Define a constant variable which includes some shell commands, such as echo, fdisk :</p><pre>const <em>DeleteAndCreate </em>= &quot;echo d; echo 1; echo n; echo p; echo 1; echo; echo; echo y; echo w | sudo fdisk /dev/sda&quot;</pre><p>Then, define a new variable of this <strong>type Execute </strong>by using <a href="https://yourbasic.org/golang/anonymous-function-literal-lambda-closure/">inline functions</a>:</p><pre>var (<br>	//ExecuteOnBash implements Execute functionality<br>	ExecuteOnBash   <strong>Execute<br></strong>)</pre><pre>func init() {<br>	ExecuteOnBash = func(query string) ([]byte,error) {<br>		return exec.Command(cons.Shell, &quot;-c&quot;, query).Output()<br>	}<br>}</pre><p>Now, use this variable of<strong> type Execute</strong> as an input argument for<strong> </strong><em>ResizePartition</em> function, please take look at <a href="https://gitlab.com/celikelozdinc/resizer/-/blob/master/pkg/resizer.go">source.go</a><strong>:</strong></p><pre>func ResizePartition(execute Execute) {<br>	out, err := execute(<em>DeleteAndCreate</em>)<br>	if err != nil {<br>		fmt.Printf(&quot;Error during deleting and recreating partition table : %v&quot;, err.Error())<br>	}<br>}</pre><p>Now, this is the most thrilling part of this story. Via using the reusable function signature, one may define a new variable of <strong>type Execute</strong> and manipulate the call by extending its behaviour on <a href="https://gitlab.com/celikelozdinc/resizer/-/blob/master/pkg/resizer_test.go">source_test.go</a>:</p><pre>func Test_ResizePartition(t *testing.T) {<br>	var executeOnNowhere <strong>Execute </strong>= func(query string) ([]byte, error) {<br>		return cons.ExecResult, nil<br>	}<br>	ResizePartition(executeOnNowhere)<br>}</pre><p>For further reading, please have a look at:</p><p><a href="https://www.amazon.com/xUnit-Test-Patterns-Refactoring-Code-dp-0131495054/dp/0131495054/ref=mt_other">Unit Test Patterns</a></p><p><a href="https://golang.org/doc/codewalk/functions/">Codewalk</a></p><p><a href="https://deepu.tech/functional-programming-in-go/">Funtional Programming in Go</a></p><p>Stay healthy and be well,</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=878b44673701" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[State Machine Factories While Using Spring Statemachine]]></title>
            <link>https://ozdinc-celikel.medium.com/state-machine-factories-while-using-spring-statemachine-55bd1e963af?source=rss-4efa543f78f2------2</link>
            <guid isPermaLink="false">https://medium.com/p/55bd1e963af</guid>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[state-machine]]></category>
            <dc:creator><![CDATA[Niyazi Ozdinc Celikel]]></dc:creator>
            <pubDate>Mon, 16 Mar 2020 08:36:34 GMT</pubDate>
            <atom:updated>2020-03-16T08:36:34.258Z</atom:updated>
            <content:encoded><![CDATA[<p>This story is targeted for describing the usage and providing an concrete example for the <em>State Machine Factory</em> option in order configure/execute Java Spring statemachines with different configuration templates.</p><p>Assume that some of services/components in your application repository are highly dependent to some specific state machine <em>configurations</em>, and also, these state machines are needed to perform different tasks from each and any other -some of them might be executing I/O-aware tasks, such as opening/closing/manipulating files- so it may be good idea to isolate these statemachines from each other for conforming best practices. By using state machine factories, developers are free to create as many state machine configurations as they see fit.</p><p>Show me your code!</p><p>The only thing to do is creating multiple <em>Configuration </em>classes and injecting as beans into our service definitions.</p><p>Below, there are two different <em>Configuration</em> classes using factories:</p><pre><strong>@Configuration</strong><br><strong>@EnableStateMachineFactory(name = &quot;factory_config_1&quot;)</strong><br>public class <strong>FactoryConfiguration1</strong>  extends EnumStateMachineConfigurerAdapter&lt;States, Events&gt; {<br><br>    private Logger logger = LoggerFactory.<em>getLogger</em>(getClass());<br><br>    @PostConstruct<br>    public void init() {<br>        logger.info(&quot; ++++++++++ POSTCONSTRUCTOR FOR factory_config_1 ++++++++++&quot;);<br>    }<br><br>    @Override<br>    public void configure(StateMachineStateConfigurer&lt;States, Events&gt; states)<br>            throws Exception { ... }<br><br>    @Override<br>    public void configure(StateMachineConfigurationConfigurer&lt;States, Events&gt; config) throws Exception { ... }<br><br>    @Override<br>    public void configure(StateMachineTransitionConfigurer&lt;States, Events&gt; transitions)<br>            throws Exception { ... }<br>.....<br>}<br></pre><pre><strong>@Configuration</strong><br><strong>@EnableStateMachineFactory(name = &quot;factory_config_2&quot;)</strong><br>public class <strong>FactoryConfiguration</strong>2  extends EnumStateMachineConfigurerAdapter&lt;States, Events&gt; {<br><br>    private Logger logger = LoggerFactory.<em>getLogger</em>(getClass());<br><br>    @PostConstruct<br>    public void init() {<br>        logger.info(&quot; ++++++++++ POSTCONSTRUCTOR FOR factory_config_2 ++++++++++&quot;);<br>    }<br><br>    @Override<br>    public void configure(StateMachineStateConfigurer&lt;States, Events&gt; states)<br>            throws Exception { ... }<br><br>    @Override<br>    public void configure(StateMachineConfigurationConfigurer&lt;States, Events&gt; config) throws Exception { ... }<br><br>    @Override<br>    public void configure(StateMachineTransitionConfigurer&lt;States, Events&gt; transitions)<br>            throws Exception { ... }<br>.....<br>}</pre><p>Last step is, injecting our factories as beans<em>, getting — </em>or<em> invoking- </em>statemachines from them and starting it from scratch:</p><pre><strong>@Service</strong><br>public class StateMachineWorker {</pre><pre>@Autowired<br><strong>@Qualifier(&quot;factory_config_1&quot;)</strong><br>private StateMachineFactory&lt;States, Events&gt; <strong>factory_config_1</strong>;<br><br>@Autowired<br><strong>@Qualifier(&quot;factory_config_2&quot;)</strong><br>private StateMachineFactory&lt;States, Events&gt; <strong>factory_config_2</strong>;</pre><pre>private StateMachine&lt;States, Events&gt; <em>stateMachine</em>;</pre><pre>private Logger logger = LoggerFactory.<em>getLogger</em>(getClass());</pre><pre>@PostConstruct<br>public void init() {</pre><pre><em>stateMachine </em>= <strong>factory_config_2.getStateMachine()</strong>;<br><em>stateMachine</em>.start();<br>}</pre><pre>}</pre><p>As of now, state machine created from <em>FactoryConfiguration2 </em>is ready to process events.</p><p>You can take a look at this repository:</p><p><a href="https://github.com/celikelozdinc/StateMachineFactoryPoc">celikelozdinc/StateMachineFactoryPoc</a></p><p>Thank you for reading (:</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=55bd1e963af" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Distributed State Machines using Java Spring State Machine Framework]]></title>
            <link>https://ozdinc-celikel.medium.com/distributed-state-machines-using-java-spring-state-machine-framework-e9ff9655c486?source=rss-4efa543f78f2------2</link>
            <guid isPermaLink="false">https://medium.com/p/e9ff9655c486</guid>
            <category><![CDATA[zookeeper]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[state-machine]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[maven]]></category>
            <dc:creator><![CDATA[Niyazi Ozdinc Celikel]]></dc:creator>
            <pubDate>Sun, 05 Jan 2020 13:26:58 GMT</pubDate>
            <atom:updated>2020-01-05T13:26:58.437Z</atom:updated>
            <content:encoded><![CDATA[<p>The aim of this story is to provide a skeleton for constructing <strong><em>distributed statemachines</em></strong> via integrating Apache Zookeeper along with Java Spring State Machine framework.</p><p>Before going implementation and integration details regarding Apache Zookeeper, here is a brief introduction for Java Spring State Machine framework, reference is from current <a href="https://docs.spring.io/spring-statemachine/docs/current/reference/">documentation</a>: <em>The idea is that your application is now in and may exist in a</em><strong><em> finite number of states</em></strong><em>. Then something happens that takes your application from one state to the next. A state machine is driven by triggers, which are based on </em><strong><em>either events or timers</em></strong><em>.</em></p><p><em>Distributed</em> property for state machines comes with an <em>abstraction </em>layer on top of default state machine implementation, for the time being, only one implementation exists which is based on <strong><em>Apache Zookeeper, </em></strong>a<strong><em> </em></strong>coordination service for <strong><em>distributed applications</em></strong>. My suggestion is reading the offical Spring State Machine documentation via this <a href="https://docs.spring.io/spring-statemachine/docs/current/reference/#sm-distributed">link </a>before going deeper.</p><p>For this example, state machine will have 3 states -and obviously, will have 3 state transitions- as visualized below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/671/1*IEbvssNwP3_vBx3MZVyrJQ.png" /><figcaption>States &amp; State Transitions</figcaption></figure><p>In order to use spring-state-machine framework, <a href="https://mvnrepository.com/artifact/org.springframework.statemachine/spring-statemachine-core/2.1.3.RELEASE">maven </a>will be used for injecting required dependencies into project structure:</p><pre>&lt;dependency&gt;<br> &lt;groupId&gt;org.springframework.statemachine&lt;/groupId&gt;<br> &lt;artifactId&gt;spring-statemachine-core&lt;/artifactId&gt;<br> &lt;version&gt;2.1.3.RELEASE&lt;/version&gt;<br>&lt;/dependency&gt;</pre><p>After importing this dependency, do not forget the clean target/ directory, install project files to the local repository again and generate classes under target/ directory via maven commands below:</p><blockquote>mvn clean &amp;&amp; mvn install &amp;&amp; mvn compile</blockquote><p>On this example, there will be 4 containers which will be hosts for state machines. These containers will be orchestrated via<strong><em> docker-compose</em></strong>. 3 of the containers will execute an identical and <strong><em>distributed</em></strong> state machine, the remaining one will be host for the Apache Zookeeper binaries. While state machines are being executed in each of the containers, they all will be using the same Apache Zookeeper instance -<strong><em>znode</em></strong>- for being <strong><em>distributed</em></strong>. Hence, <strong><em>distributed </em></strong>property for state machines is established via using Apache Zookeeper. Spring has also great <a href="https://github.com/spring-projects/spring-statemachine/tree/master/spring-statemachine-samples/zookeeper">example</a> for understanding this usage.</p><p>First of all, a Spring Configuration class is needed, which is a class annotated with <strong><em>@Configuration</em></strong> and plays a role as a container for bean definitions.</p><pre>@Configuration<strong><em>  </em></strong>                     <br>public class StateMachineConfig extends EnumStateMachineConfigurerAdapter&lt;States, Events&gt; {...}</pre><p>The next to-do is configuring <strong><em>states, events </em></strong>-triggers which starts state transitions- and<strong><em> transition actions </em></strong>-triggered during action processing, you can read <a href="https://docs.spring.io/spring-statemachine/docs/current/reference/#statemachine-config-transition-actions-errorhandling">this </a>chapter- inside configuration class in order to be more concrete about “States &amp; State Transitions” picture above:</p><pre>@Override<br>public void configure(StateMachineTransitionConfigurer&lt;States, Events&gt; transitions)<br>        throws Exception {<em><br>            </em>transitions<br>            .withExternal()<br>            .source(States.<em>UNPAID</em>).<br>             target(States.<em>WAITING_FOR_RECEIVE</em>)<br>            .event(Events.<em>PAY</em>)<br>            .action(transitionAction())<br>            <br>            .and()<br>            <br>            .withExternal()<br>            .source(States.<em>WAITING_FOR_RECEIVE</em>)<br>            .target(States.<em>DONE</em>)<br>            .event(Events.<em>RECEIVE</em>)<br>            .action(transitionAction())<br>            <br>            .and()<br>            <br>            .withExternal()<br>            .source(States.<em>DONE</em>).target(States.<em>UNPAID</em>)<br>            .event(Events.<em>STARTFROMSCRATCH</em>)<br>            .action(transitionAction());<br>}</pre><p>Inside Configuration class, there is need to instantiate an ensemble, by passing<strong><em> curotorClient</em></strong> which is an API for simplifying usage of Zookeeper functionalities and <strong><em>basePath </em></strong>which indicates the base zookeeper path -which will be used for creating <strong><em>znodes</em></strong>, highly suggested to read official <a href="https://zookeeper.apache.org/doc/current/zookeeperOver.html">documentation </a>in order to get used to terminology-:</p><pre>@Bean                           <br>public StateMachineEnsemble&lt;States, Events&gt; <strong><em>stateMachineEnsemble()</em></strong> throws Exception {                                              <br>return new ZookeeperStateMachineEnsemble&lt;States, Events&gt;(<strong><em>curatorClient()</em></strong>, <strong><em>&quot;/zkPath&quot;</em></strong>);                           }</pre><p><strong><em>stateMachineEnsemble </em></strong>bean will soon be used for declaring <strong><em>distributed</em></strong> state machine in the last step.</p><p>While creating an CuratorFramework instance, IP/hostname of the machine which hosts Apache Zookeeper binaries should be known. As we stated above, docker-compose is used as orchestration tool, so that <strong><em>hostname </em></strong>of the machine which locates Apache Zookeeper is passed as environment variable. In addition to that, default port for zookeeper -which is <strong><em>2181</em></strong>-<strong><em> </em></strong>will be used<strong><em>. </em></strong>Using hostname and port information, connection string can be constructed for further purposes.</p><pre>@Bean                           <br>public CuratorFramework <strong><em>curatorClient()</em></strong> throws Exception {                               <strong><em>String zkConnectionString = &quot;zookeeper:2181&quot;;</em></strong>                               RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);                               CuratorFramework client = CuratorFrameworkFactory.builder()                                       .defaultData(new byte[0])                                       .retryPolicy(retryPolicy)                                       .connectString(zkConnectionString)                                       .build();                               <br>client.start();                               <br>CuratorFrameworkState state = client.getState();                               System.out.println(&quot;State ----&gt; &quot; + state.name());                               <br>return client;                           <br>}</pre><p>And last step, declaring <strong><em>distributed </em></strong>state machine by using <strong><em>stateMachineEnsemble</em></strong> bean which is injected as above:</p><pre>@Override                           <br>public void configure(StateMachineConfigurationConfigurer<br>&lt;States, Events&gt; config) throws Exception {</pre><pre>config                                       <br> .withDistributed()</pre><pre> .ensemble(<strong><em>stateMachineEnsemble()</em></strong>);</pre><pre>}</pre><p>When the <strong><em>zookeeper </em></strong>up and the statemachines are connected, <strong><em>znode </em></strong>can be queried either with built-in Zookeeper commands or CuratorFramework built-in methods:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/455/1*-lTTdt-HOBrPJgnha7KwQQ.png" /><figcaption>Using “ls” commands for querying</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/641/1*1mBJYmCOc76DeDO65PyL6w.png" /><figcaption>Using CuratorFramework built-in methods for querying</figcaption></figure><p>You can see the details of implementation from <a href="https://github.com/celikelozdinc/LoadBalancer/tree/development/zookeeper">this </a>link &amp; <a href="https://github.com/celikelozdinc/DistributedStateMachine/tree/development">this </a>one.</p><p>Happy new year &amp; happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e9ff9655c486" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>