<?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 Wayne Ellis on Medium]]></title>
        <description><![CDATA[Stories by Wayne Ellis on Medium]]></description>
        <link>https://medium.com/@codemwnci?source=rss-6f0e89485e0d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*cSJjHWo8qpggMlvT.jpg</url>
            <title>Stories by Wayne Ellis on Medium</title>
            <link>https://medium.com/@codemwnci?source=rss-6f0e89485e0d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 18:01:09 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@codemwnci/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[Quarkus Web Application with SvelteJS]]></title>
            <link>https://codemwnci.medium.com/quarkus-web-application-with-sveltejs-ff03bae275a9?source=rss-6f0e89485e0d------2</link>
            <guid isPermaLink="false">https://medium.com/p/ff03bae275a9</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[quarkus]]></category>
            <category><![CDATA[sveltejs]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Wayne Ellis]]></dc:creator>
            <pubDate>Fri, 24 Jan 2020 19:12:03 GMT</pubDate>
            <atom:updated>2020-01-25T21:40:23.775Z</atom:updated>
            <content:encoded><![CDATA[<h3>Quarkus Web Application with SvelteJS — Part 3</h3><h4>Adding a SvelteJS Front End</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-ro1OYsTw0dhuiYr" /><figcaption>Photo by <a href="https://unsplash.com/@rangel?utm_source=medium&amp;utm_medium=referral">David Rangel</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Introduction</h4><p>Hopefully you have been following along, and you have built a working ToDo List API, fully database backed, and with a robust unit testing framework in place too. If not, <a href="https://medium.com/@codemwnci/quarkus-web-application-with-sveltejs-6f660b926865">you may want to go back to Part 1</a>.</p><p>Let’s finish the whole thing off with a front end to make it a complete application.</p><h4>SvelteJS</h4><p>Just like I didn’t try to explain the background of Quarkus, I am not going to explain SvelteJS either. If you want to read about it, just head over to <a href="https://svelte.dev/">svelte.dev</a> to read all about it. However, what I like about Svelte is that it compiles down to native JavaScript which gives super-fast performance and hugely streamlined download size. I also find it intuitive, and favour it over the alternatives (currently at least, and I do change my mind a lot on front-end frameworks).</p><p>I used a tutorial from Freshman.tech to give a head-start building the app. If you are interested in learning Svelte in a little more detail, head over to <a href="https://freshman.tech/svelte-todo/">https://freshman.tech/svelte-todo/</a>.</p><h4>Integrating a Front End with Quarkus</h4><p>One thing to note is that Quarkus by default enforces CORS, so expects frontend requests to come from the same domain (which includes the port) of the Quarkus app. To achieve this, we can do one of a few things</p><ol><li>Copy the compiled SvelteJS application to the resources directory of the Quarkus app, so that it is served from Quarkus</li><li>Run Quarkus / SvelteJS separately, and put a reverse proxy (e.g Nginx) in front, allowing both to look like they are being served from the same.</li><li>Turn off CORS</li></ol><p>My recommendation would usually option 2, as it is reasonably straightforward, and it also allows both Quarkus and Svelte to be running in Dev mode with hot-reloading. For our app though, we will go with option 1 as it is the easiest approach and doesn’t bring another technology into play. I don’t recommend option 3, because CORS is a best practice for web applications.</p><h4>Let’s Get Started!</h4><p>Svelte uses NPM to setup and run the necessary toolset. So, at the root of our project, let’s run the following to set it up.</p><pre>npx degit sveltejs/template todo-frontend<br>cd todo-frontend/<br>npm install</pre><p>If we were using option 2 above, we could go into Dev mode now, and start hacking out our code. To do this we would run npm run dev , but we will go into our code editor, and when done create a compiled version of our app.</p><p>We need to head over to todo-frontend\src\App.svelte and open it in our editor. We won’t need to edit any other files as part of our tutorial (unless the default title bothers you, which you can modify in the public\index.html file.</p><p>A Svelte component (our app will be a single encapsulated component), has three sections within the file…the script, the style, and the main (which is where our HTML goes). Delete the contents of the App.svelte file, and add the following code.</p><pre>&lt;style&gt;<br>  .todo-list { list-style: none; margin-bottom: 20px;}<br>  .done span { text-decoration: line-through; <br>  .done .tick::before { display: inline; }<br>  .tick::before { content: &#39;✓&#39;; font-size: 20px; display: none; }<br>  .tick {<br>    width: 30px; height: 30px; border: 3px solid #333; <br>    border-radius: 50%; display: inline-flex; <br>    justify-content: center; align-items: center; cursor: pointer;<br>  }<br>  .delete-todo {<br>    border: none; background-color: transparent; outline: none; <br>    cursor: pointer;<br>  }<br>&lt;/style&gt;</pre><pre>&lt;main&gt;<br>  &lt;div class=&quot;container&quot;&gt;<br>    &lt;h1 class=&quot;app-title&quot;&gt;My Todos&lt;/h1&gt;</pre><pre>    &lt;ul class=&quot;todo-list&quot;&gt;<br>      {#each todoItems as todo}<br>        &lt;li class=&quot;todo-item {todo.completed ? &#39;done&#39; : &#39;&#39;}&quot;&gt;<br>          &lt;label class=&quot;tick&quot; on:click={() =&gt; toggleDone(todo.id)}&gt;&lt;/label&gt;<br>          &lt;span&gt;{todo.txt}&lt;/span&gt;<br>          &lt;button class=&quot;delete-todo&quot; on:click={() =&gt; deleteTodo(todo.id)}&gt; X &lt;/button&gt;<br>        &lt;/li&gt;<br>      {/each}<br>    &lt;/ul&gt;</pre><pre>    &lt;form on:submit|preventDefault={addTodo}&gt;<br>      &lt;input class=&quot;js-todo-input&quot; type=&quot;text&quot; aria-label=&quot;Enter a new todo&quot; placeholder=&quot;Enter your todo&quot; bind:value={newTodo}&gt;<br>    &lt;/form&gt;<br>  &lt;/div&gt;<br>&lt;/main&gt;</pre><p>If you are familiar with front end frameworks, this should look reasonably familiar. The styling is configured to strikethrough text and display a tick inside of the circular checkbox (a label with a radius of 50%). The CSS is set using a Handlebars style code { somelogic ? &quot;output if true&quot;:&quot;else output if false&quot; }, and events are managed in two different ways</p><ol><li>Clicking on the label or button executes a method using the on:click= approach, which then executes a function which we will create in the next bit.</li><li>When the Enter key is pressed, it executes {addTodo} as a result of the on:submit. PreventDefault prevents the Form from submitting through standard HTML. However, when the addTodo function is called, it will read the value from newTodo which has been updated automatically due to the bind:value={newTodo} . The bind value will ensure that any changes to the input is automatically updated in the value stored in the javascript. This is done by the compiled code, and not through a shadowDOM like the other popular frameworks (Angular, React, VUE), and is why Svelte is very low in memory utilisation.</li></ol><p>So now that we have our HTML and CSS code, it’s time to add our front end logic. At the top of the same file, add the following code.</p><pre>&lt;script&gt;</pre><pre>// Svelte code based on <a href="https://freshman.tech/svelte-todo/">https://freshman.tech/svelte-todo/</a><br>import { afterUpdate } from ‘svelte’;<br>import { onMount } from “svelte”;</pre><pre>let todoItems = [];<br>let newTodo = ‘’;</pre><pre>onMount(async function() {<br>  const response = await fetch(“/todos”);<br>  const json = await response.json();<br>  todoItems = json;<br>});</pre><pre>afterUpdate(() =&gt; {<br>  document.querySelector(‘.js-todo-input’).focus();<br>});</pre><pre>&lt;/script&gt;</pre><p>This code creates the two variables that we need for our app. The first is the list of the Todos, and the second is the bind variable for the input field.</p><p>The next function reads the current Todos (getAll) from our API that we created in Parts 1 and 2, and stores it in the todoItems list.</p><p>And finally, the afterUpdate function ensures that focus is returned to the input field after state is changed, so that we don’t have to keep clicking back on the input field.</p><p>Next we have to add the addTodo, toggleDone, deleteTodo functions. So, before the closing script tag, add the remaining code.</p><pre>async function addTodo() {<br>  newTodo = newTodo.trim();<br>  if (!newTodo) return;<br>  const response = await fetch(&quot;/todos&quot;, { method: &#39;POST&#39;, headers: {&#39;Content-Type&#39;: &#39;application/json&#39;}, body: newTodo });<br>  const todo = await response.json();<br>  todoItems = […todoItems, todo];<br>  newTodo = &#39;&#39;;<br>}</pre><pre>function toggleDone(id) {<br>  const index = todoItems.findIndex(item =&gt; item.id === Number(id));<br>  todoItems[index].completed = !todoItems[index].completed;<br>  update(todoItems[index])<br>}</pre><pre>async function update(todo) {<br>   const response = await fetch(&quot;/todos/&quot;+todo.id, { method: &#39;PUT&#39;, headers: {&#39;Content-Type&#39;: &#39;application/json&#39;}, body: JSON.stringify(todo) });<br>   const updatedTodo = await response.json();<br>   todo = updatedTodo;<br>}</pre><pre>async function deleteTodo(id) {<br>  const response = await fetch(&quot;/todos/&quot;+id, { method: &#39;DELETE&#39; });<br>  const success = await response.ok;<br>  if (success) todoItems = todoItems.filter(item =&gt; item.id !== Number(id));<br>}</pre><p>Again, this code should look like plain old Javascript, so there shouldn’t be too much to discuss. The addTodo function checks that there is is data, then calls a fetch statement to our Quarkus API using an HTTP POST. When the full Todo (including the ID) is returned, it is added to the todoItems list and finally the bindValue newTodo is cleared, so that we can add our next Todo.</p><p>DeleteTodo simply calls the HTTP DELETE method, again using the Fetch statement. If the response is a success, we update the list by filtering out the deleted Todo.</p><p>ToggleDone works by switching the todo.completed value and then sending this on to the update function. The update function simply takes the todo, executes an HTTP PUT, and then updating the local Todo with the response from the server. The reason for splitting the Toggle into two functions is so that if we add a future function to update the text of a todo, the update function can be shared.</p><h4>Pulling it all together</h4><p>Now that our code is written, we need to package the code, and copy it across to our Quarkus app, so that we can run it together. To do this, we need to run the following command from within the todo-frontend directory.</p><pre>npm run build</pre><p>This will compile and package the whole Svelte app. Now we just need to copy the index.html and build directory to src/main/resources/META-INF/resources and re-run the Quarkus app (mvn quarkus:dev) and our Todo App should be complete!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ff03bae275a9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Quarkus Web Application with SvelteJS]]></title>
            <link>https://codemwnci.medium.com/quarkus-web-application-with-sveltejs-673ed595a39?source=rss-6f0e89485e0d------2</link>
            <guid isPermaLink="false">https://medium.com/p/673ed595a39</guid>
            <category><![CDATA[sveltejs]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[quarkus]]></category>
            <dc:creator><![CDATA[Wayne Ellis]]></dc:creator>
            <pubDate>Fri, 24 Jan 2020 19:09:57 GMT</pubDate>
            <atom:updated>2021-04-06T11:40:14.751Z</atom:updated>
            <content:encoded><![CDATA[<h3>Quarkus Web Application with SvelteJS — Part 2</h3><h4>Adding a Database to Our Backend</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lBVgzDvTMMzMep_k" /><figcaption>Photo by <a href="https://unsplash.com/@fatosi?utm_source=medium&amp;utm_medium=referral">Fatos Bytyqi</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4><strong>Introduction</strong></h4><p>Now that we have completed the first part of our application, we will now update it to replace our ArrayList data source with a database. If you haven’t <a href="https://medium.com/@codemwnci/quarkus-web-application-with-sveltejs-6f660b926865">read part 1</a>, go back and read that first, as this section may not make as much sense!</p><h4><strong>Start the refactoring</strong></h4><p>First up, let’s update our POM.xml file to bring in the new dependencies that we are going to need.</p><pre>&lt;dependency&gt;<br>  &lt;groupId&gt;io.quarkus&lt;/groupId&gt;<br>  &lt;artifactId&gt;quarkus-jdbc-h2&lt;/artifactId&gt;<br>  &lt;scope&gt;test&lt;/scope&gt;<br>&lt;/dependency&gt;<br>&lt;dependency&gt;<br>  &lt;groupId&gt;io.quarkus&lt;/groupId&gt;<br>  &lt;artifactId&gt;quarkus-test-h2&lt;/artifactId&gt;<br>  &lt;scope&gt;test&lt;/scope&gt;<br>&lt;/dependency&gt;<br>&lt;dependency&gt;<br>  &lt;groupId&gt;io.quarkus&lt;/groupId&gt;<br>  &lt;artifactId&gt;quarkus-flyway&lt;/artifactId&gt;<br>&lt;/dependency&gt;<br>&lt;dependency&gt;<br>  &lt;groupId&gt;io.quarkus&lt;/groupId&gt;<br>  &lt;artifactId&gt;quarkus-agroal&lt;/artifactId&gt;<br>&lt;/dependency&gt;<br>&lt;dependency&gt;<br>  &lt;groupId&gt;io.quarkus&lt;/groupId&gt;<br>  &lt;artifactId&gt;quarkus-jdbc-postgresql&lt;/artifactId&gt;<br>&lt;/dependency&gt;<br>&lt;dependency&gt;<br>  &lt;groupId&gt;com.github.seratch&lt;/groupId&gt;<br>  &lt;artifactId&gt;kotliquery&lt;/artifactId&gt;<br>  &lt;version&gt;1.1.3&lt;/version&gt;<br>&lt;/dependency&gt;</pre><p>We are bringing in two test scoped dependencies (jdbc-H2 and test-H2), and four other dependencies; Flyway for managing database migrations, agroal for datasource connection pooling, postgres as our database, and kotliquery as a database client library to simplify db access.</p><p><strong>Managing the Database</strong></p><p>There are a couple of files we need to update to get the database up and running. First off, as we are using Flyway to manage our database migrations, we need to specify our database schema in a db migrations file. Flyway expects the SQL file to be in a certain format (V##__description.sql) V version_number double_underscore description .sql. The version number is any sequential number. In our case, we will be using V0.1__initial.sql.</p><p>So, create a file src/main/resources/db/migration/V0.1__initial.sql and add the following sql code.</p><pre>CREATE TABLE todo (<br>   id SERIAL PRIMARY KEY,<br>   txt VARCHAR NOT NULL,<br>   completed boolean default false<br>);</pre><p>This should represent identically the ArrayList and the AtomicLong incrementAndGet functionality we had in the first part.</p><p>Next we need to configure our database in the application.properties. Open the file src/main/resources/application.properties, and add the following.</p><pre>quarkus.datasource.url=jdbc:postgresql://localhost/todo<br>quarkus.datasource.driver=org.postgresql.Driver<br>quarkus.datasource.username=pg<br>quarkus.datasource.password=pg<br>quarkus.datasource.min-size=3<br>quarkus.datasource.max-size=13<br>quarkus.flyway.migrate-at-start=true</pre><pre>%test.quarkus.datasource.url=jdbc:h2:tcp://localhost/mem:test<br>%test.quarkus.datasource.driver=org.h2.Driver<br>%test.quarkus.flyway.migrate-at-start=true</pre><p>The final 3 lines configures an H2 database when running in test mode.</p><p>The first 7 lines set up a link to a local postgres database, with a user / password of pg / pg, a connection pool of 3–13, and flyway set up to load the SQL schema on application start up.</p><p>This assumes you have a running local instance of postgres. If you don’t, then my usual approach is to use Docker to give me a temporary database to get up and running. If you want to try this approach, you should be able to run the following command (assuming you have docker installed)</p><pre>docker run -it --rm --name pg-docker -e POSTGRES_USER=pg -e POSTGRES_PASSWORD=pg -e POSTGRES_DB=todo -p 5432:5432 postgres</pre><p><strong>Updating the TodoService</strong></p><p>That’s it for all the additional files, so we will only be updating the TodoService.kt and TodoServiceTest.kt from here on in.</p><p>Open up the TodoService.kt file and add the following to the imports.</p><pre>import kotliquery.*<br>import javax.inject.Inject<br>import javax.enterprise.inject.Default<br>import javax.sql.DataSource</pre><p>Next, delete the todos ArrayList, idSeq AtomicLong and createTodo function, and replace it with the following to setup the datasource.</p><pre>@Inject<br>@field: Default<br>lateinit var ds: DataSource</pre><p>Quarkus uses CDI to inject the datasource into our application based on the properties that we set up in the application.properties. We will use this datasource when accessing the database to run SQL statements as we modify our endpoints.</p><p>Lets start updating the application one requirement at a time.</p><p><strong>Req#1: List all Todos</strong></p><p>Update the getAll function to look as follows</p><pre>fun getAll() = using(sessionOf(ds)) { session -&gt;<br>   session.run(queryOf(&quot;SELECT id, txt, completed FROM todo&quot;).map {<br>      row -&gt; Todo(row.long(&quot;id&quot;), row.string(&quot;txt&quot;), row.boolean(&quot;completed&quot;))<br>   }.asList)<br>}</pre><p>Most of this code is Kotliquery specific. If you want to learn more about this, you can read about it at the Kotliquery GitHub page (<a href="https://github.com/seratch/kotliquery">https://github.com/seratch/kotliquery</a>). The important part is the query code, which then maps each “row” to a Todo object, and then returns a list. The list is automatically converted to JSON and returned as per the previous implementation.</p><p><strong>Req#2: Get a single Todo</strong></p><p>Update the getOne function to look as follows</p><pre>fun getOne(@PathParam(&quot;id&quot;) id: Long) = using(sessionOf(ds)) { session -&gt;<br>   session.run(queryOf(&quot;SELECT id, txt, completed FROM todo WHERE id=?&quot;, id).map {<br>      row -&gt; Todo(row.long(&quot;id&quot;), row.string(&quot;txt&quot;), row.boolean(&quot;completed&quot;))<br>   }.asSingle)<br>}</pre><p>This update is almost identical to the getAll function, with the exception of the WHERE clause and the asSingle collector instead of asList. Note that the queryOf function takes the id as a parameter. The queryOf function signature is (sqlStatement, varargs). If there were more than one bind variables (Placeholders labelled ?), each parameter would be comma separated.</p><p><strong>Req#3:Create a Todo</strong></p><p>Update the addOne function to look as follows</p><pre>fun addOne(txt: String): Todo? {<br>   val newId: Long? = using(sessionOf(ds, true)) { session -&gt;<br>      session.run(queryOf(&quot;INSERT INTO todo (txt) VALUES (?)&quot;, txt).asUpdateAndReturnGeneratedKey )<br>   }</pre><pre>   return if (newId != null) getOne(newId) else null<br>}</pre><p>With this update, we again are using queryOf to execute a SQL query, but we are not using a map, instead we are using an asUpdate. To ensure we get the complete Todo, we get the generated autonumber (id SERIAL) by returning the generated key (asUpdateAndReturnGeneratedKey).</p><p>Once we have the ID, we use this to lookup the Todo by calling the GetOne function we created in requirements 2. The main advantage of this approach is that the default values set at the database level (completed == false, for example) will be returned by retrieving the full Todo from the database by the ID.</p><p><strong>Req#4: Delete a Todo</strong></p><p>Replace the deleteOne function with the below code.</p><pre>fun deleteOne(@PathParam(&quot;id&quot;) id: Long) =<br>   using(sessionOf(ds)) { session -&gt; session.run(queryOf(&quot;DELETE FROM todo WHERE id=?&quot;, id).asUpdate)} == 1</pre><p>This is the simpler of the updates in this section. We simply execute a DELETE statement, passing in the ID, and execute as an update. Much of this logic we have already encountered before, so there is no need to focus on it. The asUpdate executor is new, but is very similar to the asUpdateAndReturnGeneratedKey, except we simply update and return the affected row count. We are expecting a single row deleted, and therefore a row count of 1, so we complete the function with == 1, which will return true if only a single row is deleted, or false otherwise.</p><p><strong>Req#5: Update Todo</strong></p><p>And finally, lets update our final function.</p><pre>fun updateOne(@PathParam(&quot;id&quot;) id: Long, todo: Todo): Todo? {<br>   using(sessionOf(ds)) { session -&gt;<br>      session.run(queryOf(&quot;UPDATE todo SET txt=?, completed=? WHERE id=?&quot;, todo.txt, todo.completed, id).asUpdate) }<br>   return getOne(id)<br>}</pre><p>This update is slightly more involved, so lets deconstruct it. First of all, we are passing in both a PathParam, and a JSON representation of the Todo (which will auto convert into a Todo object). We the execute an UPDATE SQL statement, passing in three parameters to replace the bind variables. Finally we execute the whole thing using the asUpdate executor.</p><p>Just like in Req#3, once we have updated the Todo, we then return the Todo by calling the GetOne function to retrieve the Todo from the database.</p><p>The main application is now updated. So let’s go ahead and test it to make sure it is all working as expected.</p><p><strong>Manual Testing</strong></p><p>If you want to manually test, until we write our front-end app, use the same cURL commands as used in Part 1.</p><p><strong>Automatic Testing</strong></p><p>Now lets head back over to our test class, /src/test/kotlin/codemwnci/TodoServiceTest.kt</p><p>First off, let’s get the additional imports sorted.</p><pre>import org.junit.jupiter.api.BeforeEach<br>import kotliquery.*<br>import javax.inject.Inject<br>import javax.enterprise.inject.Default<br>import javax.sql.DataSource<br>import org.flywaydb.core.Flyway<br>import io.quarkus.test.common.QuarkusTestResource<br>import io.quarkus.test.h2.H2DatabaseTestResource</pre><p>And next add the annotations above the class definition</p><pre>@QuarkusTestResource(H2DatabaseTestResource::class)</pre><p>This annotation will ensure the H2 database is started alongside the test suite, just like the postgres database would be started on application startup.</p><p>First, to improve our tests, we will split the tests into multiple unit. To do this, we need to clear the clear down the database before each test is run so that we are starting with a clean database. However, it is not enough to simply delete the data, because we also need to reset the ID sequence to start at 1. We are using Flyway to manage our database, and it provides a convenient API to allow us to delete and recreate the database, so let’s inject Flyway into our test suite, and create a BeforeEach function to to do just that.</p><pre>@Inject<br>lateinit var flyway: Flyway;</pre><pre>// Create the DB structure before each test<br>@BeforeEach<br>fun dropAndRecreate() {<br>   flyway.clean()<br>   flyway.migrate()<br>}</pre><p>Our final piece of test setup is a simple function to add some test todos directly to the database. This is so that we are not reliant on the addTodo REST endpoint, and as such can be confident that each unit test is self contained.</p><pre>@Inject<br>@field: Default<br>lateinit var ds: DataSource<br>fun addTestTodos(vararg todos: String) {<br>   using(sessionOf(ds)) { session -&gt;<br>      for(todo in todos) {<br>         session.run(queryOf(&quot;INSERT INTO todo (txt) VALUES (?);&quot;, todo).asUpdate)<br>      } <br>   }<br>}</pre><p>This function will iterate through a list of strings, and create a new todo for each string. We will use this function in some of the tests coming up.</p><p>Next, delete the one existing test that we created, and then add the following test.</p><pre>@Test<br>fun testEmptyTodoList() {<br>  <br>given().`when`().get(“/todos”).then().statusCode(200).body(containsString(&quot;[]&quot;))<br>}</pre><p>This will simply test that when the database is empty, calling the getAll REST endpoint.</p><p>Our next test will test that we can add a new todo, and then retrieve it as a getAll.</p><pre>@Test<br>fun testAdd() {</pre><pre>   // TEST THE POST RETURNS A SINGLE JSON<br>   given().body(&quot;test todo&quot;).`when`()<br>.post(&quot;/todos&quot;).then().statusCode(200)<br>.body(containsString(&quot;test todo&quot;), containsString(&quot;&quot;&quot;{&quot;id&quot;:1,&quot;txt&quot;:&quot;test todo&quot;,&quot;completed&quot;:false}&quot;&quot;&quot;))</pre><pre>   // TEST GET NOW RETURNS AN ARRAY WITH A SINGLE ITEM<br>   given().`when`().get(&quot;/todos&quot;).then().statusCode(200)<br>.body(containsString(&quot;&quot;&quot;[{&quot;id&quot;:1,&quot;txt&quot;:&quot;test todo&quot;,&quot;completed&quot;:false}]&quot;&quot;&quot;))<br>}</pre><p>Our next test will add two todos to the database using the database function we created specifically for this test harness, and then we will retrieve the first todo using the GetOne REST endpoint. We will test that the returned todo contains the expected JSON, and does NOT contain data from the second todo.</p><pre>@Test<br>fun testGetOne() {<br>   addTestTodos(&quot;number1&quot;, &quot;test 2&quot;)<br>   given().`when`().get(&quot;/todos/1&quot;).then().statusCode(200)<br>.body(containsString(&quot;&quot;&quot;{&quot;id&quot;:1,&quot;txt&quot;:&quot;number1&quot;,&quot;completed&quot;:false}&quot;&quot;&quot;), not(containsString(&quot;test 2&quot;)))<br>}</pre><p>Our next test will confirm the delete functionality. Once again we will add a few todos, confirm the first todo is in the returned list, then delete the todo through the REST endpoint confirming that the deletion was successful, and then finally, rechecking the list to ensure it isn’t returned on the after-deletion request.</p><pre>@Test<br>fun testDelete() {<br>   addTestTodos(&quot;number1&quot;, &quot;test 2&quot;)<br>   // confirm the item is there<br>   given().`when`().get(&quot;/todos&quot;).then().statusCode(200).body(containsString(&quot;number1&quot;))</pre><pre>// delete the todo, and confirm true is returned<br>given().`when`().delete(&quot;/todos/1&quot;).then().statusCode(200).body(containsString(&quot;true&quot;))</pre><pre>// confirm the item is no longer there, and is therefore deleted<br>given().`when`().get(&quot;/todos&quot;).then().statusCode(200).body(not(containsString(&quot;number1&quot;)))</pre><pre>}</pre><p>To wrap up our testing, we simply need to test the update functionality. The update should confirm that the Todo can be updated (both the text and completed flag), but that the ID cannot be updated. We’ll use the same method to add a few todos initially, confirm the todo is in the list, update the todo, confirm todo has been updated, and finally confirm the ID has not been updated.</p><pre>@Test</pre><pre>fun testUpdate() {</pre><pre>   addTestTodos(&quot;number1&quot;, &quot;test 2&quot;)<br>   // confirm the item is there<br>given().`when`().get(&quot;/todos&quot;).then().statusCode(200).body(containsString(&quot;number1&quot;))</pre><pre>   // confirm it returned the updated details<br>given().contentType(&quot;application/json&quot;).body(&quot;&quot;&quot;{&quot;id&quot;:1,&quot;txt&quot;:&quot;1_isupdated_to_number2&quot;,&quot;completed&quot;:true}&quot;&quot;&quot;)<br>.`when`().put(&quot;/todos/1&quot;).then().statusCode(200)<br>.body(not(containsString(&quot;number1&quot;)), containsString(&quot;1_isupdated_to_number2&quot;), containsString(&quot;true&quot;))</pre><pre>   // confirm it returns from get as expected<br>given().`when`().get(&quot;/todos&quot;).then().statusCode(200).body(containsString(&quot;1_isupdated_to_number2&quot;))</pre><pre>   // make sure we cant change the ID and that it returned the updated details<br>given().contentType(&quot;application/json&quot;).body(&quot;&quot;&quot;{&quot;id&quot;:1111,&quot;txt&quot;:&quot;1_isupdated_to_number3&quot;,&quot;completed&quot;:true}&quot;&quot;&quot;)<br>.`when`().put(&quot;/todos/1&quot;).then().statusCode(200)<br>.body(not(containsString(&quot;number1&quot;)), not(containsString(&quot;1111&quot;)))</pre><pre>   // confirm it returns fron getAll as expected<br>   given().`when`().get(&quot;/todos&quot;).then().statusCode(200)<br>.body(containsString(&quot;&quot;&quot;{&quot;id&quot;:1,&quot;txt&quot;:&quot;1_isupdated_to_number3&quot;,&quot;completed&quot;:true}&quot;&quot;&quot;))</pre><pre>}</pre><p><strong>Finally</strong></p><p>And that’s it for Part 2. We now have a database backed version of our Todo list application, with an in-memory database used for testing and a decent set of tests to run against our API.</p><p>Next up, we’ll finish the whole thing off with a SvelteJS based front end to make use of our REST API. <a href="https://medium.com/@codemwnci/quarkus-web-application-with-sveltejs-ff03bae275a9">Continue on to Part 3.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=673ed595a39" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Quarkus Web Application with SvelteJS]]></title>
            <link>https://codemwnci.medium.com/quarkus-web-application-with-sveltejs-6f660b926865?source=rss-6f0e89485e0d------2</link>
            <guid isPermaLink="false">https://medium.com/p/6f660b926865</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[quarkus]]></category>
            <dc:creator><![CDATA[Wayne Ellis]]></dc:creator>
            <pubDate>Fri, 24 Jan 2020 19:07:49 GMT</pubDate>
            <atom:updated>2020-01-25T21:37:09.038Z</atom:updated>
            <content:encoded><![CDATA[<h3>Quarkus Web Application with SvelteJS — Part 1</h3><h4>The Quarkus Backend</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Lnc-G63lFQtr9yb8" /><figcaption>Photo by <a href="https://unsplash.com/@emilep?utm_source=medium&amp;utm_medium=referral">Émile Perron</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4><strong>Welcome</strong></h4><p>This will be a 3 part series demonstrating how to build a Quarkus application, using Kotlin. In part 3, we will put a front end on to our application, which will be written in SvelteJS.</p><p>This blog series will be broken down into the following sections.</p><ol><li>Setting up and building a basic ToDo List application (no database) with tests.</li><li>Add a database (postgres), and in memory test DB (H2), db migrations (flyway)</li><li>Add a front end using SvelteJS</li></ol><h4><strong>Why Quarkus?</strong></h4><p>I am going to assume you already know what Quarkus is. If you don’t, head over to the <a href="http://quarkus.io/">Quarkus.io</a> homepage and have a read. It does a far better job at describing why it exists than I can do here, but for my reasons, I was looking to find a web framework that had the same enjoyment factor as Playframework 1.x, but with a Cloud / Container first approach, with a target for a super-small memory footprint to limit cost of running webservices/microservices in the cloud. Safe to say, with Quarkus’s live reloading capability and super-fast start-up times (and more), it meets my playframework tick. With native compilation using the GraalVM target, the memory footprint is impressively low and can easily run in docker, giving me my second requirement fulfilled.</p><h4><strong>Let’s get started</strong></h4><p>To get started with Quarkus, all you need installed is Java and Maven.</p><p><em>GraalVM is optional and I am not going to cover that here. There are plenty of tutorials around, but if you are using linux or linux subsystem on windows, checkout sdkman for easy setup.</em></p><p>To get started, we are going to use a maven archetype to create the template for our application.</p><pre>mvn io.quarkus:quarkus-maven-plugin:1.1.1.Final:create -DprojectGroupId=codemwnci -DprojectArtifactId=todo-rest-demo -DclassName=&quot;codemwnci.TodoService&quot; -Dpath=&quot;/todos&quot; -Dextensions=&quot;kotlin,resteasy-jackson&quot;</pre><p>So, we have chosen the Quarkus maven plugin 1.1.1.Final:create archetype. The projectArtifactId will be the name of the directory created, and the classname will be the name of the Kotlin file created that will contain the initial demo code, with a Rest path accessed via “/todos”. Two extensions have been chosen, firstly Kotlin (which will make sure the maven structure is kotlin specific and the TodoService class is a Kotlin file. We will also include resteasy-jackson, rather than using jsonb. (Note: in previous versions we would have had to also add kotlin-jackson to our POM before running, but this is now included from 1.1.1 onwards).</p><p>Once you have run the command, the project should be created, and we are ready to start.</p><p>If you just want to see the default app running, you can do the following</p><pre>cd todo-rest-demo<br>mvn compile quarkus:dev</pre><p>This will run the application in dev mode. Go to <a href="http://localhost:8080/todos">http://localhost:8080/todos</a> to see the Hello world greeting.</p><h4><strong>The Todo App</strong></h4><p>Let’s start with the following requirements for our ToDo App.</p><ol><li>List the todos</li><li>Retrieve a single todo</li><li>Create a todo</li><li>Delete a todo</li><li>Update a todo (mark as completed)</li></ol><p>So this will translate to a typical REST service with the following REST endpoints</p><ol><li>GET /todos</li><li>GET /todos/{id}</li><li>POST /todos &lt;body text will be the todo description&gt;</li><li>DELETE /todos/{id}</li><li>PUT /todos/{id} &lt;body text will be JSON representation of the Todo&gt;</li></ol><p>The ToDo itself will be represented by an entity that contains</p><ul><li>ID: Long</li><li>txt: String</li><li>completed: Boolean</li></ul><p>We now have everything we need to construct our application.</p><p>Let’s start with the Todo entity, and the mechanisms to save to a datastore (in this section represented by an arraylist until replaced by a DB in the next section).</p><p>Open the file src/main/kotlin/codemwnci/TodoService</p><p>First off, delete the hello world function.</p><p>Just below the TodoService class definition, add the following code</p><pre>class Todo(var id: Long = 0L, val txt: String = &quot;&quot;, val completed: Boolean = false)</pre><pre>val idSeq: AtomicLong = AtomicLong()<br>fun createTodo(txt: String): Todo = Todo(idSeq.incrementAndGet(), txt)<br>val todos: ArrayList&lt;Todo&gt; = ArrayList()</pre><p>Also add the following import</p><pre>import java.util.concurrent.atomic.AtomicLong;</pre><p>We now have an arraylist we can interact with for our REST endpoints, and a createTodo function that will ensure we generate sequential Ids (in place of not having a DB that would otherwise do the job for us). Apart from the Todo class, this code will be removed when we create our database.</p><p><strong>NOTE</strong>: having default values, and the properties marked as VAR may look odd. I typically would mark as VAL and only have default values for completed (because I would want it to default to false), but there is a bug in the native compiler that causes Jackson JSON parsing to fail if not configured in this way. If you are using a version greater than 1.1.1.Final, check <a href="https://github.com/quarkusio/quarkus/issues/3954">https://github.com/quarkusio/quarkus/issues/3954</a> to see if the bug has been fixed.</p><p>Next step will be to implement the different endpoints.</p><p>Quarkus identifies endpoints using standard JAX-RS annotations. Let’s take our requirements one at a time. Place the following code underneath the arraylist we created above.</p><h4>Requirement 1: List all Todos</h4><pre>@GET<br>@Produces(MediaType.APPLICATION_JSON)<br>fun getAll() = todos</pre><p>Hopefully this is fully self-explanatory. The function getAll -the function name doesn’t matter, but its useful to be descriptive- simply returns the list of todos. It responds via a GET on the root path of the service (/todos is set up at the TodoService Class level by the @Path annotation. This was done automatically by the maven archetype).</p><p>The produced annotation specifies we are using JSON, and therefore Jackson is used to automatically serialise the list of Todos into a JSON string.</p><h4>Requirement 2: Get a single todo</h4><pre>@GET<br>@Path(&quot;/{id}&quot;)<br>@Produces(MediaType.APPLICATION_JSON)<br>fun getOne(@PathParam(&quot;id&quot;) id: Long) = if (!todos.isEmpty()) todos.first { it.id == id } else null</pre><p>This is slightly more complex, but not much. Again we are using a GET request, but we are looking for an ID in the path, e.g. /todos/1. We pass the path parameter into the function as a parameter, by specifying the PathParam annotation, and then returning the first Todo in the list where the passed in ID matches (if you are new to Kotlin, it is the variable used in lambda functions when there is only a single parameter, and the parameter is otherwise omitted, it is equivalent of writing todos.first {item: Todo -&gt; item.id == id}). The if statement check is to prevent NoSuchElementException being thrown if first is called on an empty list.</p><h4>Requirement 3: Create a Todo</h4><pre>@POST<br>@Produces(MediaType.APPLICATION_JSON)<br>fun addOne(txt: String): Todo {<br>   val todo = createTodo(txt)<br>   todos.add(todo)<br>   return todo<br>}</pre><p>This again is pretty straightforward. The text of the Todo is passed in the body of the Todo. If the body was a JSON object, it would be converted into the target object (we’ll see that in requirement 5), but as we are accepting just plain text, then no conversion is needed nor do we need any annotations.</p><p>We use the txt value to create a Todo using the createTodo function we wrote at the start of the tutorial (this will ensure we have a sequential ID), then add the Todo to the list, and return the Todo as the output. The return will automatically convert the Todo to a JSON string, with the content encoding set as Application-Json, based onthe @Produces annotation.</p><h4>Requirement 4: Delete a Todo</h4><pre>@DELETE<br>@Path(&quot;/{id}&quot;)<br>@Produces(MediaType.APPLICATION_JSON)<br>fun deleteOne(@PathParam(&quot;id&quot;) id: Long) = todos.remove( todos.first { it.id == id } )</pre><p>This function is almost the same as the GET function we created for requirement 2. We use @DELETE instead of @GET, but we use the same path, path param, and we find the todo from the list using the ArrayList.first function. From the Todo retrieved from the list, this is passed to the ArrayList.remove() function to remove it from the list.</p><h4>Requirement 5: Update Todo</h4><pre>@PUT<br>@Path(&quot;/{id}&quot;)<br>@Produces(MediaType.APPLICATION_JSON)<br>fun updateOne(@PathParam(&quot;id&quot;) id: Long, todo: Todo): Todo? {<br>   deleteOne(id)<br>   todos.add(todo)<br>   return todo<br>}</pre><p>This time we are using @PUT, and passing in both a PathParam and JSON body. The JSON body is automatically converted by Jackson from the String body to the Todo object.</p><p>We use the path parameter to then call our deleteOne function, then add the updated Todo back to the list, and finally returning the Todo as output.</p><h4><strong>Manually Testing our Service using cURL</strong></h4><p>To manually test our application, if it isn’t already started, run the application with mvn quarkus:dev.</p><p>We can then use cURL to test our rest endpoints. There are other options you can use, like Postman, but cURL is nice and simple. If you are running on Windows (like me), I tend to use the Windows Subsystem for Linux, by installing Ubuntu from the Windows Store, giving you access to cURL and much much more.</p><p>Let’s take a look at our 5 requirements again, and then the cURL commands we need to test each one.</p><p><strong>Req#1: List All</strong></p><pre>curl <a href="http://localhost:8080/todos">http://localhost:8080/todos</a></pre><p><strong>Req#2: Get One</strong></p><pre>curl <a href="http://localhost:8080/todos/1">http://localhost:8080/todos/1</a></pre><p><strong>Req#3: Add One</strong></p><pre>curl -d &#39;my todo&#39; -H &quot;Content-Type: application/json&quot; -X POST <a href="http://localhost:8080/todos">http://localhost:8080/todos</a></pre><p><strong>Req#4: Delete</strong></p><pre>curl -X DELETE <a href="http://localhost:8080/todos/1">http://localhost:8080/todos/1</a></pre><p><strong>Req#5: Update</strong></p><pre>curl -d &#39;{&quot;id&quot;:1,&quot;txt&quot;:&quot;my updated todo&quot;,&quot;completed&quot;:true}&#39; -H &quot;Content-Type: application/json&quot; -X PUT <a href="http://localhost:8080/todos/1">http://localhost:8080/todos/1</a></pre><p>If you run the cURL commands in order, you won’t get anything from the #1 and #2 because the arraylist is empty. Also, you will get an error if you run #5 because the Todo will have been deleted. Therefore, use the commands as a reference, and try them out in a sensible order to confirm the application is behaving as you would expect. E.g.</p><p>Check Empty (#1), Add one (#3), Check not empty (#1), Get 1 (#2), Update todo (#5), Check is update (#2), Delete Todo (#4), Check Empty (#1), Check can’t now retrieve single todo (#2).</p><p>And that should give you everything you need to manually test. However, that’s not great for modifying your application and checking you haven’t broken anything. That’s a lot of manual work to repeat every change you make. So, lets make some automated tests to do something similar.</p><h4><strong>Unit Testing our Service using RestEasy</strong></h4><p>By default (if you used the maven archetype), Quarkus will have generated a Test class, configured with RestEasy. Go to src/test/kotlin/codemwnci/TodoServiceTest.kt, and take a look at the code.</p><p>Delete the default test that was generated, and replace it with</p><pre>@Test<br>fun testTodos() {<br>   given().`when`().get(&quot;/todos&quot;).then().statusCode(200).body(containsString(&quot;[]&quot;))<br>}</pre><p>And make sure you add the following imports</p><pre>import org.hamcrest.CoreMatchers.containsString;<br>import org.hamcrest.core.IsNot.not;</pre><p>This test will test that if we call the URL /todos, which is our getAll, we return an empty JSON list.</p><p>One thing to note as we build up our test suite, is that we cannot guarantee the order that the tests are run. When we move on to the database section of this tutorial, I will show how we can clean-down the in-memory database before each test run, but for now, we will have to run all our tests inside a single @Test function.</p><p>Update the function to now look like the following.</p><pre>@Test<br>fun testTodos() {<br>   // Check Empty (#1)<br>   given().`when`().get(&quot;/todos&quot;).then().statusCode(200).body(containsString(&quot;[]&quot;))<br>   // Add one (#3)<br>   given().body(&quot;test todo&quot;).`when`().post(&quot;/todos&quot;).then().statusCode(200).body(containsString(&quot;test todo&quot;), containsString(&quot;&quot;&quot;{&quot;id&quot;:1,&quot;txt&quot;:&quot;test todo&quot;,&quot;completed&quot;:false}&quot;&quot;&quot;))<br>   // Check not empty (#1)<br>   given().`when`().get(&quot;/todos&quot;).then().statusCode(200).body(not(containsString(&quot;[]&quot;)))<br>   // Get 1 (#2)<br>   given().`when`().get(&quot;/todos/1&quot;).then().statusCode(200).body(containsString(&quot;test todo&quot;))<br>   // Update todo (#5)<br>   given().contentType(&quot;application/json&quot;).body(&quot;&quot;&quot;{&quot;id&quot;:1,&quot;txt&quot;:&quot;real todo&quot;,&quot;completed&quot;:true}&quot;&quot;&quot;).`when`().put(&quot;/todos/1&quot;).then().statusCode(200).body(not(containsString(&quot;test&quot;)), containsString(&quot;real&quot;), containsString(&quot;true&quot;))<br>   // Check is updated (#2)<br>   given().`when`().get(&quot;/todos/1&quot;).then().statusCode(200).body(containsString(&quot;real todo&quot;))<br>   // Delete Todo (#4)<br>   given().`when`().delete(&quot;/todos/1&quot;).then().statusCode(200).body(containsString(&quot;true&quot;))<br>   // Check Empty (#1)<br>   given().`when`().get(&quot;/todos&quot;).then().statusCode(200).body(containsString(&quot;[]&quot;))<br>   // Check can’t now retrieve single todo (#2)<br>   given().`when`().get(&quot;/todos/1&quot;).then().statusCode(204)<br>}</pre><p>The tests should test the same order of manual tests that we carried out in manual testing section. I am not going to go into this in detail, as I hope the tests themselves should be self explanatory. One note on status code 204 means No Content, which is what is expected if nothing (null) is returned from our GET request.</p><p>To run the tests, you can use mvn test. The tests will also run when mvn package is executed.</p><h4><strong>Finally</strong></h4><p>And that is it. Part 1 complete. A simple REST service, written in Kotlin using the Quarkus framework.</p><p><a href="https://medium.com/@codemwnci/quarkus-web-application-with-sveltejs-673ed595a39">In part 2</a>, I will add a database and update the code to use the database instead of the ArrayList. This will include adding an in memory database for the unit testing.</p><p><a href="https://medium.com/@codemwnci/quarkus-web-application-with-sveltejs-ff03bae275a9">In part 3</a>, I will add a front end application to make use of the service, instead of the cURL.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6f660b926865" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dockerised Kotlin Web App]]></title>
            <link>https://codemwnci.medium.com/dockerised-kotlin-web-app-956c08cbfc42?source=rss-6f0e89485e0d------2</link>
            <guid isPermaLink="false">https://medium.com/p/956c08cbfc42</guid>
            <category><![CDATA[web-app-development]]></category>
            <category><![CDATA[maven]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Wayne Ellis]]></dc:creator>
            <pubDate>Thu, 27 Dec 2018 20:58:07 GMT</pubDate>
            <atom:updated>2018-12-27T20:58:07.929Z</atom:updated>
            <content:encoded><![CDATA[<h4>Build and run with a simple Dockerfile</h4><h4>TL:DR</h4><p>Just jump to the Dockerfile code, the comments hopefully make it self explanatory. It is a multi-stage Dockerfile that builds using a Maven Image and then runs using a Java image.</p><h4>Longer version</h4><p>I have been developing with Kotlin for a while now, but these have all been for personal projects. I decided it was time I learned how to use Docker, especially as I am getting more and more into Google Cloud and want to explore using Kubernetes Engine. There were a few things I noticed when learning how to use Docker with Kotlin Web Apps: <br>1: there aren’t many examples, <br>2: the examples are all about running apps that have already been built and not build and run (which I wanted to use Docker so the entire development lifecycle was portable).</p><p>So, my goal was to create a Multi-Stage Dockerfile that used Maven to build my web app, and then run the web app.</p><p>Below is the Dockerfile, which I will explain how / why I have created this way. Note: This is me learning how to use Docker, it may not be the best approach, so let me know if you have some advice to make this better.</p><p>This expects a directory structure like the following</p><pre> ./Dockerfile<br> ./pom.xml<br> ./src/main/kotlin/<br> ./src/main/resources/public/</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/47acd64cceabc5abb2bdc2a968f25295/href">https://medium.com/media/47acd64cceabc5abb2bdc2a968f25295/href</a></iframe><p>The Dockerfile is split into two parts, with Part 1 being responsible for Build, and Part 2 being responsible for Run.</p><h4>Part 1 — Build</h4><p>I have split the Build stage into two parts. First, I only add the POM.xml file, and then run the mvn verify clean which will download all the dependencies. This means that if the POM file does not change, the dependencies won’t download each time (this was what was happening to begin with and was getting to be a bit of a pain).</p><p>I then add the rest of the files and run the package command. This assumes your POM file has the package stage that builds a JAR file. I am using the maven-assembly-plugin, which by default creates a fat-jar in the format ([artefact-id]-[version]-jar-with-dependencies.jar).</p><h4>Part 2 — Run</h4><p>Now the build is out of the way, we start the run phase. Using the OpenJDK docker image as a base, we copy the JAR we created at the end of part 1, and name it app.jar.</p><p>We then run java -jar ./app.jar to run the packaged application.</p><h3>Where’s the Kotlin Web App Code?</h3><p>I haven’t included it here, as I ran a very simple SparkJava application that simply returned a test response. My other Medium posts and Github pages are suitable examples to use however.</p><h3>Using the Dockerfile</h3><p>Now, to run the whole thing, we just run</p><p>docker build -t imagename:version .</p><p>Replace imagename with the name of your app, and version is just a unique identifier for you to increment your version numbers.</p><p>Then to run, we do</p><p>docker run -it --rm --expose=9000 -p 9000:9000 imagename:version</p><p>-it Runs docker in interactive mode, rather than in the background. This means that when you Ctrl+C, the container will shutdown so you can modify your code, and re-run when you are ready.</p><p>--rm This removes the docker image once finished. I generally find for running an app, it is unnecessary to keep the run image around after it has finished, and this saves space.</p><p>--expose=portnumber exposes a port number from within the container. For my Kotlin Web App, I was running on port 9000, so to be able to access port 9000 on the container, we need to expose the port. This could be done inside of the Dockerfile itself as an EXPOSE directive.</p><p>-p 9000:9000 This sets the port 9000 on the local machine to map to port 9000 on the container. It is possible from here to map a different local port to the container port. This can be useful when running multiple instances of the same app (for load-balancing).</p><h3>Feedback</h3><p>As I mentioned, I am no Docker expert, so feel free to offer advice on how to improve this, but I certainly achieved my goal of having a maven based build process (without needing to install maven), and without having to download maven dependencies each time, and then able to run the built application from the same Docker process.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=956c08cbfc42" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kotlin on Google Cloud Platform]]></title>
            <link>https://codemwnci.medium.com/kotlin-on-google-cloud-platform-dd1a51e5417b?source=rss-6f0e89485e0d------2</link>
            <guid isPermaLink="false">https://medium.com/p/dd1a51e5417b</guid>
            <category><![CDATA[kotlin-server-programming]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Wayne Ellis]]></dc:creator>
            <pubDate>Sat, 27 Oct 2018 10:12:49 GMT</pubDate>
            <atom:updated>2018-12-25T04:30:03.684Z</atom:updated>
            <content:encoded><![CDATA[<p>Exploring GAE and GCE to deploy my Kotlin App.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KGpQE2GHVFcO3d_1JVO4hw.png" /></figure><h3>Context</h3><p>Before I jump in to the short journey I went through in selecting the right GCP product for my Kotlin app, I should explain a little about my use case, so that you can understand whether my experience matches your own. I am a firm believer that in technology, software especially, there is no one size fits all, so I don’t want to direct you to a particular route if it doesn’t fit with your needs.</p><p>To explain then. I have hosted a small Chrome extension that collects a small amount of data on certain web pages, and replays that data back to you and other users (crowdsourcing of data) the next time they visit to see how prices have changed. The app is a very simple set of REST APIs with a backing database. It has about 10,000 regular users, which I originally hosted on OpenShift (remember that?) because it allowed free database hosting of 1Gb and 24/7 Java application running. I ran this as a Play Framework (v1) app and it worked happily for about 7 years…until OpenShift changed their rules, and made the free version unrealistic for a 24/7 operation albeit very low volumes.</p><p>I moved to AWS last year to take up their 1 year free database, and elastic beanstalk offering, which I knew I would have to move. That is where GCP comes into the picture.</p><p>Note: I am not being excessively tight here, I make no money from the chrome extension, so I don’t really want to fund it at the tune of $20–$30 per month for the sole pleasure of those using the extension.</p><h3>Kotlin for REST APIs</h3><p>In the transition between OpenShift and AWS, I rewrote the app in Kotlin. I had started to use Kotlin much more for backend technologies, so I wanted to try out Kotlin in a production (albeit small) app. I have used a range of Kotlin frameworks, Spring Boot and SparkJava being the two favoured ones. So, please up step GCP to run my new Kotlin App.</p><h3>GCP: Google Cloud Platform</h3><p>Note: Yes I could have written this in PHP, or Go or lots of other things that may have made it simpler to deploy to GCP, but Kotlin is my language of choice, and I want my hosting option to fit in with me, not the other way around…selfish right?</p><p>I started migrating the database. I opted for Google Compute Engine, because I could get this running for free with Google’s 720 hours / month free forever. I didn’t use the marketplace, because it wanted to run on a more powerful instance that would have cost money…can’t have that, so I spun up an instance and installed it myself. I won’t go into that here, there are plenty of tutorials on how to do that by more capable sysadmins.</p><p><em>Step 1: sort the database. Done.</em></p><p>At this stage, I had my elastic beanstalk running in AWS writing to the database in Google. A little extra latency, but nothing I couldn’t live with. Next step, migrate the Kotlin app.</p><h4>Option 1: Google App Engine Standard</h4><p>Google App Engine (GAE) runs in two modes. Standard is a little more restrictive in the technologies it allows (although there are lots), one being Java (and therefore Kotlin will work), but it does require you to interface via the Servlet API, which Spring Boot nor SparkJava aren’t straight up enabled with.</p><p>The other problem with GAE Standard is that it is self contained from a networking perspective. It runs as Software as a Service, and the security model doesn’t allow you to access Compute Engines inside of your project. See <a href="https://stackoverflow.com/questions/47308749/connect-google-app-engine-and-google-compute-engine#47324010">this StackOverflow post </a>for more info. This meant that even if I compromised and used a Servlet API based App Engine, it wouldn’t be able to write to my database.</p><h4>Option 2: Google App Engine Flex</h4><p>So GAE Standard out of the way, I move on to GAE Flex. This allows you to run a containerised app. This was super easy to set up.</p><ol><li>Create the app.yaml, with the two specific settings: flex environment and custom runtime</li><li>I used a simple Dockerfile based on Java exposing port 8080, and running my JAR file</li><li>I could have ended it there, but GAE Flex allows you to put lifecycle events to let the platform know your application is healthy, so that it can restart the instance if not. It just requires two HTTP endpoints; one for application started, and one for application healthy. Both are configured in the app.yaml.</li><li>The whole thing is then deployed nicely with the gcloud deploy command line function. Easy!</li></ol><p>In less than an hour, I was up and running, pointing at my compute engine database (via the internal IP), and running beautifully.</p><p>So why do I have an option 3? Well, a dozen hours later I had a billing alert. I set an alert for £0.01, £0.03 and £0.05. I had spent £0.78. Huh? I thought GAE was free under 750 hours…apparently not for Flex environments. Back to the drawing board. That lovely developer experience lost because I don’t like spending any money. Back to AWS for the Kotlin app (database can stay on GCP) until I figure out what to do.</p><h4>Option 3: Google Compute Engine</h4><p>You will recall from a little further up this page, I have a Compute Engine running my DB. This has been running happily for well over a week now, no issues.</p><p>I simply used the gcloud command to push my JAR file built in Option 2 and sent it to my Compute Engine instance. Run the JAR file (changing the DB to listen only on localhost, and the App to talk to the local database), and we are almost ready to go. We just need to expose the app to the outside world.</p><p>A simple change to the Compute Engine settings to expose port 80 gets us almost there, but my app doesn’t run on port 80. Two options here</p><ol><li>Just let the Kotlin server run on port 80. Not recommended, but the lazy option.</li><li>Put NGINX as a reverse proxy, routing port 80 requests to 8080. Fortunately I am on Compute Engine, with SSH access, and a ton of resources on the Internet telling me how to do this. Less than 20 minutes and we are up and running.</li></ol><h3>Conclusion</h3><p>So here we land. A free instance of GCE, running NGINX, a Kotlin Server and a Database. Serving traffic 24/7 for well over a month, and a zero cost to do so. Yes I lost time in working through these options, but I value learning, so what’s the real cost? And I got to write this blog post.</p><p>The more I get into GCP, the more I am impressed with their offering. Some of the newer stuff coming out like Kubernetes Engine merged with Istio look super interesting…if only they would have let me use GAE Flex for free, I would have been over the moon.</p><p><em>This post is specific to Kotlin, but for GAE and GCE this could be equally applicable to any non Servlet Engine based Java / Scala Framework, etc. Some of those will have plugins that create a servlet API wrapper specifically for GAE, and hopefully this post helps you understand why they would do that, and the limitations (db access, for example) that this still leaves.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dd1a51e5417b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kotlin, SpringBoot and WebSockets]]></title>
            <link>https://codemwnci.medium.com/kotlin-springboot-and-websockets-276029b22482?source=rss-6f0e89485e0d------2</link>
            <guid isPermaLink="false">https://medium.com/p/276029b22482</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[websocket]]></category>
            <dc:creator><![CDATA[Wayne Ellis]]></dc:creator>
            <pubDate>Sat, 27 Jan 2018 17:14:46 GMT</pubDate>
            <atom:updated>2018-01-27T17:15:08.654Z</atom:updated>
            <content:encoded><![CDATA[<h4>Using Kotlin to do websockets the SpringBoot way</h4><h4>Introduction</h4><p>For my latest Blog post, I have decided to continue the Kotlin theme, and this time explore SpringBoot further by revisiting the WebSocket Chat Application example that I started with many months, but converting it from SparkJava to SpringBoot. Whilst I personally find SparkJava very expressive and simple to use, Spring as a community has a very strong following, but I have found very little information on Kotlin and Websockets using Spring. This post is an attempt to rectify that.</p><p>First off, I should point out that there are two methods of implementing WebSockets in SpringBoot. This first, and the one you will find in the tutorials, is STOMP (Streaming Text Oriented Message Protocol). However, I prefer a little extra control, and a little less boilerplate, so I am gong to focus on the WebSocketHandler approach.</p><p>Given that I have already covered this topic previously, I am not going to go into too much detail on the client side. The focus of this topic is Kotlin and Spring; as such I am going to largely lift the implementation from the SparkJava code I created in the previous post. However, the main change to that is that rather than using straight WebSockets on the javascript side, I will instead make use of SockJS. This will give us fallback options if the browser the client is using does not support Websockets…albeit this is becoming less and less, SpringBoot implements SockJS with ease, so we may as well take the increased functionality for the few lines of extra code.</p><h4>Let’s start coding</h4><p>We only need 3 files for this implementation. These are</p><ol><li>build.gradle</li><li>src/main/resources/static/index.html</li><li>src/main/kotlin/codemwnci/bootsocket/ChatApplication.kt</li></ol><p>The source code can be found on GitHub below</p><p><a href="https://github.com/codemwnci/kotlin-springboot-websocket">codemwnci/kotlin-springboot-websocket</a></p><h4>The Build File</h4><p>To begin, I have used Gradle for the build script, rather than Maven for this implementation, but if you prefer Maven it is almost a standard spring boot set up, with the Jackson Kotlin module for easy JSON integration. You can use <a href="https://start.spring.io/">https://start.spring.io</a>, or can copy directly from here.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b921cb28c43acf2f93e0f65d07111318/href">https://medium.com/media/b921cb28c43acf2f93e0f65d07111318/href</a></iframe><h4>The client code</h4><p>As mentioned in the introduction, the client side chat code is mostly a copy-paste from the previous example. As you can see from the code, to open a socket using SockJS is as simple as giving it a relative path and creating a SockJS object, rather than a standard WebSocket object. The only other change is to include the SockJS script in the head. The rest of the code is identical.</p><p>For those who have not read the previous example, the cost is fairly straightforward. There is a DIV for the chat area, a DIV for the users logged in, and a final DIV with a text input and button to send a message. The javascript is also reasonably straightforward. It initially opens the socket, and sets three function callbacks to deal with open, close and message events.</p><ol><li>The onopen event simply asks the user to choose their username, and then sends a message to the websocket server to inform who has joined</li><li>The onclose event just outputs an alert to the user that the server has closed the connection</li><li>The onmessage event calls the receiveMessage function, which in turn adds or removes a user to/from the userlist, or adds a new chat message to the message DIV.</li></ol><p>Finally, the javascript has a click / keypress listener on the button and text box, that executes the sendMessage function. This function simply sends a message to the server with a JSON string containing the chat message or the join request.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e7ca4c9c94ac3580fa89e2e019f7adf2/href">https://medium.com/media/e7ca4c9c94ac3580fa89e2e019f7adf2/href</a></iframe><h4>The server code</h4><p>The server code can be split into three distinct parts; the SpringBoot bootstrapping, the websocket handler registration configuration, and finally the websocket handler itself.</p><p>The springboot boostrapping is the same as any other Kotlin springboot implementation. We won’t discuss this in any detail (lines 58–63).</p><p>The websocket registration (lines 50–55) is a simple configuration class with a couple of annotations that enable websockets for the SpringBoot application. This code looks somewhat overkill in its 6 lines of code, however if your application is more than just this simple example, this separation will look far less overkill and instead a neat separation of concerns. It should be noted here that as part of the websocket registration, the “withSockJS()” method is called, which gives us the server side effort for SockJS fallback.</p><p>The ChatHandler class is where the interesting parts of the Websocket implementation takes place. We are extending the TextWebSocketHandler, which when not using STOMP will be the most useful parent class for most websocket implementations.</p><p>For our implementation, there are 5 functions that require implementation, two of which are overridden methods from the Java parent class that we are extending, and 3 helper functions for communicating back to the connected web sockets. I will deconstruct this class line by line to explain how our serverside implementation works.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fd8ea7db020a4e396156f049d0a73c4f/href">https://medium.com/media/fd8ea7db020a4e396156f049d0a73c4f/href</a></iframe><p>Line 14–15: Here we are creating two DTO classes. They will both be used to convert to JSON when we send the information back to the client.</p><p>Line 19: This is a hashmap that will contain all the sessions that have connected and joined the chat.</p><p>Line 20: So that we can inform the clients when users are removed, we need to ensure we have a unique identifier for each user, and therefore we give each User that joins a UID. We use AtomicLong to ensure that we not have any synchronisation issues.</p><p>Line 22–25: This overridden method is called when a websocket disconnects from the server. On this event, we remove the session from the hashmap. We could also at this stage inform the client that the user has left, but for brevity of this example, we will not perform this action.</p><p>Before discussing the main function (handleTextMessage), we will briefly discuss the three helper functions that are all used as part of the handleTextMessage function.</p><p>Line 45: This helper function (emit) simply takes the websocket we wish to send a message to, and the message we wish to send. We call the sendMessage function on the websocket, construct a new TextMessage object, which is part of the Spring Websocket implementation, and then using Jackson JSON we transform the message we wish to send into a JSON string.</p><p>Line 46: This helper function (broadcast) simply takes the message we wish to send to all websockets, and iterates over each element of the hashmap that contains all of the sessions using the forEach function, and then simply calls the emit function we have just described passing in the session object from each iteration, and the passed in message.</p><p>Line 47: This helper function (broadcastToOthers) is very similar to the broadcast helper function, except it specifically excludes a single passed in websocket. This is achieved by again using one of the functional utilities of the Kotlin collections by filtering the hashmap (to include every session except the one we wish to exclude) and then executing the forEach in the same way as the broadcast function previously described.</p><p>Finally, we will walk through the handleTextMessage function. Starting at Line 27, this takes in a websocket (the one that has send the message), and a message that they have sent. The first step is to turn this message into JSON, which we do on Line 28 using the Jackson ObjectMapper object and getting the message from the payload property of the passed in message.</p><p>Line 30: Now that we have the JSON message, we can determine what we need to do using the message type contained in the message JSON string. Using the kotlin WHEN clause, we can execute two different paths based on the “join” or “say” message type.</p><p>Line 31–38: When a user requests to “join” the chat, we first create a new user object by incrementing the counter, and reading the user’s name from the JSON message. The user is then added to the sessionlist and we send two messages. To the user joining, we send a message directly to them using the emit helper function to tell them all the users in the current chat. We then broadcast to all the other users to tell them that this new user has joined, by calling the broadcastToOthers helper function.</p><p>Line 39–41: When a user sends a chat message (“say”), we simply call the broadcast function sending the text that they inputted to all connected sessions, including themselves.</p><p>And that is it. The boilerplate from SpringBoot is minimal. The addition of SockJS is easy and not intrusive. Yet, the extensibility of the code is there without having to do any meaningful refactoring.</p><p>Hopefully this has been an informative article that will give you suitable ideas of how you yourself could use the ease of SpringBoot and the power of WebSockets to develop real-time applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=276029b22482" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kotlin WebApp Tutorial — ToDoList — Part 3]]></title>
            <link>https://codemwnci.medium.com/kotlin-todo-webapp-part-3-97942a79ad42?source=rss-6f0e89485e0d------2</link>
            <guid isPermaLink="false">https://medium.com/p/97942a79ad42</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Wayne Ellis]]></dc:creator>
            <pubDate>Sun, 17 Sep 2017 10:30:41 GMT</pubDate>
            <atom:updated>2017-09-17T10:35:50.272Z</atom:updated>
            <content:encoded><![CDATA[<h4>Using SpringBoot instead of SparkJava for the Web Framework</h4><p>A few weeks back, I wrote a two-part series on creating a Web App using Kotlin. For it, I decided to use SparkJava to serve the REST endpoints, and VueJS for the front end. One of the main questions I have had since is, why SparkJava and not SpringBoot? Well, I believe it is a matter of preference, but both a valid and capable options…but for completeness, I decided to write a quick implementation using SpringBoot.</p><h4>Jumping Straight In</h4><p>I am not going to go back over, the concepts that were covered in <a href="https://medium.com/@codemwnci/kotlin-webapp-tutorial-todolist-part-1-c544b9a70f29">Part 1</a>, or <a href="https://medium.com/@codemwnci/kotlin-webapp-tutorial-todolist-part-2-36af3048801a">Part 2</a>, you can welcome to click back and read. All I am going to do in this part is to replace what we did in Part 1 and build our REST endpoints in SpringBoot.</p><p>To get us up and running far quicker, I suggest you just go to <a href="http://start.spring.io./">http://start.spring.io.</a> and choose to genereate a Maven project, with Kotlin and I chose SpringBoot 2. Set the group and artefact of your choice (I did group=codemwnci, artefact=kotlinspringboot). From the dependencies, choose Web, JPA and H2.</p><h4>The code</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7f56e2030d946722fd66394be6662bfe/href">https://medium.com/media/7f56e2030d946722fd66394be6662bfe/href</a></iframe><p>So, lets go and explain this code.</p><p>First off, we’ll start with lines 38–43. This is the Todo object. This was a single line on the previous implementation, but I have split it out for clarity, because we have a few annotations on the id field. It is marked as an Entity so that JPA can pick this up, and then the Id andGeneratedValue elements are set to tell the database that this is an auto-increment value. You will also notice that all the values have been given default values; this is because JPA needs a no-args constructor, so giving all elements a default value achieves this in the background.</p><p><strong>Note</strong>: we haven’t needed to set up a datasource, or the H2 database. All of this is done for us, by the H2 dependency that we pulled in at the start.</p><p>Next, the JPA Repository allows us to use DB helper methods to access our underlying database entities (we will use FindAll, FindById, Save, and DeleteById). In Kotlin, all we need to do is implement the interface (line 36), to extend the JpaRepository, setting the Type as Todo, and Key as a Long.</p><p>The final part is the RestController, which accesses the DB and works with the entities.</p><ul><li>Line 8: This sets up the class as Controller, serving REST requests, with all mappings inside the class being served up from the /todo path.</li><li>Line 9: The class is defined here, with the main thing of note is that the JPARepository is passed in. This achieves the dependency injection required to give us an implementation of our TodoRepository interface.</li><li>Line 11/12: This returns a JSON respoonse of all the Todos in the database. As we are working with a RestController, if the response is a class, it is converted into JSON. This endpoint has been defined in a functional style (no parenthesise or return type, just an equals sign).</li><li>Line 14/15: This function returns a single Todo. The Id is defined as a path variable using the {id} syntax in the GetMapping value, which is then passed in as a parameter into the function. We can then once again is the jpaRepository to return a Todo using the findById function.</li><li>Line 17/18: This function is similar to the previous two, except it is a PostMapping (not Get), and the data is taken from the RequestBody, rathen than a PathVariable. We then use the JPA Repository to save a newly created Todo object, which we create using a named parameter (we only pass in a single parameter, all the others are defaulted). Note that the Id set to default of zero will be ignored by the DB in favour of the auto-generated Id.</li><li>Line 20–26: This function is slightly different as we are not using the functional style (there is too much going on), which means we need a return type and a return statement. Similar to Line 14, we have the {id} passed into the parameter list, along with a Todo object, which is automatically converted from the JSON passed in from the RequestBody. The code then goes onto load the Todo from the Database (using the findById function), update the text and done variables, and then return the saved entity.</li><li>Line 28–32: This function simply takes the {id} from the path and calls the deleteById function, and finally responds with the sameOk text that we returned in the SparkJava implementation.</li></ul><p>And that is it. Slightly less verbose than the SparkJava implementation, due to the additional magic delivered to us by SpringBoot and the SpringBoot dependencies.</p><h3>SpringBoot or SparkJava?</h3><p>As I said at the start of this article, I think it is a preference, based on your own style and your own requirements. I personally prefer the expressive nature of the routes in SparkJava, over the annotations in Spring, but it is a very minor point, because Spring still looks very clean.</p><p>I didn’t have to set up anything for the DB (like Hikari or Kotliquery), which is fine for a simple implementation likes this, but for a bigger, or more Enterprise implementation, I know many would prefer to have the control in favour of a small amount of verbosity.</p><p>JPA also took away a lot of the verbosity of dealing with the entities. Again, in many situations this is fantastic…however, there are cases where loading the whole entity to make a minor change is overkill. I read an argument a few years back that stated that DBs did not need a DSL like JPA offers when you have a perfectly good one in SQL. In my experience, I prefer to work directly with the DB, especially with DTOs so easy to create in Kotlin, but it really is a personal choice.</p><p>I’d be interested to hear your own preferences and opinions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=97942a79ad42" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kotlin WebApp Tutorial — ToDoList — Part 2]]></title>
            <link>https://codemwnci.medium.com/kotlin-webapp-tutorial-todolist-part-2-36af3048801a?source=rss-6f0e89485e0d------2</link>
            <guid isPermaLink="false">https://medium.com/p/36af3048801a</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Wayne Ellis]]></dc:creator>
            <pubDate>Fri, 25 Aug 2017 22:16:40 GMT</pubDate>
            <atom:updated>2017-08-25T22:16:40.522Z</atom:updated>
            <content:encoded><![CDATA[<h4>Creating REST services using SparkJava / Kotlin and Single Page App using VueJS</h4><p>In <a href="https://medium.com/@codemwnci/kotlin-webapp-tutorial-todolist-part-1-c544b9a70f29">part 1</a> we created the REST backend for our TodoList App. Now, in part 2, we will complete the app by creating the VueJS front end.</p><h4>Setup</h4><p>Most of the setup is already done; we have our server via SparkJava, and we have created the /public folder and specified in SparkJava that is where our static resources are loaded from, all we have to do now is create an HTML file. So let’s go ahead and create an index.html file in /src/main/resources/public.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f95e38ec038e08c91a46d9ea4003c4e1/href">https://medium.com/media/f95e38ec038e08c91a46d9ea4003c4e1/href</a></iframe><p>Most of this is standard HTML, the things of note are:</p><ol><li>Line 6/7: Here we are loading VueJS and Axios (defacto http library for VueJS).</li><li>Line 11: This is where the VueJS template code will live.</li><li>Line 16: This creates a new VueJS app, and specifies that the element bounds are from with the element with ID of “app” (the div from line 11).</li></ol><p>The data, methods and mounted we will come back to shortly, but are mostly self explanatory; data is the application data (the model), methods are the functions we call as events etc, and mounted is executed when the VueJS is setup and ready to start (similar to $(document).ready() in JQuery).</p><h4>Let’s Add Some Todos</h4><p>Update the code so that it looks more like below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ed62df2a091ccb6c2fb926d9872568f6/href">https://medium.com/media/ed62df2a091ccb6c2fb926d9872568f6/href</a></iframe><ol><li>Line 3: Here we’ve added an input text tag, which calls the addTodo method when the enter key is pressed.</li><li>Line 4–8: We have added an unordered list, with the list items being generated by iterating over the todos data, and then outputting the text of the todo (we’ll add the done part later). This double brackets notation is called handlebars, and is the template style used by VueJS.</li><li>Line 15: Here we have added a data item called todos, and configured it with an empty array.</li><li>Line 18–23: This is the addTodo function. This uses axois to post to our server, passing the input text value in the body (event.srcElement.value) and then pushes the JSON response onto the data array (this will be the Todo JSON from the server). Finally, the input textnox is rest to blank so we can add more Todos.</li></ol><blockquote><strong>Note</strong>: On our SparkJava server, we used staticFileLocation which reads the index.html from the created JAR file. This means we have to restart our server for our HTML changes to take effect. It is possible to use externalStaticFileLocation and specify a path outside of the JAR file, which means we do not need to restart the server each time we change our HTML, but this will not deploy to a different location. If you use this method, do so for testing only!</blockquote><p>If we give this a go, we should be able to add elements, but if we refresh the page we lose our todos (they still in the database, but our page is not loading them on start up). Let’s fix that next.</p><h4>Load All Todos</h4><p>To load all the todos, we need to do that when VueJS has finished loading. This what the mounted() function was for. So let’s update that function with an axois request that loads all the todos from the server.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bbd8015cde676097d59c685e6e4374bc/href">https://medium.com/media/bbd8015cde676097d59c685e6e4374bc/href</a></iframe><p>It really is that simple. We call a GET request to the server route that returns all Todos, which responds with a JSON array of Todos, which we simply store on our todos data element. We should now see our saved todos even after we refresh the web page.</p><h4>Delete a Todo</h4><p>Inside of the li update the handlebars code, so that it now looks like the following.</p><pre>{{todo.text}} <br>&lt;a href=&quot;#&quot; @click=&quot;deleteTodo(todo.id)&quot;&gt;(delete)&lt;/a&gt;</pre><p>This calls the deleteTodo method (we’ll create this next) when the href is clicked, passing in the id of the todo into the method.</p><p>Next we need to create the deleteTodo method, which we will place inside of the “methods” curly braces, underneath the addTodo method (<em>ensure that there is a comma after the closing curly brace of the addTodo function</em>).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5f15a5190534bb838b3a51150e8e9c80/href">https://medium.com/media/5f15a5190534bb838b3a51150e8e9c80/href</a></iframe><p>This function simply sends an HTTP Delete request to the todo path (which includes the passed in ID). If the response data is equal to “ok”, which we return from the server if the delete from the DB succeeded, we then iterate through the data array and delete the matching element.</p><h4>Updating the Todo</h4><p>The final piece of the app is to allow us to update the todo. In this example, I will just focus on the done flag, by creating a checkbox showing if the todo is done or not, and allowing the checkbox to be updated. Also, now that we will be able to set the todo as done, I will also update the delete link, so that it is only visible for completed todos (using the v-if filter of VueJS).</p><p>So, update the li so that it now looks like the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/737d32cf41ba79342723359f56c7fc83/href">https://medium.com/media/737d32cf41ba79342723359f56c7fc83/href</a></iframe><ol><li>Line 2: creates a checkbox, marking it checked when the todo.done boolean is true, and setting up an event called toggleCheck passing in the todo to update.</li><li>Line 4: contains the updated code for the delete, with the v-if. This added code means that the &lt;a href is only visible when todo.done is true.</li></ol><p>Next we need to add the toggleCheck(todo) method, which we will add to the methods section.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c787ab6e5590a500ecd90f36e1ad6076/href">https://medium.com/media/c787ab6e5590a500ecd90f36e1ad6076/href</a></iframe><ol><li>Line 1–4: this code simply inverts the done boolean of the todo, effectively toggling the value, and then calls the update method.</li><li>Line 7: this code executes an HTTP Put (update) to the URL containing the todo’s ID, and passes in a JSON string in the body of the request. The JSON is the updated todo values (in our case, just the done value, but both values are required to be sent serverside).</li><li>Line 8–13: when the server responds we simply iterate through the list of todos, looking for the todo that matches the ID that we updated, and the we update the values to match what is returned (therefore keeping serverside and clientside in sync).</li></ol><h4>And That’s It!</h4><p>And there we have it. A simple (yes, I know the CSS is lacking), but functional ToDo app client side in 70 odd lines of HTML and Javascript, plus 90 lines of serverside code.</p><p>Full source code can be found on GitHub → <a href="https://github.com/codemwnci/KotlinToDoApp">https://github.com/codemwnci/KotlinToDoApp</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=36af3048801a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kotlin WebApp Tutorial — ToDoList — Part 1]]></title>
            <link>https://codemwnci.medium.com/kotlin-webapp-tutorial-todolist-part-1-c544b9a70f29?source=rss-6f0e89485e0d------2</link>
            <guid isPermaLink="false">https://medium.com/p/c544b9a70f29</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[vuejs]]></category>
            <dc:creator><![CDATA[Wayne Ellis]]></dc:creator>
            <pubDate>Fri, 25 Aug 2017 21:19:11 GMT</pubDate>
            <atom:updated>2018-01-05T09:47:40.611Z</atom:updated>
            <content:encoded><![CDATA[<h4>Creating REST services using SparkJava / Kotlin and Single Page App using VueJS</h4><p>Not so long ago, I wrote a piece on creating a <a href="https://medium.com/@codemwnci/kotlin-websocket-chat-using-javaspark-dd6d863e98e7">Websocket chat</a> implementation using Kotlin and SparkJava. This was fun, and helped show the power of Kotlin in web development, but didn’t really hammer home why web development in Kotlin is a good thing. With so much being written and spoken about Kotlin in the Android world, I wanted to try to address the balance somewhat and put a little more weight onto the web dev argument for using Kotlin.</p><p>The following blog post will be split into two parts. Part 1 (this post) will be the REST backend, and <a href="https://medium.com/@codemwnci/kotlin-webapp-tutorial-todolist-part-2-36af3048801a">Part 2</a> will be the VueJS client side. Full source code can be found <a href="https://github.com/codemwnci/KotlinToDoApp">here on GitHub</a>. (update: I have added a <a href="https://medium.com/@codemwnci/kotlin-todo-webapp-part-3-97942a79ad42">Part 3</a> that uses SpringBoot instead of SparkJava, so you can compare implementations).</p><h4>Set Up</h4><p>As with last time, assuming you already have Kotlin up and running (I have used IntelliJ), first we will create a POM file. If you are using intelliJ, then create a Maven project, and copy the following code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/483f43b3035e0b65a466fc6cf543ca09/href">https://medium.com/media/483f43b3035e0b65a466fc6cf543ca09/href</a></iframe><p>Some specific things to note here:</p><ol><li>JCenter as a repository has been included. This is because we are importing Fuel later for testing our REST routes, and Fuel is only available currently on JCenter and not maven central.</li><li>The dependencies we have included are, in order; Kotlin, KotlinTest, SparkJava, HikariCP (for DB connection pooling), H2 (we will use an in memory DB to save us installing a specific database), kotliquery (a DB access library), SLF4J (for logging), Jackson (for JSON← →Object conversions), and finally Fuel (which is an HTTP client which we will use in our unit tests.</li></ol><p>Again, just like last time, if you have set up the project as a Maven project, then you will have a standard maven directory structure. We will need to create two further directories.</p><ol><li>We need to create a directory called public inside of src\main\resources\</li><li>We need to create a directory to put our package structure in. I have chosen to use a kotlin directory inside of src\main and src\testrather than using the normal src\main\java. We also need to add a package directory in both src\main and src\test. I have chosen codemwnci.</li></ol><p>If you have chosen the same approach as me, you will now have a directory structure like the following</p><pre>- src<br>  - main<br>    - kotlin    <br>      - codemwnci<br>    - resources<br>      - public<br>  - test<br>    - kotlin<br>      - codemwnci</pre><p>We are now ready to start our coding! So let’s begin with adding a database to store our ToDo’s in.</p><h4>Add Database Support</h4><p>So, let’s create a new Kotlin file, called MainController.kt</p><p>Copy the following code</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/303ed87d68a055db4c07bd2c495917ad/href">https://medium.com/media/303ed87d68a055db4c07bd2c495917ad/href</a></iframe><p>This code hopefully is fairly self explanatory. We import all the necessary packages, and then within the main function (this will later contain our REST code) we call the setupDBfunction.</p><p>The setupDB function first of all creates a datasource. Hikari allows multiple data sources to be created, however, in our example we only need one, so we will set a default datasource with the URL required for an in memory H2, and any username / password. Next we make use of the datasource, using kotliquery.</p><p>Each kotliquery starts with the using statement and then inside the body of that statement, we use the session.run(queryOf().asExecute) statement. The asExecute is used for update statements, where as SELECT queries use a MAP and asSingle / asList method (we’ll come on to that shortly). So, here we execute a statement to create the TODO table with 4 columns (id, text, done and created_at).</p><p>And there we have it, we have database support configured with a data source, and fully configured database table set up and running in memory. Next we can start to populate the database!</p><h4>Create A Todo (HTTP Post)</h4><p>Firstly, remember that the database that we have configured is an in memory database. The data does not persist between server restarts. To do that, we would need to configure a different DB URL (and there would also be no need to run the CREATE TABLE sql every time the server started).</p><p>Anyhow, on to the code for our first REST service. First of all, let’s set up some utility functions. Add them just above the setupDB function.</p><pre>fun badRequest(reason: String) = halt(400, reason)<br>fun serverError(reason: String) = halt(500, reason)</pre><p>These are two very simple functions that allow us to break out of processing our routes under certain circumstances, and return a 400 / 500 code with an associated reason message. We’ll make use of these in our first route.</p><p>Now, let’s go back to to our main function and add the following code immediately after the setupDB call, so it looks like below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3e1932402dc246c15b29d04b5f0a783c/href">https://medium.com/media/3e1932402dc246c15b29d04b5f0a783c/href</a></iframe><p>Let’s dissect this code a little:</p><ol><li>Line 4: we set our code to run on port 9000 (I spent so long with PlayFramework, I can’t help it!)</li><li>Line 5: here we set where our HTML / JS code will go. We won’t get to this until Part 2 of this blog, so ignore it for now.</li><li>Line 7: all of our routes are going to be access via VERB /todo/&lt;something&gt; so rather than repeating the /todo/ part, we use the path to say that everything contained inside are child routes of /todo/ .</li><li>Line 8: this is part of the reason I love Koltin. This would be a full class with setters / getters in Java. Here, we have our DTO that represents our Todo. If you use Scala, this is equivalent of a case class.</li><li>Line 10: this is a simple function that converts a Row (DB Result Row) into a Todo, by accessing the database object and creating a new Todo object from the accessed data. We will use this next on Line 12.</li><li>Line 11: This function takes an ID and returns a Todo (the return type is not null safe because it is possible the database does not contain that ID. Here we use the using statement we used to CREATE the database earlier.</li><li>Line 12: here we run a select statement, passing in the ID that was passed into the function. We then map using the toTodo mapper we created in step 5 (line 10) and tell KotliQuery that we are expecting a single value using the asSingle terminator.</li></ol><p>Now let’s dissect Line 15 to 24, which makes up the actual HTTP request that handles then HTTP Post to create a new Todo. Here, we expect a request to POST http://localhost:9000/todo/ with the text of the todo in the body of the request.</p><ol><li>Line 15: this is our POST method. We pass in the empty string, because we expect the post to be sent to /todo/.</li><li>Line 16: we ensure that the body is not empty, and if it is we call the badRequest function we set up at the start of this section.</li><li>Line 18: we get the todo from the body of the request</li><li>Line 20: We run an insert statement to insert the todo text retrieved in Line 18. One thing to note here is instead of asExecute we use asUpdateAndReturnGeneratedKey. This returns the generated ID, which we store into the val idon line 19.</li><li>Line 23: we do a simple check that the id is not null, to ensure the insert was successful. If it is null, we call the internalServerError function.</li><li>Line 24: if all is successful, we use the jacksonObjectMapper to create a JSON representation of a Todo, which we retrieve from the database using the ID passed into the getTodo function that we created on Line 11/12. We load the full Todo from the database at this stage, to return because there are a number of database generated values (done / created_at), that we don’t have direct access to otherwise following a create.</li></ol><p>And that is it. We can now using something like Postman to do a HTTP Post, and we should see a JSON string returned to us.</p><h4>Get a Single Todo (HTTP Get)</h4><p>To return a single Todo will be really easy, given that we have done most of the work already in the POST.</p><p>We just need to add the following code just underneath our previous post route, so that it is still inside of path scope.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3f12069a2b9c8a24960339e007b4feef/href">https://medium.com/media/3f12069a2b9c8a24960339e007b4feef/href</a></iframe><p>There is not much to dissect here. the :id inside of the get identifies to the route that we expect a value to be passed in. This will be the ID of the specific ID we want to return. Next we call the getTodo that we used in the POST to return the created todo, except the ID that we pass into the function is retrieved from the request req parameter and convereted to a Long.</p><p>The Todo is then converted into JSON using jacksonObjectMapper as we did in the POST method.</p><h4>Get All Todos (HTTP Get)</h4><p>When we first load our todo app, we will want to return all the Todos, not one by one. So, let’s see if we can return all Todos and not just a single element.</p><p>We have already done a lot of the work, so again, this is pretty straightfoward. Add the following code after the GET from above (again, inside of the todo PATH).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/68ca62d2b292f2a07f6563b09dc7e2b2/href">https://medium.com/media/68ca62d2b292f2a07f6563b09dc7e2b2/href</a></iframe><ol><li>Line 2: note that we are List&lt;Todo&gt; from the SQL statement, rather than a single Todo like before.</li><li>Line 3: we select all todos, we map using the same toTodo mapper that we used in the getTodo function, but we finish with asList indicating to KotliQuery that we expect a list of Todo objects to be returned from the query, therefore to iterate over the result set, rather than just getting a single item.</li><li>Line 5: we use the jacksonObjectMapper to convert the List of Todos into JSON.</li></ol><p>Job done! Easy.</p><h4>Delete A Todo (HTTP Delete)</h4><p>Next, we want to be able to delete todos when we are done with them. How frustrating would a todo list app be if we could never get rid of the todos!</p><p>Again, this is pretty straightforward now that we are getting the hang of using SparkJava and KotliQuery. We expect a HTTP Delete request to be sent to us with the ID of the todo we wish to delete.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4953219b7d7ce235823c840891145110/href">https://medium.com/media/4953219b7d7ce235823c840891145110/href</a></iframe><p>Line 1: here we specify the route as a DELETE with an ID expected in the path.</p><p>Line 2 / 3: we run a delete query where the ID is equal to the ID that we passed in, and run the query as an Update. The asUpdate terminator results in an integer being returned with the number of affected rows (we store this in the rowsDeleted value).</p><p>Line 6: if we deleted a single row as expected, we simply return “ok” (note in Kotlin we don’t need to specify return. This “ok” will indicate to the client side that the delete was successful.</p><p>Line 7: if we did not delete a single row, then we return a server error 500, saying something went wrong.</p><h4>Update A Todo (HTTP Put)</h4><p>Finally, the only thing our server side does not take care of is updating of the todo (marking as done, or editing the todo text). To do that, we will use the HTTP PUT verb again with the ID as a path parameter, but with some JSON in the body of the request with the updated details.</p><p>Again, add the following code inside of the PATH parenthesise like we have done for all the other routes.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/97ed60ddbcbeb3463b0c20a51beeb001/href">https://medium.com/media/97ed60ddbcbeb3463b0c20a51beeb001/href</a></iframe><ol><li>Line 3: Here we create a value called update, which contains a JSON object that has been read from the body of the request. This contains the data that needs to be updated.</li><li>Line 4: we check if the JSON contains both text and done, if not returning a badRequest.</li><li>Line 6–9: resulting in a number of rows updated, we execute an update query, getting the text and boolean from the JSON and the ID from the request paramater, and then executing the SQL using asUpdate.</li><li>Line 12: Just like on the DELETE statement, we check if we had a single row updated. If we did, we return the updated Todo by calling the getTodo function (like we did on the POST).</li><li>Line 13: Otherwise, if we did not have a single row updated, we return that something went wrong.</li></ol><p>And that is it. A complete REST App with 5 different routes to add, delete, update and read (one or all), in 90 or so lines of code. You can test all of this our using cURL or Postman or SoapUI. But, before we finish and start working on the client side, we really should test our code like every conscientious developer should.</p><h4>Unit Testing using JUnit</h4><p>Remember that we are using an in-memory database. This means that the database is freshly set up every time, which perfectly suits our unit-testing needs. If we start to use a real database, we would have to ensure that when we start our server, we do so with a test (clean) database rather than the development / production database.</p><p>Unlike the code above, which I broke down into manageable chunks, I am just going to dump the whole lot in one go, and explain it, as there is a lot of repetition as each route is tested in turn.</p><p>Create a new file in /src/test/kotlin/codemwnci/ called MainControllerTest.kt, and past the following code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/223cea7e600d744e55e920a822077fdb/href">https://medium.com/media/223cea7e600d744e55e920a822077fdb/href</a></iframe><ol><li>Line 4: we are importing Fuel. This is an httpClient library that allows us to execute our HTTP routes. Spark does not come with a built in testing library like some HTTP frameworks, so we will use Fuel to do it for us.</li><li>Line 10–21: This set of code starts and stops SparkJava ready for testing. Because our main function that contained our routes (in MainController.kt) is not within a Class boundary, it is referenced at package level therefore, in our BeforeClass, we can simply access it by calling main() and pass in an empty array. Also note that JUnit requires the BeforeClass / AfterClass to be in a companion object, and the functions marked as @JvmStatic.</li><li>Line 30–33: I will highlight the second part of the first test to dive a little deeper into here. Line 30 we create an http request using Fuel to execute a post request, and setting the body with the text of the todo. This returns a Triple (request, response, result). On Line 31 we use the response (accessed from post1.second), because response is the second element of the triple, and then we check the httpStatus code is 200 indicating a successful post. We then get the data from the result (post1.third.get()) , convert it to JSON, and check that the generated ID is 1.</li></ol><p>The rest of the tests are along similar lines. Making requests, and checking the httpStatus from the response, or reading the result and checking the data is as we expected.</p><p>Again, remember that this is all possible because the database starts afresh each time we start the server. If we had a permanent database behind it, this would not work as it stands, and we would have to ensure that when started up the server (via the main method), we passed in parameters that ensured that app knew it had to start up in Test mode.</p><h3>And That’s All for Part 1</h3><p>Thanks for reading, and please come back to read more in <a href="https://medium.com/@codemwnci/kotlin-webapp-tutorial-todolist-part-2-36af3048801a">Part 2</a> when we take a look at the client side in VueJS to consume our REST services.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c544b9a70f29" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kotlin WebSocket Chat using SparkJava]]></title>
            <link>https://codemwnci.medium.com/kotlin-websocket-chat-using-javaspark-dd6d863e98e7?source=rss-6f0e89485e0d------2</link>
            <guid isPermaLink="false">https://medium.com/p/dd6d863e98e7</guid>
            <category><![CDATA[websocket]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Wayne Ellis]]></dc:creator>
            <pubDate>Sat, 15 Jul 2017 00:21:12 GMT</pubDate>
            <atom:updated>2017-09-18T22:55:55.511Z</atom:updated>
            <content:encoded><![CDATA[<iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fg3ohGP4QJKY%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dg3ohGP4QJKY&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fg3ohGP4QJKY%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/ea9b6b1f28c670de62158a5eae0a1248/href">https://medium.com/media/ea9b6b1f28c670de62158a5eae0a1248/href</a></iframe><p>I have been using Kotlin for a little while now, but in a small way. I have been flitting between Java, Scala and Kotlin for a few years, but with the announcement from Google of now officially supporting Kotlin for Android, I decided to jump back in again.<br>My typical use case when exploring new languages is a web application that I have been building on and off for a few years, which is essentially a Single Page App (JavaScript, usually Angular) on the front end, and a REST back end that doesn’t have to make me work too hard.<br>I have used a number of frameworks in the past, but for Scala I have always stayed pretty loyal to Play Framework. For Java, I have used SparkJava (or Play!), and for Kotlin, I went searching…Very quickly I decided that SparkJava was still a good solution to my use case.</p><p>My intention is to write a series of blogs on using SparkJava and Kotlin with associated other technologies to make a complete end to end solution.</p><p>To demo WebSockets, I am going to build a simple Chat application, using Kotlin, SparkJava and native browser WebSockets (no shims, frameworks etc). I am also going to only use JQuery, rather than a SPA framework like Angular, as not distract from the WebSockets.</p><p>All the code for this demo can be found on GitHub here → <a href="https://github.com/codemwnci/kotlinwschat">https://github.com/codemwnci/kotlinwschat</a></p><h3>Setup</h3><p>Assuming you already have Kotlin up and running (I have used IntelliJ), first we will create a POM file. If you are using intelliJ, then create a Maven project, and copy the following code.</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;<br>&lt;project xmlns=&quot;<a href="http://maven.apache.org/POM/4.0.0">http://maven.apache.org/POM/4.0.0</a>&quot;<br>         xmlns:xsi=&quot;<a href="http://www.w3.org/2001/XMLSchema-instance">http://www.w3.org/2001/XMLSchema-instance</a>&quot;<br>         xsi:schemaLocation=&quot;<a href="http://maven.apache.org/POM/4.0.0">http://maven.apache.org/POM/4.0.0</a> <a href="http://maven.apache.org/xsd/maven-4.0.0.xsd">http://maven.apache.org/xsd/maven-4.0.0.xsd</a>&quot;&gt;<br>    &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;</pre><pre>&lt;groupId&gt;codemwnci&lt;/groupId&gt;<br>    &lt;artifactId&gt;kotlin-ws-chat&lt;/artifactId&gt;<br>    &lt;version&gt;1.0-SNAPSHOT&lt;/version&gt;</pre><pre>&lt;properties&gt;<br>        &lt;kotlin.version&gt;1.1.3-2&lt;/kotlin.version&gt;<br>    &lt;/properties&gt;</pre><pre>&lt;dependencies&gt;<br>        &lt;dependency&gt;<br>            &lt;groupId&gt;org.jetbrains.kotlin&lt;/groupId&gt;<br>            &lt;artifactId&gt;kotlin-stdlib-jre8&lt;/artifactId&gt;<br>            &lt;version&gt;${kotlin.version}&lt;/version&gt;<br>        &lt;/dependency&gt;<br>        &lt;dependency&gt;<br>            &lt;groupId&gt;org.jetbrains.kotlin&lt;/groupId&gt;<br>            &lt;artifactId&gt;kotlin-test&lt;/artifactId&gt;<br>            &lt;version&gt;${kotlin.version}&lt;/version&gt;<br>            &lt;scope&gt;test&lt;/scope&gt;<br>        &lt;/dependency&gt;<br>        &lt;dependency&gt;<br>            &lt;groupId&gt;com.sparkjava&lt;/groupId&gt;<br>            &lt;artifactId&gt;spark-core&lt;/artifactId&gt;<br>            &lt;version&gt;2.5.5&lt;/version&gt;<br>        &lt;/dependency&gt;<br>        &lt;dependency&gt;<br>            &lt;groupId&gt;com.fasterxml.jackson.module&lt;/groupId&gt;<br>            &lt;artifactId&gt;jackson-module-kotlin&lt;/artifactId&gt;<br>            &lt;version&gt;2.8.4&lt;/version&gt;<br>        &lt;/dependency&gt;<br>        &lt;dependency&gt;<br>            &lt;groupId&gt;org.slf4j&lt;/groupId&gt;<br>            &lt;artifactId&gt;slf4j-simple&lt;/artifactId&gt;<br>            &lt;version&gt;1.7.22&lt;/version&gt;<br>        &lt;/dependency&gt;<br>    &lt;/dependencies&gt;</pre><pre>&lt;build&gt;<br>        &lt;plugins&gt;<br>            &lt;plugin&gt;<br>                &lt;groupId&gt;org.jetbrains.kotlin&lt;/groupId&gt;<br>                &lt;artifactId&gt;kotlin-maven-plugin&lt;/artifactId&gt;<br>                &lt;version&gt;${kotlin.version}&lt;/version&gt;<br>                &lt;executions&gt;<br>                    &lt;execution&gt;<br>                        &lt;id&gt;compile&lt;/id&gt;<br>                        &lt;phase&gt;compile&lt;/phase&gt;<br>                        &lt;goals&gt;<br>                            &lt;goal&gt;compile&lt;/goal&gt;<br>                        &lt;/goals&gt;<br>                    &lt;/execution&gt;<br>                    &lt;execution&gt;<br>                        &lt;id&gt;test-compile&lt;/id&gt;<br>                        &lt;phase&gt;test-compile&lt;/phase&gt;<br>                        &lt;goals&gt;<br>                            &lt;goal&gt;test-compile&lt;/goal&gt;<br>                        &lt;/goals&gt;<br>                    &lt;/execution&gt;<br>                &lt;/executions&gt;<br>                &lt;configuration&gt;<br>                    &lt;jvmTarget&gt;1.8&lt;/jvmTarget&gt;<br>                &lt;/configuration&gt;<br>            &lt;/plugin&gt;<br>        &lt;/plugins&gt;<br>    &lt;/build&gt;</pre><pre>&lt;/project&gt;</pre><p>The items to not on here is that we have included dependencies for SparkJava, Jackson (for JSON processing), and SLF4J (which is used by Spark to output logger info).</p><p>If you have set up the project as a Maven project, then you will have a standard maven directory structure. We will need to create two further directories.</p><ol><li>We need to create a directory called public inside of src\main\resources\</li><li>We need to create a directory to put our package structure in. So, inside of src\main\java we need to put a package. I have chosen codemwnci.</li></ol><p>If you have chosen the same approach as me, you will now have a directory structure like the following</p><pre>- src<br>  - main<br>    - java    <br>      - codemwnci<br>    - resources<br>      - public</pre><h3>Let’s Start Coding</h3><p>I am not going to go into much detail on the normal REST approach to SparkJava. You can read that on their website, or you can watch the video at the top of this page if you are interested. Instead, we are going to jump straight into the configuration of SparkJava for WebSockets. So, let’s create a new Kotlin file, called ChatController.kt</p><p>Copy the following code</p><pre>package codemwnci </pre><pre>import com.fasterxml.jackson.databind.ObjectMapper<br>import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper<br>import org.eclipse.jetty.websocket.api.Session<br>import org.eclipse.jetty.websocket.api.annotations.*<br>import spark.Spark.*<br>import java.util.concurrent.atomic.AtomicLong </pre><pre>fun main(args: Array&lt;String&gt;) {    <br>    port(9000)    <br>    staticFileLocation(&quot;/public&quot;)    <br>    webSocket(&quot;/chat&quot;, ChatWSHandler::class.java)    <br>    init()<br>}</pre><pre>@WebSocket<br>class ChatWSHandler {</pre><pre>}</pre><p>We don’t need much more at the moment. This code just imports a few things we will need now and later, and then starts a main function to configure SparkJava with the following attributes.</p><ol><li>Running on port 9000</li><li>Pointing to the the publicdirectory that we set up in our resources directory</li><li>Configuring the /chat URL to work websockets</li><li>Starting up the SparkJava server</li></ol><p>If we run this code now, it doesn’t do much other than starting the server. If we navigated to any URL on port 9000 we would get a 404 — Not Found error, as we have put no further routes in our code, nor put in any html files in our public directory.</p><p>So let’s fix that, and create our index.html file in the /resources/public directory.</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>&lt;head&gt;    <br>  &lt;meta charset=&quot;UTF-8&quot;&gt;    <br>  &lt;title&gt;Chat - Websocket Kotlin&lt;/title&gt;     <br>  &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1&quot;&gt;    <br>  &lt;link rel=&quot;stylesheet&quot; href=&quot;//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css&quot;&gt;    <br>  &lt;link rel=&quot;stylesheet&quot; href=&quot;//cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css&quot;&gt;    <br>  &lt;script src=&quot;//ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js&quot;&gt;&lt;/script&gt;     <br>  &lt;style&gt;        <br>    .full-height { height: 100%; }        <br>    .input-text  { height: 10%;  }        <br>    .chat-text   { height: 90%;  }        <br>    .border      { border: 1px black; }    <br>  &lt;/style&gt;<br>&lt;/head&gt;<br>&lt;body class=&quot;full-height&quot;&gt;    <br>  &lt;div class=&quot;container-fluid full-height&quot;&gt;        <br>    &lt;div class=&quot;row chat-text&quot;&gt;            <br>      &lt;div class=&quot;col-md-10 border chat-text&quot; id=&quot;chatbox&quot;&gt;&lt;/div&gt;                  <br>      &lt;div class=&quot;col-md-2 border chat-text&quot;&gt;<br>        &lt;ul id=&quot;userlist&quot;&gt;&lt;/ul&gt;            <br>      &lt;/div&gt;        <br>     &lt;/div&gt;        <br>    &lt;div class=&quot;row input-text border&quot;&gt;            <br>      &lt;div class=&quot;col-md-10&quot;&gt;                <br>        &lt;input type=&quot;text&quot; class=&quot;btn-block&quot; id=&quot;msg&quot; /&gt;            <br>      &lt;/div&gt;            <br>      &lt;div class=&quot;col-md-2&quot;&gt;                <br>        &lt;button type=&quot;button&quot; class=&quot;btn btn-primary btn-block btn-lg&quot; id=&quot;send&quot;&gt;Send&lt;/button&gt;<br>      &lt;/div&gt;        <br>    &lt;/div&gt;    <br>  &lt;/div&gt;   <br>  &lt;script&gt;        <br>   var webSocket = new WebSocket(&quot;ws://&quot; + location.hostname + &quot;:&quot; + location.port + &quot;/chat/&quot;);        <br>   webSocket.onmessage = function (msg) {   <br>     receievMsg(JSON.parse(msg.data)) <br>   }        <br>   webSocket.onclose = function(){ alert(&quot;Server Disconnect You&quot;); }        <br>   webSocket.onopen = function(){            <br>     var name = &quot;&quot;;            <br>     while (name == &quot;&quot;) name = prompt(&quot;Enter your name&quot;);              <br>     sendMessage(&quot;join&quot;, name);        <br>   }        <br>   $(&quot;#send&quot;).click(function () {            <br>     sendMessage(&quot;say&quot;, $(&quot;#msg&quot;).val());        <br>   });        <br>   $(&quot;#msg&quot;).keypress(function(e) {            <br>     if(e.which == 13) sendMessage(&quot;say&quot;, e.target.value);             <br>   });        <br>   <br>   function sendMessage(type, data) {            <br>     if (data !== &quot;&quot;) {                   <br>       webSocket.send(JSON.stringify({type: type, data: data}));                  <br>       $(&quot;#msg&quot;).val(&quot;&quot;);                <br>       $(&quot;#msg&quot;).focus();            <br>     }        <br>   }        <br>   function receievMsg(msg) {            <br>     if (msg.msgType == &quot;say&quot;) {                  <br>       $(&quot;#chatbox&quot;).append(&quot;&lt;p&gt;&quot;+msg.data+&quot;&lt;/p&gt;&quot;);            <br>     }            <br>     else if (msg.msgType == &quot;join&quot;) {                  <br>       addUser(msg.data);            <br>     }            <br>     else if (msg.msgType == &quot;users&quot;) {                <br>       msg.data.forEach(function(el) { addUser(el); });            <br>     }            <br>     else if (msg.msgType == &quot;left&quot;) {                <br>       $(&quot;#user-&quot;+msg.data.id).remove();            <br>     }        <br>   }        <br>   function addUser(user) {            <br>     $(&quot;#userlist&quot;).append(&quot;&lt;li id=&#39;user-&quot;+user.id+&quot;&#39;&gt;&quot;+user.name+&quot;&lt;/li&gt;&quot;);        <br>   }    <br>&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre><p>This code starts off by including JQuery and Bootstrap, and then using Bootstrap to add a few DIVs to create two rows and two columns on each. The script then executes and carries out the following activities</p><ol><li>Opens a websocket connection to our /chat URL</li><li>Creates a function that calls the receiveMsg function when a message is received from the server.</li><li>Creates a function that handles a socket close (disconnect from the server), that outputs a simple alert.</li><li>Creates a function that handles the socket open event. Here we ask the user to input their name, and then sends this to the server as a JSON message via the sendMessage function that is created in point 6.</li><li>Next we create a click event (on send button click) and button press event (to capture an enter key). Both send a JSON message with the text that was entered in the text box.</li><li>The sendMessage function sends a JSON object via the websocket to the server, and then clears the text box.</li><li>Finally the receiveMessage function that handles websocket messages is created. This deals with a “say” request, by adding a new paragraph to the chat window. The “join” request adds a new list item to the list of users. The “users” request iterates through all the users in the array and adds them to the list of users. Finally, the “left” request removes a user from the list.</li></ol><p>Now if we restart the server, we should see the chat window, but still won’t see anything happening because we haven’t completed our server-side code. So, let’s finish off that code.</p><pre>class User(val id: Long, val name: String)<br>class Message(val msgType: String, val data: Any)<br><br>@WebSocket<br>class ChatWSHandler {<br><br>    val users = HashMap&lt;Session, User&gt;()<br>    var uids = AtomicLong(0)<br><br>    @OnWebSocketConnect<br>    fun connected(session: Session) = <em>println</em>(&quot;session connected&quot;)<br><br>    @OnWebSocketMessage<br>    fun message(session: Session, message: String) {<br>        val json = ObjectMapper().readTree(message)<br>        // {type: &quot;join/say&quot;, data: &quot;name/msg&quot;}<br>        when (json.get(&quot;type&quot;).asText()) {<br>            &quot;join&quot; -&gt; {<br>                val user = User(uids.getAndIncrement(), json.get(&quot;data&quot;).asText())<br>                users.put(session, user)<br>                // tell this user about all other users<br>                emit(session, Message(&quot;users&quot;, users.values))<br>                // tell all other users, about this user<br>                broadcastToOthers(session, Message(&quot;join&quot;, user))<br>            }<br>            &quot;say&quot; -&gt; {<br>                broadcast(Message(&quot;say&quot;, json.get(&quot;data&quot;).asText()))<br>            }<br>        }<br>        <em>println</em>(&quot;json msg ${message}&quot;)<br>    }<br><br><br>    @OnWebSocketClose<br>    fun disconnect(session: Session, code: Int, reason: String?) {<br>        // remove the user from our list<br>        val user = users.remove(session)<br>        // notify all other users this user has disconnected<br>        if (user != null) broadcast(Message(&quot;left&quot;, user))<br>    }<br><br><br>    fun emit(session: Session, message: Message) = session.<em>remote</em>.sendString(jacksonObjectMapper().writeValueAsString(message))<br>    fun broadcast(message: Message) = users.<em>forEach</em>() <strong>{ </strong>emit(<strong>it</strong>.key, message) <strong>}<br>    </strong>fun broadcastToOthers(session: Session, message: Message) = users.<em>filter </em><strong>{ it</strong>.key != session <strong>}</strong>.forEach() <strong>{ </strong>emit(it.<em>key</em>, message)<strong>}<br><br></strong>}</pre><p>First off, we create two data classes User and Message to represent the JSON objects that we send back to the HTML file that we have just completed.</p><p>Inside of the websocket handler, we start by creating some state for our chat application, with a list of users and their associated Sessions. The Sessions are the objects that keep hold of the TCP connection, and will be used later when communicating to the websockets.</p><p>We then create 3 annotation to deal with open, close and message events.</p><p><strong><em>Open</em></strong>: we don’t really need this for our chat application, so we simply println that a user has connected.</p><p><strong><em>Close</em></strong>: for this event, we simply remove the session from our list of users in the chat room and then broadcast the message that this user has left to all remaining users. <strong>Warning</strong>: Don’t forget the Nullable ? String reason of the disconnect function. If you miss this, the OnWebSocketClose function will not be triggered, but you won’t necessarily get an error message to explain why!</p><p><strong><em>Message</em></strong>: for this event, we deal with two types of messages. A “say” event, or a “join” event. Here we make use of Kotlin’s great where . When a “say” event is received, we simply broadcast this to all users in the chat room. When a “join” event is received, we create a new User object (also getting and incrementing the ID), add the user to the list of users, send all the User objects to the client who just joined, and then sends a “join” message to all other sessions.</p><p>Finally, to finish off, we create the 3 functions that we have just used in the Close / Message functions to <strong>broadcast </strong>to all, send to one (<strong>emit</strong>), and send to all others (<strong>broadcastToOthers</strong>). These are all very similar functions, so we will explain each in turn.</p><p><strong><em>emit</em></strong>: this is the basis for all our broadcast functions, and serves as a function to send a message to a single websocket Session. The code picks up the connection via the remote property, and then calls sendString, passing in a JSON string that has been converted via the JacksonObjectMapper.</p><p><strong><em>broadcast</em></strong>: this function simply calls the forEach function on the HashMap of users, which gives us access to each websocket Session object. From this, the emit function (described above) is called for each one.</p><p><strong><em>broadcastToOthers</em></strong>: this function is a slight variation on the broadcast function described previously. in that the forEach is only called once a filter is executed which excludes the passed in Session object, to ensure that only the other Sessions are sent the message.</p><p>And, that folks, is it. WebSockets, with no magic, and no trickery. Just Kotlin and SparkJava.</p><p>If you would like more in-depth explanations of anything, please leave a comment. If you like the YouTube video, I’d also appreciate it if you could subscribe to the channel. I hope you have found this interesting and informative!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dd6d863e98e7" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>