<?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 Domagoj Madunić on Medium]]></title>
        <description><![CDATA[Stories by Domagoj Madunić on Medium]]></description>
        <link>https://medium.com/@domagoj.madunic?source=rss-24eefdb9af7e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*4Fc-xLAYOBsqUrw57aKvcQ.jpeg</url>
            <title>Stories by Domagoj Madunić on Medium</title>
            <link>https://medium.com/@domagoj.madunic?source=rss-24eefdb9af7e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 18:27:51 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@domagoj.madunic/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[Setup Firebase Cloud Messaging for JHipster generated application (Angular 11/Spring boot)]]></title>
            <link>https://medium.com/agency04/setup-firebase-cloud-messaging-for-jhipster-generated-application-angular-11-spring-boot-f5f45033efee?source=rss-24eefdb9af7e------2</link>
            <guid isPermaLink="false">https://medium.com/p/f5f45033efee</guid>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[jhipster]]></category>
            <dc:creator><![CDATA[Domagoj Madunić]]></dc:creator>
            <pubDate>Sun, 11 Jul 2021 17:07:06 GMT</pubDate>
            <atom:updated>2023-01-20T09:04:50.094Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iOv6uo3JTErotkDvH0x3BA.png" /></figure><p>In the <a href="https://agency04.com/creating-a-spring-petclinic-app-with-jhipster/">previous post</a> we have demonstrated the power and the ease of use of <strong>JHipster</strong> code generator by building the famous Spring “Pet Clinic” application, with the <strong>Spring Boot / Angular</strong> as its tech stack. In this blog we will show how to integrate Angular based application with Google’s <strong>Firebase Cloud Messaging (FCM)</strong> service. Google’s Firebase cloud messaging provides an infrastructure along with the API abstraction to send messages across the range of devices, including Android, iOS and Web apps. FCM can be used to send messages directly to the specific device, or to a topic, for messages to be consumed by multiple devices subscribed to it. Later is the showcase for this blog.</p><p>That said, in this exercise we will build from scratch JHipster generated <strong>Spring Boot/Angular (v 11.x)</strong> application whose backend will provide the continuous feed of messages to a <strong>FCM</strong> topic, which will be consumed by the Angular web client.</p><p>To be able to <em>hands-on</em> follow this blog post, you will need to have the following tools in place: Git, Java JDK, Nodejs, npm and JHipster (version 7.0.1. at the time of writing of this post). For the detailed instructions on how to setup your dev environment please take a look at JHipster official <a href="https://www.jhipster.tech/installation/">setup guide</a>.</p><h3>1. Create JHipster project and configure Google Firebase SDK</h3><p>The first step is to create application skeleton. Open the terminal and issue the following commands:</p><pre>mkdir jhfcm<br>cd jhfcm/<br>jhipster</pre><p>When prompted to do so, answer the JHipster wizard’s questions as shown in the image (and the listing) bellow:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BXK3tbJvkq8kzfu9GW2jtA.png" /></figure><p>Read the full story on the <a href="https://wearenotch.com/firebase-cloud-messaging-setup-for-jhipster-generated-angular-11-application/">link</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f5f45033efee" width="1" height="1" alt=""><hr><p><a href="https://medium.com/agency04/setup-firebase-cloud-messaging-for-jhipster-generated-application-angular-11-spring-boot-f5f45033efee">Setup Firebase Cloud Messaging for JHipster generated application (Angular 11/Spring boot)</a> was originally published in <a href="https://medium.com/agency04">Agency04</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Configuring a loading bar for Angular 9 application]]></title>
            <link>https://medium.com/agency04/configuring-a-loading-bar-for-angular-9-application-5c060532d689?source=rss-24eefdb9af7e------2</link>
            <guid isPermaLink="false">https://medium.com/p/5c060532d689</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[jhipster]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[loading-bar]]></category>
            <category><![CDATA[pet-clinic]]></category>
            <dc:creator><![CDATA[Domagoj Madunić]]></dc:creator>
            <pubDate>Wed, 19 Aug 2020 09:51:40 GMT</pubDate>
            <atom:updated>2020-12-16T13:58:06.156Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q1SC55GVFMc7bVwpjqVDoA.png" /></figure><p>As every seasoned Web developer is painfully aware of, web applications tend to behave “slightly” different once they are deployed to the target server environment. Our new super coll web app, that had ninja time instant responses while running in <strong>local dev environment</strong> (on localhost), once deployed to the server, becomes the subject to the network lags, glitches in the infrastructure, failures of other systems that it depends on and so forth.</p><p>Keeping users informed that something is happening and that system is busy executing their actions is one of the main principles in good user interface design. In that regard loading or progress bars have proven to be very effective tools of communication to the app users that their action has been received and that system is busy performing it.</p><p><strong>In this blog post we will demonstrate how to add loading bar to the JHipster generated Angular web application.</strong> In <a href="https://medium.com/agency04/creating-spring-petclinic-app-with-jhipster-bd8e4366b789">the previous blog post</a> we have generated JHipster/Angular version of the famous Spring Petclinic application, we will use this app as a playground for the purposes of this tutorial to demonstrate how to improve user experience with the use of <strong>ngx-loading-bar</strong> library. For more details on <strong>ngx-loading-bar</strong> see the <a href="https://github.com/aitboudad/ngx-loading-bar">project’s web site</a>.</p><p>If you would like to follow this article “hands on,” you can do that by cloning the jhpetclinic repository (if you haven’t done it yet) and switching to the <strong>progres_bar_start</strong> branch. This branch represents the starting point for this tutorial. To do so simply execute the following two git commands:</p><pre>git clone <a href="https://github.com/dmadunic/jhpetclinic.git">https://github.com/dmadunic/jhpetclinic.git</a><br>git checkout progress_bar_start</pre><h3>Register and Configure ngx-loading-bar router and http-client modules</h3><p>The first step is to add the required dependencies to the project. In that order, inside the project root folder execute the following commands:</p><pre>npm install @ngx-loading-bar/core @ngx-loading-bar/http-client @ngx-loading-bar/router --save</pre><p>With npm packages in place, now it is time to configure JHpetclinic app to use it. The first thing we will do is to configure loading bar to be shown at the top of the browser window area every time a user navigates to another page. Locate the <strong>app.module.ts</strong> file and add the following lines to it:</p><pre>…<br>// 1. import ngx-loading-bar modules<br><strong>import { LoadingBarModule } from ‘</strong><a href="http://twitter.com/ngx"><strong>@ngx</strong></a><strong>-loading-bar/core’;<br>import { LoadingBarRouterModule } from ‘</strong><a href="http://twitter.com/ngx"><strong>@ngx</strong></a><strong>-loading-bar/router’;</strong></pre><pre><a href="http://twitter.com/NgModule">@NgModule</a>({<br> imports: [<br> BrowserModule,<br> JhpetclinicSharedModule,<br> JhpetclinicCoreModule,<br> JhpetclinicHomeModule,<br> // jhipster-needle-angular-add-module JHipster will add new module here<br> JhpetclinicEntityModule,<br> JhpetclinicAppRoutingModule,<br> // 2. register ngx-loading-bar modules<br> <strong>LoadingBarModule,<br> LoadingBarRouterModule</strong><br> ],<br> declarations: [MainComponent, NavbarComponent, ErrorComponent, PageRibbonComponent, ActiveMenuDirective, FooterComponent],<br> bootstrap: [MainComponent],<br>})<br>export class JhpetclinicAppModule {}</pre><p>Now navigate to: <strong>src/main/webapp/app/layouts/main</strong>, open <strong>main.component.html</strong> file and add the following line to it:</p><pre>&lt;jhi-page-ribbon&gt;&lt;/jhi-page-ribbon&gt;<br>&lt;div&gt;<br>    &lt;router-outlet name=&quot;navbar&quot;&gt;&lt;/router-outlet&gt;<br>&lt;/div&gt;<br>&lt;!-- Add ngx-loading-bar at the top ot the display area --&gt;<br><strong>&lt;ngx-loading-bar color=&quot;#CD67BA&quot; height=&quot;4px&quot;&gt;&lt;/ngx-loading-bar&gt;</strong><br>&lt;div class=&quot;container-fluid&quot;&gt;<br>    &lt;div class=&quot;card jh-card&quot;&gt;<br>        &lt;router-outlet&gt;&lt;/router-outlet&gt;<br>    &lt;/div&gt;</pre><pre>&lt;jhi-footer&gt;&lt;/jhi-footer&gt;<br>&lt;/div&gt;</pre><p>If you start the JHPetclinic app now you will see nice loading bar and the spinner at the top of the window area every time you navigate to a new page (as in the image bellow).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lhf7Cv8QqR1fPk30cB193w.png" /><figcaption>JHPetclinc with loading bar</figcaption></figure><p><strong>ngx-loading-bar</strong> offers several configuration options, for example turning spinner off and on, adjusting the color of the bar, and so on. We will not dive into those here, but feel free to check the <a href="https://github.com/aitboudad/ngx-loading-bar#customize-ngx-loading-bar">official docs</a> for more details.</p><figure><a href="http://bit.ly/MediumAGENCY04"><img alt="" src="https://cdn-images-1.medium.com/max/700/1*7qqbNQH6sjI81Ad0AgFTlQ.png" /></a></figure><p>With this we have taken care of user’s navigation through our app. Now, its time to turn our attention to a little more complicated task, that is of displaying a progress bar when our application is waiting for a response from server to begin navigation to another page.</p><p>To demonstrate this case perform the following:</p><ol><li>Import <strong>jhpetclinic</strong> into your favorite IDE (ie. IntelliJ or Eclipse)</li><li>Run <strong>jhpetclinic</strong> in debug mode and put the break point to the second line of the <strong>org.jhipster.petclinic.web.rest.UserJWTController.authorize()</strong> method as shown on the picture bellow</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Sb-u7GtDkAxqBoYX8q10Cw.png" /></figure><p>Now in the separate terminal window, inside the jhpetclinic root folder start the angular client app:</p><pre>npm start</pre><p>If you attempt to “Sign in” into app now, you will notice that nothing is happening (since we have stopped the process on the server side with the breakpoint). The LoadingBarRouterModule handles only transitions from page to page, yet no transition is happening at the moment, our application is waiting for the data from server. However, our users are left with no indication that anything is happening and would simply (impatiently) had to wait for an HTTP request to time out in order to receive any response from our app. <strong>Needless to say, very undesired behavior</strong>.</p><p>Fortunately, there is a simple way to fix this, all we have to do is configure <strong>@ngx-loading-bar/http-client</strong> library in our application. Similar to the behavior of the <strong>router</strong> module, registered <strong>LoadingBarHttpClientModule</strong> will attach itself to every HTTP request, and trigger display of progress bar while the operation is in progress. To achieve this, first add the npm package, by executing (inside the project root folder):</p><pre>npm install @ngx-loading-bar/http-client --save</pre><p>Now import <strong>LoadingBarHttpClientModule</strong>, by modifying <strong>app.module.ts</strong> file so that it looks as in the code snippet bellow:</p><pre>...<br>// 1. import ngx-loading-bar modules<br>import { LoadingBarModule } from &#39;<a href="http://twitter.com/ngx">@ngx</a>-loading-bar/core&#39;;<br><strong>import { LoadingBarHttpClientModule } from &#39;</strong><a href="http://twitter.com/ngx"><strong>@ngx</strong></a><strong>-loading-bar/http-client&#39;</strong>;<br>import { LoadingBarRouterModule } from &#39;<a href="http://twitter.com/ngx">@ngx</a>-loading-bar/router&#39;;</pre><pre><a href="http://twitter.com/NgModule">@NgModule</a>({<br>  imports: [<br>    BrowserModule,<br>    JhpetclinicSharedModule,<br>    JhpetclinicCoreModule,<br>    JhpetclinicHomeModule,<br>    // jhipster-needle-angular-add-module JHipster will add new module here<br>    JhpetclinicEntityModule,<br>    JhpetclinicAppRoutingModule,<br>    // 2. register ngx-loading-bar modules<br>    LoadingBarModule,<br>    <strong>LoadingBarHttpClientModule, </strong> <br>    LoadingBarRouterModule<br>  ],<br>  declarations: [MainComponent, NavbarComponent, ErrorComponent, PageRibbonComponent, ActiveMenuDirective, FooterComponent],<br>  bootstrap: [MainComponent],<br>})<br>export class JhpetclinicAppModule {}</pre><p>Finally lets also add some modification in the <strong>src/main/webapp/app/layouts/main/mainn.component.html</strong> file, one as displayed in the code snippet bellow.</p><pre>&lt;jhi-page-ribbon&gt;&lt;/jhi-page-ribbon&gt;<br>​<br>&lt;div&gt;<br>    &lt;router-outlet name=&quot;navbar&quot;&gt;&lt;/router-outlet&gt;<br>&lt;/div&gt;<br>&lt;!-- Add ngx-loading-bar at the top ot the display area --&gt;<br><strong>&lt;ngx-loading-bar color=&quot;#CD67BA&quot; height=&quot;4px&quot; [includeSpinner]=&quot;false&quot; ref=&quot;router&quot;&gt;&lt;/ngx-loading-bar&gt;<br>&lt;ngx-loading-bar color=&quot;#CD67BA&quot; height=&quot;4px&quot; ref=&quot;http&quot;&gt;&lt;/ngx-loading-bar&gt;</strong><br>​<br>&lt;div class=&quot;container-fluid&quot;&gt;<br>    &lt;div class=&quot;card jh-card&quot;&gt;<br>        &lt;router-outlet&gt;&lt;/router-outlet&gt;<br>    &lt;/div&gt;<br>​<br>    &lt;jhi-footer&gt;&lt;/jhi-footer&gt;<br>&lt;/div&gt;</pre><p>With this changes we have configured two loading bars, that will be shown (overlapping) at the top of the browser window area.</p><ol><li>The first loading bar will be used by <strong>router</strong> module and will display 4 pixel thick loading bar every time we navigate from page to page.</li><li>The second loading bar will be used by <strong>http-client</strong> module and will display <strong>both</strong> the loading bar and <strong>the spinner</strong> every time an application is performing an HTTP request to the server.</li></ol><p>This way based on the behavior of the loading bar component we can be aware of what our application is waiting for, is there a problem with the client angular code and transition from state to state, or with the server API we are invoking. To test it, you can now repeat the small exercise from the above. If all is well, you should see the loading bar and the spinner while Angular app is waiting for a breakpoint to be released.</p><h3>What next?</h3><p>In case you need more control over the LoadingBar please check <a href="https://github.com/aitboudad/ngx-loading-bar#manually-manage-loading-service">the official docs</a> on how to manually start and stop loading bar, inside a service.</p><h3>Sample Code:</h3><p>Entire source code for this tutorial is available at GitHub repository:</p><p><a href="https://github.com/dmadunic/jhpetclinic">dmadunic/jhpetclinic</a></p><h3>Additional resources:</h3><p><a href="https://jhpetclinic.azurewebsites.net/">JHPetclinic demo</a></p><p><a href="https://github.com/aitboudad/ngx-loading-bar">aitboudad/ngx-loading-bar</a></p><p><strong>Keywords</strong>:</p><p>Angular 9, JHipster, Progress Bar, Petclinic,</p><p><strong>Thank you for reading! I do hope you enjoyed it and please share if you did.</strong></p><figure><a href="http://bit.ly/MediumAGENCY04"><img alt="" src="https://cdn-images-1.medium.com/max/700/1*58jJEfqGw4mwv-m5whRo5Q.png" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5c060532d689" width="1" height="1" alt=""><hr><p><a href="https://medium.com/agency04/configuring-a-loading-bar-for-angular-9-application-5c060532d689">Configuring a loading bar for Angular 9 application</a> was originally published in <a href="https://medium.com/agency04">Agency04</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating Spring PetClinic app with JHipster]]></title>
            <link>https://medium.com/agency04/creating-spring-petclinic-app-with-jhipster-bd8e4366b789?source=rss-24eefdb9af7e------2</link>
            <guid isPermaLink="false">https://medium.com/p/bd8e4366b789</guid>
            <category><![CDATA[pet-clinic]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[jhipster]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Domagoj Madunić]]></dc:creator>
            <pubDate>Mon, 27 Jul 2020 08:40:19 GMT</pubDate>
            <atom:updated>2020-07-29T07:04:37.876Z</atom:updated>
            <content:encoded><![CDATA[<h3>Creating a Spring PetClinic app with JHipster</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m7RZVCfFRIABjpV9wa9WbA.png" /></figure><p>For over a decade and a half, <a href="https://projects.spring.io/spring-petclinic/"><strong>Spring Petclinic application</strong></a> (the first version was developed back in 2003 by Kren Krebs and Juergen Hoeller) has been used as an official demo app designed to show how the Spring stack can be used to build simple, but powerful database-oriented applications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*f37ndc7_IuuGAsrObp2TNQ.png" /><figcaption>Spring PetClinic application</figcaption></figure><p>Today, this app has still not lost on popularity. The <a href="https://spring-petclinic.github.io/">Spring PetClinic Community</a> site, in addition to the official Spring version, hosts a wide range of other showcases of the PetClinic app, each demonstrating various application development scenarios for the Spring framework stack. These come in many flavors, ranging from the Kotlin based one, versions demonstrating use of different persistent technologies (Jdbc/JPA), the REST based version of PetClinic app with both ReactJs and Angular frontend apps, to the fully distributed microservices version of the PetClinic application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*PFUBfBkpbKFwiDkASWU-bg.png" /><figcaption>Distributed version of Spring PetClinic</figcaption></figure><p>In this blog post we will (re)create this legendary application by using powerful <strong>JHipster</strong> code generator . For those not familiar with the JHipster, <em>it is a development platform to quickly generate, develop &amp; deploy modern web applications &amp; microservice architectures</em>. Make sure to check out its <a href="https://www.jhipster.tech/">official web site</a> for more details.</p><h3>What exactly are we going to build?</h3><p>We will use JHipster to generate a simple <strong>monolith</strong> version of the JHipster PetClinic application name <strong>jhpetclinic</strong>, one that uses the same database model as the original PetClinic app. Furthermore, we will also use JHipster to scaffold a simple Angular based client app that provides base CRUD functionality for all application entities. If you prefer ReactJs, feel free to chose ReactJs as a technology for the frontend stack instead of Angular.</p><p>Our main goal in this exercise is that our <strong>jhpetclinic</strong> app on the model level matches as much as possible the original Spring PetClinic version.</p><h4>Prerequisites</h4><p>To be able to follow <em>hands-on</em> this blog post, you will need to have the following tools in place: Git, Java JDK, Nodejs, npm, yeoman and JHipster. For the detailed instructions on how to setup your dev environment please take a look at JHipster official <a href="https://www.jhipster.tech/installation/">setup guide</a>.</p><figure><a href="http://bit.ly/MediumAGENCY04"><img alt="" src="https://cdn-images-1.medium.com/max/700/1*AbDaga_zeoInKDdhGXJDJQ.png" /></a></figure><h3>Generate application skeleton</h3><p>Once you have all prerequisites met, and you are able to issue <strong>jhipster</strong> command without any errors, it is time to begin. As a first step, create a root project folder and start <strong>jhipster</strong> generator inside it, as shown bellow:</p><pre>mkdir jhpetclinic<br>cd jhpetclinic/<br>jhipster</pre><p>When prompted to do so, answer the JHipster wizard’s questions as shown in the image (and the listing) bellow:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6wVP-8guD-Tw8Pxt0cMFvQ.png" /><figcaption>jhipster wizard questions and answers</figcaption></figure><pre>? Which *type* of application would you like to create? Monolithic application (recommended for simple projects)<br>? [Beta] Do you want to make it reactive with Spring WebFlux? No<br>? What is the base name of your application? jhpetclinic<br>? What is your default Java package name? org.jhipster.petclinic<br>? Do you want to use the JHipster Registry to configure, monitor and scale your application? No<br>? Which *type* of authentication would you like to use? JWT authentication (stateless, with a token)<br>? Which *type* of database would you like to use? SQL (H2, MySQL, MariaDB, PostgreSQL, Oracle, MSSQL)<br>? Which *production* database would you like to use? PostgreSQL<br>? Which *development* database would you like to use? PostgreSQL<br>? Do you want to use the Spring cache abstraction? Yes, with the Ehcache implementation (local cache, for a single node)<br>? Do you want to use Hibernate 2nd level cache? Yes<br>? Would you like to use Maven or Gradle for building the backend? Gradle<br>? Which other technologies would you like to use? <br>? Which *Framework* would you like to use for the client? Angular<br>? Would you like to use a Bootswatch theme (https://bootswatch.com/)? Flatly<br>? Choose a Bootswatch variant navbar theme (https://bootswatch.com/)? Primary<br>? Would you like to enable internationalization support? Yes<br>? Please choose the native language of the application English<br>? Please choose additional languages to install <br>? Besides JUnit and Jest, which testing frameworks would you like to use? <br>? Would you like to install other generators from the JHipster Marketplace? No</pre><p>With this we have instructed JHipster to generate a Spring Boot monolith application, which will use a relational database for persistence, JWT for security, both <em>ehcache</em> and 2nd level Hibernate caches for caching, Gradle as the main build tool and Angular as the client framework.</p><h3>Configuring dev environment</h3><p>As you can see above, we have chosen Postgres as the target database for both the development and production. Accordingly, for the <strong>dev</strong> environment JHipster pre-configured our datasource to use local Postgres instance and to connect to database named <strong>jhpetclinic</strong> with the user of the same name (jhpetclinic) and an empty string for password. Furthermore, in case that you do not have installed local Postgres instance, JHipster also prepared a docker-compose file which can be used to launch Postgres instance configured to match this setup as docker service by running the following line from the project root:</p><pre>docker-compose -f src/main/docker/postgres.yml up</pre><p>Let’s change this base setting a little, so that the empty password is not used. This can lead to some problems in the case when you would like to use locally installed Postgres in combination with Postgres as a docker service. Open the file: “<strong>./src/main/resources/config/application-dev.yml</strong>” and change the datasource section to match the snippet bellow:</p><pre>datasource:<br>    type: com.zaxxer.hikari.HikariDataSource<br>    url: jdbc:postgresql://localhost:5434/jhpetclinic<br>    username: jhpetclinic<br>    password: jhpetclinic</pre><p>Now navigate to and open the file: “<strong>./src/main/docker/postgres.yml</strong>” and change the <strong>environment</strong> block so it includes the password for the jhpetclinic user:</p><pre>environment:<br>      - POSTGRES_USER=jhpetclinic<br>      - POSTGRES_PASSWORD=jhpetclinic<br>      - POSTGRES_HOST_AUTH_METHOD=trust</pre><p>In case you would like to use existing Postgres instance instead of Postgres run as docker service, you still need to create the jhipster database and role. In that order, connect to your target instance with the superuser privileges and execute the following commands:</p><pre>-- Create database jhpetclinic, user jhpetclinic and and grant all priviliges to user<br>CREATE DATABASE jhpetclinic;<br>CREATE jhpetclinic NOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT LOGIN PASSWORD &#39;jhpetclinic&#39;;<br>GRANT ALL PRIVILEGES ON DATABASE jhpetclinic TO jhpetclinic;</pre><p>Whichever scenario of these two you have chosen, either to use Postgres as a docker service or a fully installed local instance, now you have database setup to receive your request and you can start up your <strong>jhpetclinic</strong> application.</p><p>To do so simply run the following command:</p><pre>./gradlew</pre><p>This will compile and build your app and start it with the “<strong>dev</strong>” and “<strong>swagger</strong>” as active spring profiles. Now, if you open another terminal and run:</p><pre>npm start</pre><p>and point your browser to: <a href="http://localhost:9000/">http://localhost:9000</a> you will see the default welcome page for the Jhipster generated app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w5eXyFnlFuqFYQVuq_ZncA.png" /><figcaption>JHPetClinic welcom screen</figcaption></figure><p>You can sign in and look around using some of the pre-configured accounts: user or admin. Though it seems that there is not much to be seen, <strong>yet(!)</strong>, in reality, under the hood, a lot of work has been done for us.</p><p>We have a running application with the configured gradle and npm build scripts, configured Liquibase tooling to control changes in our database, configurations to run our app as a docker service, aspect based monitoring and logging of all http requests, the support for internationalization (both on the client and server side), configured JWT based Spring Security, fully implemented “sign in,” register and “forgot your password” workflows, the full user management and much more.</p><p>All of this has been done by JHipster for us. What remains to be done is to create our business entities, their JPA Repositories, Services and Resource Controllers.</p><h3>The real stuff: generate model, services, REST API and the Angular client</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/416/1*j3T-_2xCGYA_Qg-F-nMb6w.png" /><figcaption>PetClinic data model</figcaption></figure><p>As can be seen from the ER diagram above, Petclinic application model consists of the following six entities:</p><ul><li>vets — Veterinarians</li><li>specialties — Specializations of the Veterinarians</li><li>owners — Pet owners</li><li>pets — Pets themselves</li><li>types — Types of the pets (ie. cats, birds, dogs, ….)</li><li>visits — Records of the pet visits to the veterinarians</li></ul><p>One of the most powerful features of the JHipster is its <a href="https://www.jhipster.tech/jdl/"><strong>Domain Language (JDL)</strong></a>. With JHipster Domain language (<strong>JDL</strong>), using a user-friendly syntax, we can describe all our entities and their relationships in a single file (or in a more than one), and then supply this file(s) to the JHipster generator and let him generate all the code for us.</p><p>Additionally, JDL can be used not only to describe entities and their relationship, but also to describe our applications, deployments, and much more that is beyond the scope of this article.</p><p>What follows, in the code snippet bellow, is the JDL definition of the PetClinic entities and their relationships. Diving deep into JDL is beyond the scope of this blog post but if you would like to learn more on how to use JDL to describe entities and their relationships be sure to check the <a href="https://www.jhipster.tech/jdl/entities-fields">official documentation</a> which provides rather good instructions.</p><pre>entity PetType(types) {<br>    name String required maxlength(80)<br>}<br>​<br>entity Specialty(specialties) {<br>    name String required maxlength(80)<br>}<br>​<br>entity Vet(vets) {<br>    firstName String required maxlength(30)<br>    lastName String required maxlength(30)<br>}<br>​<br>entity Owner(owners) {<br>    firstName String required maxlength(30)<br>    lastName String required maxlength(30)<br>    address String required maxlength(255)<br>    city String required maxlength(80)<br>    telephone String required maxlength(20)<br>}<br>​<br>entity Pet(pets) {<br>    name String required maxlength(30)<br>    birthDate LocalDate<br>}<br>​<br>entity Visit(visits) {<br>    visitDate LocalDate<br>    description String required maxlength(255)<br>}<br>​<br>// --- Relationships ----------------------------------------------</pre><pre>relationship OneToMany {<br>  Owner{pets(name)} to Pet{owner(lastName)}<br>  Pet{visits} to Visit{pet(name)}<br>}<br>​<br>relationship ManyToOne {<br>  Pet{type(name)} to PetType<br>}<br>​<br>relationship ManyToMany{<br>    Vet{specialties(name)} to Specialty{vets}<br>}<br>​<br>// --- Application options ----------------------------------------<br>​<br>// Set pagination options<br>paginate PetType, Specialty, Vet, Owner, Pet, Visit with pagination<br>​<br>// We will use DTO&#39;s and not expose domain classes directly<br>dto * with mapstruct<br>​<br>// Set service options to all except few<br>service all with serviceImpl<br>​<br>filter Vet, Owner, Pet, Visit</pre><p>Copy/paste the code above and save it to the location of your choice under the name of <strong>petclinic.jh</strong>. Now it is time to let JHipster generate some code ;-)</p><p>To do so, open the terminal and run the command bellow, and when prompted by wizard concerning the conflict in files simply answer with “<strong>a</strong>” (ie. <em>overwrite this one and all others</em>).</p><pre>jhipster import-jdl path_to_the_downloaded_file/petclinic.jh</pre><p>As you can see from the console log, JHipster has created a lot of files :-) In short, for each of our entities the following has been create on the <strong>server side</strong>:</p><ul><li>JPA Class representation of an entity</li><li>Liquibase change set to create an entity table in the database</li><li>SpringData JPa Repository for the entity</li><li>Service, both interface and implementation, with base CRUD operations</li><li>DTO representation of the entity</li><li><a href="https://mapstruct.org/">Mapstruct</a> mapper to map entity to DTO</li><li>Resource controller that provides a rest interface for base CRUD operations</li></ul><p>Furthermore, the resource controller will also provide the single GET endpoint with the ability to filter the entity based on its attributes (for more on this powerful feature of JHipster see: <a href="https://www.jhipster.tech/entities-filtering/">Filtering Entities</a>)</p><p>In addition, JHipster has also performed the following tasks: configured <em>ehcache</em> for all our entities, created swagger documentation for rest API endpoints. Last but not least, it also generated the full Angular front end app with simple CRUD functionality for all of our entities.</p><p>However before starting this newly generated app, we need to tweak it a little bit with a few changes to the generated code so that in the end our model matches the original PetClinic one. The first thing we need to do is to change all generated JPA entity classes.</p><h3>Fix @Id property of all JPA entity classes</h3><p>The authors of the Spring PetClinic application decided that all primary keys of their entities should be generated by GenerationType.IDENTITY strategy. This assumes that the ID of the entity will be generated by the database using <strong>idnetity</strong> column. For example, in the case of <strong>h2</strong> or <strong>mysql</strong> databases this assumes marking primary key fields in the database with a <strong>AUTO_INCREMENT</strong> attribute, and for Postgres using utility field types <strong>serial</strong> or <strong>identity</strong> (for Postgres 10+).</p><p>On the other hand, JHipster by default generates all entity identity fields in the following manner:</p><pre>@Id<br>@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = &quot;sequenceGenerator&quot;)<br>@SequenceGenerator(name = &quot;sequenceGenerator&quot;)<br>private Long id;</pre><p>In this setup the value for the primary key for all the entities will be taken from the single sequence (named <strong>sequence_generator</strong>). There is a long discussion concerning why each of this approaches is better or worst than the other, and I will not dive into it. As we have noted at the beginning of this blog post we will strive for our JHipstet PetClinc app to resemble the model of the original Spring version as much as possible.</p><p>Therefore, in all of the generated entity JPA classes (Owner, Pet, PetType, Specialty, Vet, Visit):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/367/1*wqDgYqO4ELUcZvww2BvW3w.png" /><figcaption>JHPetclini JPA entities</figcaption></figure><p>change the definition of the id property so that it looks as follows:</p><pre>@Id<br>@GeneratedValue(strategy = GenerationType.IDENTITY)<br>private Long id;</pre><p>Before starting up our app, there is one more thing that needs to be done: we need to adjust generated Liquibase change sets to match the changes in the JPA classes. For those not familiar with it, <a href="https://www.liquibase.org/">Liquibase</a> is a great tool to track, version, manage and deploy changes to your database. In short, it will generate our tables and if instructed to do so populate it with data.</p><p>For each of the Petclinic entities JHipster has generated a single file of the name pattern: <strong>$timestamp_added_entity_$entityName.xml</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/476/1*vzCBZ6Ole-kRlXeMdO-MNA.png" /><figcaption>Liquibase changeset files</figcaption></figure><p>Now in each of these six files locate the following block of code:</p><pre>&lt;column name=&quot;id&quot; type=&quot;bigint&quot;&gt;<br>    &lt;constraints primaryKey=&quot;true&quot; nullable=&quot;false&quot;/&gt;<br>&lt;/column&gt;</pre><p>and change it to look as in the snippet bellow:</p><pre>&lt;column name=&quot;id&quot; type=&quot;bigint&quot; autoIncrement=&quot;true&quot;&gt;<br>    &lt;constraints primaryKey=&quot;true&quot; nullable=&quot;false&quot;/&gt;<br>&lt;/column&gt;</pre><p>With these changes in place, it is time to start our jhpetclinic application again. First start the REST backend by opening the terminal and issuing the following command:</p><pre>./gradlew</pre><p>followed by (in another terminal window):</p><pre>npm start</pre><p>If you sign in to your JHipster app now, you will notice that there is a menu entry under Entities for each of the Petclinc’s entities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*etJ69SuXo_SVIJ95nMZ4VQ.png" /></figure><p>In addition to playing with the newly generated Angular client, you can now also take a look at the generated swagger documentation for the application’s REST endpoints.</p><p>To do so, point your browser to the following url: <a href="http://127.0.0.1:8080/swagger-ui/index.html">http://127.0.0.1:8080/swagger-ui/index.html</a> (just make sure you have previously signed in).</p><p>Generated swagger documentation is a great way to explore but also to test REST endpoints. I strongly suggest to go ahead and use swagger to familiarize yourself with the filtering capabilities of the generated REST endpoints.</p><p>You might have noticed that our tables are filled with some gibberish data. That is because JHipster has generated “fake” data for each of our entities. We will now populate our tables with the same initial data as the one in the original PetClinic application.</p><p><strong>If you have REST Api and Angular client running, please stop them before proceeding to the next steps.</strong></p><p>The first thing that you have to do is to disable fake data to be loaded on the application startup. To do so open the: <strong>src/main/resources/config/application-dev.yml</strong> file and locate the following block of configuration:</p><pre>liquibase:<br>  # Remove &#39;faker&#39; if you do not want the sample data to be loaded automatically<br>  contexts: dev, faker</pre><p>As the comment says, simply remove “faker” context from the last line.</p><p>Now, using your favorite db tool, drop all the tables created by Liquibase. Make sure to do it with the cascade option which will make all linked sequences, indexes and constraints also to be dropped (however, you will still need to manually drop the sequence “sequence_generator”).</p><pre>INSERT INTO vets VALUES (1, &#39;James&#39;, &#39;Carter&#39;);<br>INSERT INTO vets VALUES (2, &#39;Helen&#39;, &#39;Leary&#39;);<br>INSERT INTO vets VALUES (3, &#39;Linda&#39;, &#39;Douglas&#39;);<br>INSERT INTO vets VALUES (4, &#39;Rafael&#39;, &#39;Ortega&#39;);<br>INSERT INTO vets VALUES (5, &#39;Henry&#39;, &#39;Stevens&#39;);<br>INSERT INTO vets VALUES (6, &#39;Sharon&#39;, &#39;Jenkins&#39;);<br>​<br>INSERT INTO specialties VALUES (1, &#39;radiology&#39;);<br>INSERT INTO specialties VALUES (2, &#39;surgery&#39;);<br>INSERT INTO specialties VALUES (3, &#39;dentistry&#39;);<br>​<br>INSERT INTO vets_specialties(vet_id, specialties_id) VALUES (2, 1);<br>INSERT INTO vets_specialties(vet_id, specialties_id) VALUES (3, 2);<br>INSERT INTO vets_specialties(vet_id, specialties_id) VALUES (3, 3);<br>INSERT INTO vets_specialties(vet_id, specialties_id) VALUES (4, 2);<br>INSERT INTO vets_specialties(vet_id, specialties_id) VALUES (5, 1);<br>​<br>INSERT INTO types VALUES (1, &#39;cat&#39;);<br>INSERT INTO types VALUES (2, &#39;dog&#39;);<br>INSERT INTO types VALUES (3, &#39;lizard&#39;);<br>INSERT INTO types VALUES (4, &#39;snake&#39;);<br>INSERT INTO types VALUES (5, &#39;bird&#39;);<br>INSERT INTO types VALUES (6, &#39;hamster&#39;);<br>​<br>INSERT INTO owners VALUES (1, &#39;George&#39;, &#39;Franklin&#39;, &#39;110 W. Liberty St.&#39;, &#39;Madison&#39;, &#39;6085551023&#39;);<br>INSERT INTO owners VALUES (2, &#39;Betty&#39;, &#39;Davis&#39;, &#39;638 Cardinal Ave.&#39;, &#39;Sun Prairie&#39;, &#39;6085551749&#39;);<br>INSERT INTO owners VALUES (3, &#39;Eduardo&#39;, &#39;Rodriquez&#39;, &#39;2693 Commerce St.&#39;, &#39;McFarland&#39;, &#39;6085558763&#39;);<br>INSERT INTO owners VALUES (4, &#39;Harold&#39;, &#39;Davis&#39;, &#39;563 Friendly St.&#39;, &#39;Windsor&#39;, &#39;6085553198&#39;);<br>INSERT INTO owners VALUES (5, &#39;Peter&#39;, &#39;McTavish&#39;, &#39;2387 S. Fair Way&#39;, &#39;Madison&#39;, &#39;6085552765&#39;);<br>INSERT INTO owners VALUES (6, &#39;Jean&#39;, &#39;Coleman&#39;, &#39;105 N. Lake St.&#39;, &#39;Monona&#39;, &#39;6085552654&#39;);<br>INSERT INTO owners VALUES (7, &#39;Jeff&#39;, &#39;Black&#39;, &#39;1450 Oak Blvd.&#39;, &#39;Monona&#39;, &#39;6085555387&#39;);<br>INSERT INTO owners VALUES (8, &#39;Maria&#39;, &#39;Escobito&#39;, &#39;345 Maple St.&#39;, &#39;Madison&#39;, &#39;6085557683&#39;);<br>INSERT INTO owners VALUES (9, &#39;David&#39;, &#39;Schroeder&#39;, &#39;2749 Blackhawk Trail&#39;, &#39;Madison&#39;, &#39;6085559435&#39;);<br>INSERT INTO owners VALUES (10, &#39;Carlos&#39;, &#39;Estaban&#39;, &#39;2335 Independence La.&#39;, &#39;Waunakee&#39;, &#39;6085555487&#39;);<br>​<br>INSERT INTO pets VALUES (1, &#39;Leo&#39;, &#39;2000-09-07&#39;, 1, 1);<br>INSERT INTO pets VALUES (2, &#39;Basil&#39;, &#39;2002-08-06&#39;, 6, 2);<br>INSERT INTO pets VALUES (3, &#39;Rosy&#39;, &#39;2001-04-17&#39;, 2, 3);<br>INSERT INTO pets VALUES (4, &#39;Jewel&#39;, &#39;2000-03-07&#39;, 2, 3);<br>INSERT INTO pets VALUES (5, &#39;Iggy&#39;, &#39;2000-11-30&#39;, 3, 4);<br>INSERT INTO pets VALUES (6, &#39;George&#39;, &#39;2000-01-20&#39;, 4, 5);<br>INSERT INTO pets VALUES (7, &#39;Samantha&#39;, &#39;1995-09-04&#39;, 1, 6);<br>INSERT INTO pets VALUES (8, &#39;Max&#39;, &#39;1995-09-04&#39;, 1, 6);<br>INSERT INTO pets VALUES (9, &#39;Lucky&#39;, &#39;1999-08-06&#39;, 5, 7);<br>INSERT INTO pets VALUES (10, &#39;Mulligan&#39;, &#39;1997-02-24&#39;, 2, 8);<br>INSERT INTO pets VALUES (11, &#39;Freddy&#39;, &#39;2000-03-09&#39;, 5, 9);<br>INSERT INTO pets VALUES (12, &#39;Lucky&#39;, &#39;2000-06-24&#39;, 2, 10);<br>INSERT INTO pets VALUES (13, &#39;Sly&#39;, &#39;2002-06-08&#39;, 1, 10);<br>​<br>INSERT INTO visits(id, pet_id, visit_date, description) VALUES (1, 7, &#39;2010-03-04&#39;, &#39;rabies shot&#39;);<br>INSERT INTO visits(id, pet_id, visit_date, description) VALUES (2, 8, &#39;2011-03-04&#39;, &#39;rabies shot&#39;);<br>INSERT INTO visits(id, pet_id, visit_date, description) VALUES (3, 8, &#39;2009-06-04&#39;, &#39;neutered&#39;);<br>INSERT INTO visits(id, pet_id, visit_date, description) VALUES (4, 7, &#39;2008-09-04&#39;, &#39;spayed&#39;);<br>​<br>ALTER SEQUENCE owners_id_seq RESTART WITH 100;<br>ALTER SEQUENCE pets_id_seq RESTART WITH 100;<br>ALTER SEQUENCE specialties_id_seq RESTART WITH 100;<br>ALTER SEQUENCE types_id_seq RESTART WITH 100;<br>ALTER SEQUENCE vets_id_seq RESTART WITH 100;<br>ALTER SEQUENCE visits_id_seq RESTART WITH 100;</pre><p>Copy/paste above SQL statements and save them in the project hierarchy as the: <strong>src/main/resources/config/liquibase/data/petclinic-data.sql</strong> file.</p><p>Now open the file: <strong>src/main/resources/config/liquiabse/master.xml</strong> and add the following line to the bottom of the file:</p><pre>    &lt;include file=&quot;config/liquibase/data/petclinic-data.sql&quot; /&gt;<br>&lt;/databaseChangeLog&gt;</pre><p>After doing this, when you run a jhpetclinic app again, you should see its database populated with this data.</p><h3>What’s next?</h3><p>The purpose of the original Spring PetClinc app was to help people learn basics and some of the best practices in the development of web applications using Spring boot framework. This can be applied to the <strong>jhpetclinic</strong> project also, so I suggest you import the <strong>jhpetclinc</strong> code into your favorite IDE and examine for yourself the code that has been generated for you.</p><p>At this stage we have fully functional <strong>jhpetclinic</strong> application. We can add, view, edit and delete all six entities. In difference to the original PetClinic app, in the <strong>jhpetclinic</strong> version we can not search owners, but we have pagination and sort implemented for all entities. Just for the purpose of flavour, I have added the original Spring PetClinic banner, and replaced JHipster artwork with the PetClinic’s one on the homepage (to see this final result checkout v0.2.0 tag on the master branch) .</p><p>All further feature changes, for example, implementation of the search of owners by name and more complex detailed view of the Owner (with the same features as in the original PetClinic app) require only proficiency with Angular or ReactJs and has nothing more to do with JHipster. In this blog post we have demonstrated how easy it is to scaffold the entire functional application using JHipster, the only prerequisite being familiarity with JHipster’s JDL.</p><p><em>Fully tweaked Angular app (process finished in less than a day!) that behave (almost) the same as the original PetClinic app, yet without modified look, but with slightly more functional UI is available as the final product at this project’s </em><a href="https://github.com/dmadunic/jhpetclinic"><em>code repository</em></a><em>.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qSpxUmJsk4woW7_1ltT9Vg.png" /><figcaption>jhpetclinic owners list with the search form and pagination.</figcaption></figure><p><strong>Good coding!</strong></p><h3>Sample Code:</h3><p>Entire source code for this tutorial is available at GitHub repository:</p><p><a href="https://github.com/dmadunic/jhpetclinic">dmadunic/jhpetclinic</a></p><p>Alos, online demo version of the <a href="https://jhpetclinic.azurewebsites.net/">jhpetclinic</a> application can be found <a href="https://jhpetclinic.azurewebsites.net/">here</a>.</p><h3>Additional resources:</h3><p><a href="https://www.jhipster.tech/">JHipster homepage</a></p><p><a href="https://github.com/spring-projects/spring-petclinic">Spring Petclinic GitHub page</a></p><p><a href="https://spring-petclinic.github.io/">Spring Petclinic Community</a></p><p><strong>Keywords</strong>:</p><p>JHipster, Java, Spring Boot, Petclinic</p><p><strong>Thank you for reading! I do hope you enjoyed it and please share if you did.</strong></p><figure><a href="http://bit.ly/MediumAGENCY04"><img alt="" src="https://cdn-images-1.medium.com/max/700/1*Y3ED-wf8BUuvqZmAfXdACw.png" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bd8e4366b789" width="1" height="1" alt=""><hr><p><a href="https://medium.com/agency04/creating-spring-petclinic-app-with-jhipster-bd8e4366b789">Creating Spring PetClinic app with JHipster</a> was originally published in <a href="https://medium.com/agency04">Agency04</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Developing CLI application with Spring Shell (part 5)]]></title>
            <link>https://medium.com/agency04/developing-cli-application-with-spring-shell-part-5-c13403cb79b4?source=rss-24eefdb9af7e------2</link>
            <guid isPermaLink="false">https://medium.com/p/c13403cb79b4</guid>
            <category><![CDATA[cli]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[spring-security]]></category>
            <category><![CDATA[spring-shell]]></category>
            <dc:creator><![CDATA[Domagoj Madunić]]></dc:creator>
            <pubDate>Tue, 11 Jun 2019 13:55:49 GMT</pubDate>
            <atom:updated>2020-02-24T11:09:03.750Z</atom:updated>
            <content:encoded><![CDATA[<h3>Part 5: Developing CLI application with Spring Shell</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4QnELL2o_wbRucPtsmzEFw.png" /></figure><p>In this post, we are going to configure <a href="https://spring.io/projects/spring-security"><strong>Spring Security</strong></a> for our Spring Shell <em>clidemo</em> application. Spring Security is a very powerful library, rich in features, with support for a wide range of security mechanisms, from JAAS, CAS, to OAuth2 and many others, and has become a <em>defacto</em> standard security library for Spring applications. There are tons of available tutorials and examples of how to configure spring security for <strong>web applications</strong>. However, there are only a few workable tutorials on how to configure it for Java standalone applications (non-web applications).</p><p><strong>What will we be building in this post?</strong></p><p>If you run <em>clidemo</em> application and type <strong>help</strong> you should see the list of available commands, as displayed below:</p><pre>CLI-DEMO:&gt;help<br>AVAILABLE COMMANDS</pre><pre>Built-In Commands<br>        clear: Clear the shell screen.<br>        exit, quit: Exit the shell.<br>        help: Display help about available commands.<br>        history: Display or save the history of previously run commands<br>        script: Read and execute commands from a file.<br>        stacktrace: Display the full stacktrace of the last error.</pre><pre>Echo Command<br>        echo: Displays greeting message to the user whose name is supplied<br>        progress-bar: Displays progress bar<br>        progress-counter: Displays progress counter (with spinner)<br>        progress-spinner: Displays progress spinner</pre><pre>Table Examples Command<br>        sample-tables: Display sample tables<br>        table-formatter-demo: Table formatter demo</pre><pre>User Command<br>        create-user: Create new user with supplied username<br>        update-all-users: Update and synchronize all users in local database with external source<br>        user-details: Display details of user with supplied username<br>        user-list: Display list of users</pre><p>At the moment anyone who starts <em>clidemo</em> application can access every one of these commands. What we would like to achieve is that only those users (<em>CliUser</em>) who have signed in with their credentials (username/password) can access <strong>user-details</strong> and <strong>user-list</strong> commands, and only those signed-in users who have their property <strong>superuser</strong> set to <em>TRUE</em> can access <strong>create-user, user-details, </strong>and <strong>update-all-users</strong> commands.</p><p>As the first step of this post, add the spring security dependency to an existing <strong>build.gradle</strong> file:</p><pre>dependencies {<br>   implementation <strong>&#39;com.fasterxml.jackson.core:jackson-databind&#39;<br>   </strong>implementation <strong>&#39;org.springframework.shell:spring-shell-starter:2.0.1.RELEASE&#39;<br>   </strong>implementation <strong>&#39;org.springframework.security:spring-security-config&#39;</strong></pre><pre><strong>   </strong>testImplementation <strong>&#39;org.springframework.boot:spring-boot-starter-test&#39;<br></strong>}</pre><h3><strong>Restrict User Commands Access</strong></h3><p>Spring Shell has a built-in mechanism for controlling which commands are available to the user, due to the current internal state of the application, and which are not. This feature is called <em>Dynamic Command Availability</em>. Basically, it works as follows: with each command method one control method can be associated, that will be responsible to decide whether this method is available or not. For details please consult the official Spring Shell documentation on the following <a href="https://docs.spring.io/spring-shell/docs/current/reference/htmlsingle/#dynamic-command-availability">link</a>.</p><figure><a href="http://bit.ly/MediumAGENCY04"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tquvcAixKbvB7IvqqXTl8Q.png" /></a></figure><p>We are going to use this Spring Shell feature to protect our user commands, that is to make them available only to the signed in users. For start, let us create a new abstract class <strong>SecuredCommand, </strong>with code as shown in the snippet below:</p><pre><strong>package </strong>com.ag04.clidemo.command;<br><br><strong>import </strong>org.springframework.shell.Availability;<br><strong>import </strong>org.springframework.shell.standard.ShellMethodAvailability;<br><br><strong>public abstract class </strong>SecuredCommand {<br><br>    <strong>public </strong>Availability isUserSignedIn() {<br>           <strong>return </strong>Availability.<em>unavailable</em>(<strong>&quot;you are not signedIn. Please sign in to be able to use this command!&quot;</strong>);<br>    }<br><br>}</pre><p>The current implementation of <em>isUserSignedIn()</em> method will always simply return result indicating to the Spring Shell that command is not available, we will fix this later. Now declare <strong>UserComman</strong>d class to extend <strong>SecuredCommand</strong> class, and annotate all command methods in it with the following annotation:</p><pre>@ShellMethodAvailability(<strong>&quot;isUserSignedIn&quot;</strong>)</pre><p>Modified <strong>UserCommand</strong> class should, in the end, reassemble the following code snippet:</p><pre>@ShellComponent<br><strong>public class </strong>UserCommand <strong>extends </strong>SecuredCommand {</pre><pre>    // properties omitted</pre><pre>    @ShellMethod(<strong>&quot;Display list of users&quot;</strong>)<br>    @ShellMethodAvailability(<strong>&quot;isUserSignedIn&quot;</strong>)<br>    <strong>public void </strong>userList() {<br>        // method body omitted ...<br>    }</pre><pre>    @ShellMethod(<strong>&quot;Create new user with supplied username&quot;</strong>)<br>    @ShellMethodAvailability(<strong>&quot;isUserSignedIn&quot;</strong>)<br>    <strong>public void </strong>createUser(@ShellOption({<strong>&quot;-U&quot;</strong>, <strong>&quot;--username&quot;</strong>}) String username) {<br>        //  method body omitted ...<br>    }</pre><pre>    ...</pre><pre>}</pre><p>Rebuilding and running <em>clidemo</em> <strong>help</strong> command now produces the following output:</p><pre>CLI-DEMO:&gt;help<br>AVAILABLE COMMANDS</pre><pre>Built-In Commands<br>        clear: Clear the shell screen.<br>        exit, quit: Exit the shell.<br>        help: Display help about available commands.<br>        history: Display or save the history of previously run commands<br>        script: Read and execute commands from a file.<br>        stacktrace: Display the full stacktrace of the last error.</pre><pre>Echo Command<br>        echo: Displays greeting message to the user whose name is supplied<br>        progress-bar: Displays progress bar<br>        progress-counter: Displays progress counter (with spinner)<br>        progress-spinner: Displays progress spinner</pre><pre>Table Examples Command<br>        sample-tables: Display sample tables<br>        table-formatter-demo: Table formatter demo</pre><pre>User Command<br>      * create-user: Create new user with supplied username<br>      * my-details: Display details of signedIn user<br>      * update-all-users: Update and synchronize all users in local database with external source<br>      * user-details: Display details of user with supplied username<br>      * user-list: Display list of users</pre><pre>Commands marked with (*) are currently unavailable.<br>Type `help &lt;command&gt;` to learn more.</pre><p>As you can see, all user commands are marked with asterix (*) signaling that they are not available at the moment. For example, an attempt to run <strong>user-list</strong> command would result in the following response:</p><pre>CLI-DEMO:&gt;user-list<br>Command ‘user-list’ exists but is not currently available because you are not signedIn. Please sign in to be able to use this command!<br>Details of the error have been omitted. You can use the stacktrace command to print the full stacktrace.</pre><p>Now that user commands are “protected” in this manner, we can proceed with implementing a real spring security protection.</p><h3>Configuring Spring Security</h3><p>First, we will change the existing <strong>SecuredCommand</strong> class and implement real <em>isUserSignedIn</em>() method, as shown in the code below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a79353a19bc4595c63fdbdc76a2ae6ca/href">https://medium.com/media/a79353a19bc4595c63fdbdc76a2ae6ca/href</a></iframe><p>If <strong>SecurityContextHolder</strong> contains valid <strong>Authentication</strong> object this method returns positive result (access to the command is granted), otherwise negative (access to the command is denied). For more on <strong>SecurityContextHolder</strong> see the following <a href="https://www.baeldung.com/get-user-in-spring-security">link</a>. Now, only signed in users will have access to the user commands.</p><p>The next step is to configure spring security for <em>clidemo</em> application. At the core of our configuration is custom <strong>ClidemoUserDetailsService</strong> implementation of Spring security <em>UserDetailsService</em> interface. Create this class with the code from the following code snippet:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ec95cdb143f31dcb7b63084a05c5aad2/href">https://medium.com/media/ec95cdb143f31dcb7b63084a05c5aad2/href</a></iframe><p>For more on <em>UserDetailsService</em> interface see this <a href="https://www.baeldung.com/spring-security-authentication-with-a-database"><strong>article</strong></a>. With this class in place, we can proceed and create a separate spring configuration file that will hold all spring security related configurations. To do so, create <strong>SpringSecurityConfig</strong> class as shown below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f80d19165743d5dede9d28f96e16a3ef/href">https://medium.com/media/f80d19165743d5dede9d28f96e16a3ef/href</a></iframe><p>Now it is time to enable our users to actually sign in. For that purpose, we will create a new command that will prompt users to provide their <em>username</em> and <em>password</em>. Create new <strong>SigninCommand</strong> class as shown in the code below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3b58205f9af81c2d08284f26c758f56f/href">https://medium.com/media/3b58205f9af81c2d08284f26c758f56f/href</a></iframe><p>Rebuild/rerun <em>clidemo</em> and try to <strong>signin</strong> with the following credentials: <em>lmodric </em>/ <em>midfielder10</em>, and you should be greeted with welcome message as shown in the picture below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/1*fM2HyBx7CZnSYMbvvmxUug.png" /><figcaption>User successfully signed in to clidemo application.</figcaption></figure><p>Also, running a <strong>help</strong> command now would display that all user commands are available to currently signed in user (<em>lmodric</em>).</p><p>NOTE: other available user data can be found in <strong>src/main/resources/cli-user.json</strong> file.</p><h3>Restrict user access based on the granted authorities</h3><p>What remains to be implemented is to enable only users whose property <strong>superuser</strong> is set to TRUE to have access to <strong>create-user, user-details, </strong>and <strong>update-all-users</strong> commands. As can be seen from the implementation of <strong>CliudemoUserDetailsService</strong> all users are granted ROLE_USER and only those with superuser property are also granted ROLE_ADMIN. What remains to be done is:</p><ol><li>Add a new method to <strong>SecuredCommand</strong> that will check if user has ROLE_ADMIN among his granted authorities.</li><li>Associate this new method with all relevant user command methods.</li></ol><p>To do so, first, remove all <strong>@ShellMethodAvailability</strong> annotations from the <strong>UserCommand</strong> class. Then, modify <strong>SecuredCommand</strong> class as shown in the code snippet below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a439f69e668e887cd7e924bdc8863139/href">https://medium.com/media/a439f69e668e887cd7e924bdc8863139/href</a></iframe><p>Spring Shell provides several methods of associating control methods with command methods. In the previous implementation, we have annotated command methods with the <strong>@ShellMethodAvailability</strong> annotation that contained the name of the <strong>control method</strong> (ie. <em>isUserSignedIn</em>) that should be invoked to determine whether the particular command is available or not.</p><pre>@ShellMethodAvailability(<strong>&quot;isUserSignedIn&quot;</strong>)</pre><p>In the final implementation, this relationship is reversed! We have instead opted to annotate control methods with the <strong>@ShellMethodAvailability</strong> annotation and provided the list of <strong>command names(!), NOT method names, </strong>to which particular method should control access. Thus the method <em>isUserAdmin</em>() is configured to check if user is allowed to access <strong>create-user, user-details, </strong>and <strong>update-all-users</strong> commands.</p><pre>@ShellMethodAvailability({<strong>&quot;create-user&quot;</strong>, <strong>&quot;update-all-users&quot;</strong>, <strong>&quot;user-details&quot;</strong>})<br><strong>public </strong>Availability isUserAdmin() {<br>   ...<br>}</pre><p>In larger applications, this approach is much more practical, since all command availability configurations are found in a single place, and it is rather easy to determine which method controls the access to which command.</p><p>Now if you want to play with this new configuration rebuild and rerun <em>clidemo</em>, sign in with the credentials: <strong>nacho/defender6</strong>. After attempting to access <strong>update-all-users</strong> command you should see the following output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z8L-6d3gUZprfsrPauRTvQ.png" /><figcaption>User is denied access to command due to lack of sufficient security privileges.</figcaption></figure><p><strong>This completes the fifth and final part of this blog series. </strong>Of course, many more topics remain to be tackled but armed with the knowledge of this and previous posts I have no doubt that you will be able to overcome any challenges encountered while using Spring Shell library. <strong>I do hope that you have found this series of posts satisfying and that its content will prove helpful in your future (CLI) projects.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/819/1*iSy_K6bOh4QxeQ746BGpJA.png" /></figure><h3>Rest of the series</h3><p>Part 1: <a href="https://medium.com/agency04/developing-cli-application-with-spring-shell-part-1-807cd3a32461"><em>Conveying contextual messages to the users in the CLI application</em></a></p><p>Part 2: <a href="https://medium.com/agency04/developing-cli-application-with-spring-shell-part-2-4be6ce252678"><em>Capturing user’s input in the CLI application</em></a></p><p>Part 3: <a href="https://medium.com/agency04/developing-cli-application-with-spring-shell-part-3-b4c247fdf558"><em>Displaying the progress of CLI command execution with the use of counters, spinners and progress bars</em></a></p><p>Part 4: <a href="https://medium.com/agency04/developing-cli-application-with-spring-shell-part-4-8bd2aafa7146"><em>Displaying the data with the use of tables in a Spring Shell based CLI application</em></a></p><p>Part 5: <em>Securing CLI application with Spring Security</em></p><h3>Sample Code:</h3><p>Entire source code for this tutorial is available at GitHub repository:</p><p><a href="https://github.com/dmadunic/clidemo">https://github.com/dmadunic/clidemo</a></p><h3>Additional resources:</h3><p>Spring Shell project site:</p><p><a href="https://projects.spring.io/spring-shell/">https://projects.spring.io/spring-shell/</a></p><p>Spring Shell official documentation:</p><p><a href="https://docs.spring.io/spring-shell/docs/current-SNAPSHOT/reference/htmlsingle/">https://docs.spring.io/spring-shell/docs/current-SNAPSHOT/reference/htmlsingle/</a></p><p><a href="https://docs.spring.io/spring-shell/docs/current/api/">https://docs.spring.io/spring-shell/docs/current/api/</a></p><p>Spring Security official documentation:</p><p><a href="https://spring.io/projects/spring-security">https://spring.io/projects/spring-security</a></p><p><strong>Thank you for reading! I do hope you enjoyed it and please share if you did.</strong></p><figure><a href="http://bit.ly/MediumAGENCY04"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tquvcAixKbvB7IvqqXTl8Q.png" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c13403cb79b4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/agency04/developing-cli-application-with-spring-shell-part-5-c13403cb79b4">Developing CLI application with Spring Shell (part 5)</a> was originally published in <a href="https://medium.com/agency04">Agency04</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Developing CLI application with Spring Shell (part 4)]]></title>
            <link>https://medium.com/agency04/developing-cli-application-with-spring-shell-part-4-8bd2aafa7146?source=rss-24eefdb9af7e------2</link>
            <guid isPermaLink="false">https://medium.com/p/8bd2aafa7146</guid>
            <category><![CDATA[cli]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[spring-shell]]></category>
            <dc:creator><![CDATA[Domagoj Madunić]]></dc:creator>
            <pubDate>Tue, 21 May 2019 19:36:06 GMT</pubDate>
            <atom:updated>2020-02-24T11:07:49.081Z</atom:updated>
            <content:encoded><![CDATA[<h3>Part 4: Developing CLI application with Spring Shell</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*netVSRFuB0Jg4OoPhUaTIA.png" /></figure><p>In the previous posts we have tackled the topics of base customization of Spring Shell CLI applications, conveying contextual information to the user by the use of colored output and capturing user input (in the form of the free text, one value from the list of options etc).</p><blockquote><strong>In this post we will turn our attention to the task of displaying data as tables using built-in Spring Shell functionality.</strong></blockquote><h3>Basic concepts</h3><p>It is best to begin this post with a simple example. Open your favorite IDE and create a new <strong>sample-tables</strong> command with the code shown bellow:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/40fb5767aa54e43d5bbf18baeb1c57bd/href">https://medium.com/media/40fb5767aa54e43d5bbf18baeb1c57bd/href</a></iframe><p>After invoking this new <strong>sample-tables</strong> command you should be presented with the following output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Sss0hxwio3UvkQW3c05CkA.png" /><figcaption>Demo of some of the available table border options.</figcaption></figure><p>As can be seen, this command displays the same set of data as tables, yet each with a different border style, illustrating the basic Spring Shell capabilities of displaying tabular data in the terminal.</p><p>At the core of this <strong>sample-tables</strong> command and Spring Shell support for display of tabular data is the <strong>TableBuilder</strong> class. This <strong>Spring Shell</strong> class, based on the supplied <strong><em>TableModel</em></strong> (we will cover it a little bit later), creates a <strong>Table</strong> object, that is a representation of our data (ie model). At the end what remains to be done is simply to print the Table object to the terminal.</p><p>The following lines of code do exactly that:</p><pre>TableBuilder tableBuilder = new TableBuilder(someModel);<br>Table table = tableBuilder.build().render(width);<br>shellHelper.print(table);</pre><p>In addition, the <strong>TableBuilder</strong> class has many other options. It allows us to: set border style (on all cells, only on the outline or header or just on some cells), set a wrapping strategy for an entire table or just a cell, set a cell alignment, configure a specific formatter class for a particular cell/or class, and finally to specify exact cell widths. More on these options will be said later, before that we will have to turn our attention to another Spring Shell core element- the <strong><em>TableModel</em></strong> interface.</p><p>The<strong><em> TableModel</em></strong> encapsulates our raw data and provides the Spring Shell <strong>Table</strong> class with a convenient interface for accessing it. The Spring Shell provides two <strong><em>TableModel</em></strong> implementations: <strong>ArrayTableModel</strong> and <strong>BeanListTableModel</strong> (this one will be discussed later).</p><p>The<strong> ArrayTableModel</strong> class is the most general implementation of the <strong><em>TableModel</em></strong> interface. Its constructor simply accept a two-dimensional array of Objects making it suitable for a wide range of cases:</p><pre><a href="https://docs.spring.io/spring-shell/docs/current/api/org/springframework/shell/table/ArrayTableModel.html#ArrayTableModel-java.lang.Object:A:A-"><strong>ArrayTableModel</strong></a>(<a href="https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html?is-external=true"><strong>Object</strong></a>[][] data)</pre><p>As can be seen from the code example above, constructing and displaying data in tabular form is very simple and boils down to these steps:</p><ol><li>Construct the TableModel around your actual data</li><li>Construct the TableBuilder with the previously constructed model</li><li>Add a border, formatter(s), set a wrapper and/or cell size …</li><li>Render a Table from TableBuilder</li><li>Print the Table to the terminal</li></ol><p>In the <strong>table-samples</strong> command above we have adjusted the table border for each of the displayed tables, and in the last example we have shown how to set a different border for the header row:</p><pre>TableModel model = <strong>new </strong>ArrayTableModel(sampleData);<br>TableBuilder tableBuilder = <strong>new </strong>TableBuilder(model);</pre><pre>....<br>tableBuilder.addInnerBorder(BorderStyle.<strong><em>fancy_light</em></strong>);<br>tableBuilder.addHeaderBorder(BorderStyle.<strong><em>fancy_double</em></strong>);<br><strong>shellHelper</strong>.print(tableBuilder.build().render(80));</pre><p>Fore more information on all available options please consult the official Javadoc for<em> </em>th<em>e BorderStyle</em> enumeration and the<strong>TableBuilder</strong> class.</p><figure><a href="http://bit.ly/MediumAGENCY04"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tquvcAixKbvB7IvqqXTl8Q.png" /></a></figure><h4>Data Formatters</h4><p>So far we have displayed only Strings, and, as expected, all worked fine. However, in real life applications this is hardly going to be the case. We will most likely encounter the need to display other data types, as for example <strong>java.util.Date</strong>.</p><p>To display an element from the model within a cell, the <strong>Table</strong> class invokes configured <strong>Formatter</strong>, and the Spring shell provides a simple pre-configured <strong>DefaultFormatter</strong> class which simply invokes <em>toString()</em> method on the particular element being displayed. In the case of more complex objects, as for example java.util.Date, this is most likely going to produce unacceptable results.</p><p>In the next example we will create the model that will consist of both Strings and LocalDates and accordingly configure the <strong>TableBuilder</strong> class to use our own <strong>LocalDateFormatter</strong> class (see bellow) to display the <strong>LocalDate</strong> elements of the model.</p><p>In the <strong>TableExampleCommand</strong> class create a new method as shown bellow:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aae4e2c65ea6962c351aafd9a4dd71fe/href">https://medium.com/media/aae4e2c65ea6962c351aafd9a4dd71fe/href</a></iframe><p>The sample code for the custom LocalDateFormatter can be found in the following code snippet:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/52b6bb444d2996783fd01148a9f5af40/href">https://medium.com/media/52b6bb444d2996783fd01148a9f5af40/href</a></iframe><p>After rebuilding the <em>clidemo</em> application and running of the new <strong>table-formatter-demo</strong> command you should see the following output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZVqFCAp1NxPfk0t8TVSxig.png" /></figure><p>As can be seen, all dates are formatted with “dd.MM.YYY” pattern, just as we wanted. Now that we have addressed the basics of using the Spring Shell support for the display of tabular data, it is time to turn to more advanced topics. That is, how to display a list of the (same) Java Beans or a single Java Bean as tabular data.</p><p>However, before proceeding any further we need to improve our <strong>MockUserService </strong>class to more reassemble a real life service and returns richer set of <em>CliUser</em> data.</p><h3>Improved MockUserService</h3><p>To do so, we will first expand the existing <em>UserService</em> interface to include the following methods:</p><pre><strong>public interface </strong>UserService {<br>    CliUser findById(Long id);<br>    CliUser findByUsername(String username);<br>    List&lt;CliUser&gt; findAll();<br><br>    <strong>boolean </strong>exists(String username);<br>    CliUser create(CliUser user);<br>    CliUser update(CliUser user);<br>    <strong>long </strong>updateAll();<br>}</pre><p>now, change the implementation of the MockUserService to match the following code snippet:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/03c900d4692f3e73bea0b1d894c29aa9/href">https://medium.com/media/03c900d4692f3e73bea0b1d894c29aa9/href</a></iframe><p>This implementation loads data from JSON file, store it locally and then performs all the operations on this local data. The location of JSON file should be in the <strong>src/main/resources</strong> folder and the example of JSON file can be found here:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0253f1dd0dbb4331d153c4c42bd9add8/href">https://medium.com/media/0253f1dd0dbb4331d153c4c42bd9add8/href</a></iframe><p>For all this to work some additional configurations are needed. First we need to configure Jackson’s <strong>ObjectMapper</strong> bean. Now, create a new <strong>JacksonConfig</strong> configuration class, as shown in the next code snippet.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a3169491f1fb800c343216fea42384ba/href">https://medium.com/media/a3169491f1fb800c343216fea42384ba/href</a></iframe><p>At the moment this class contains just a simple configuration of a single bean, but in a case we would later need to further customize default Jackson’s serialization and deserialization behavior, it is convenient to already have it in place.</p><p>Finally, we need to change the existing <strong>UserServiceConfig</strong> configuration class to match the changes in the <strong>MockUserService</strong>:</p><pre>@Configuration<br><strong>public class </strong>UserServiceConfig {<br><br>    @Bean<br>    <strong>public </strong>UserService userService(ProgressUpdateObserver observer, ObjectMapper objectMapper) <strong>throws </strong>IOException {<br>        MockUserService userService = <strong>new </strong>MockUserService();<br>        userService.setObserver(observer);<br>        userService.setObjectMapper(objectMapper);<br>        userService.init(<strong>&quot;cli-users.json&quot;</strong>);<br>        <strong>return </strong>userService;<br>    }<br>}</pre><p>Now we are ready to further expand the existing <strong>UserCommand</strong> class by introducing new user related commands.</p><h3>Display List of Java Beans/Entities</h3><p>As mentioned before in addition to the <strong>ArrayTableModel,</strong> Spring Shell also provides the <strong>BeanListTableModel</strong>, a <em>TableModel</em> implementation suited for the display of the list of the same Java Beans/Entities. Using this <em>TableModel</em> implementation we will implement the <strong>user-list</strong> command that displays all available CliUsers. The <strong>BeanListTableModel </strong>class provides three constructors of which the most convenient for our purposes is the following one:</p><pre><a href="https://docs.spring.io/spring-shell/docs/current/api/org/springframework/shell/table/BeanListTableModel.html#BeanListTableModel-java.lang.Iterable-java.util.LinkedHashMap-"><strong>BeanListTableModel</strong></a>(<a href="https://docs.oracle.com/javase/8/docs/api/java/lang/Iterable.html?is-external=true"><strong>Iterable</strong></a>&lt;<a href="https://docs.spring.io/spring-shell/docs/current/api/org/springframework/shell/table/BeanListTableModel.html"><strong>T</strong></a>&gt; list, <a href="https://docs.oracle.com/javase/8/docs/api/java/util/LinkedHashMap.html?is-external=true"><strong>LinkedHashMap</strong></a>&lt;<a href="https://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true"><strong>String</strong></a>,<a href="https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html?is-external=true"><strong>Object</strong></a>&gt; header);</pre><p>As can be seen this constructor takes as its first parameter the iterable list of the beans/entities which were to be displayed. The second parameter (named header) is a <em>Map</em> in which keys represent the names of the bean properties we would like to display in the table and elements represent labels for those properties, which will accordingly be displayed in the header row of the table. One thing is worth noting here, omitting a property name from this list would result in exclusion of that property from the table. In this manner it is possible to, rather conveniently, filter the data that will be displayed in the table.</p><p>Now we can start working on the new <strong>user-list </strong>command. Add the following method to the <strong>UserCommand</strong> class:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d8acd2f1dc18f3c25a6c8dacec8c7e45/href">https://medium.com/media/d8acd2f1dc18f3c25a6c8dacec8c7e45/href</a></iframe><p>Rebuilding the <em>clidemo</em> application and running the <strong>user-list</strong> command, now should produce the following output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JHt_8TPLAgRYO3XxBAMHRg.png" /><figcaption>Output of the user-list command.</figcaption></figure><h3>Display single Bean/Entity as tabular data</h3><p>As the last exercise in this post we will address the issue of displaying a single Java Bean/Entity as tabular data. What we want to achieve is to have a table in which all rows consist of two columns, the first one containing the property label and the second one a property value, as shown in the image bellow:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y22MAmxVudKf_yCb_C0oYg.png" /><figcaption>Desired output of the <strong>user-details</strong> command.</figcaption></figure><p>Unfortunately the Spring Shell does not provide an out-of-box implementation of the <em>TableModel</em> that would suite our needs. However, the following can be achieved with the use of an existing <strong>ArrayTableModel</strong>. All we need to do is to create a two-dimensional array, in which the first column would contain a property label and a second property value.</p><p>In order not to have to repeat this procedure multiple times, we will create the <strong>BeanTableModelBuilder</strong> class that will also enable us to register property labels and a header row. The full listing of the <strong>BeanTableModelBuilder</strong> can be found in the snippet bellow:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a7c6c8bb3a698ff3c8bf72d95b933ef3/href">https://medium.com/media/a7c6c8bb3a698ff3c8bf72d95b933ef3/href</a></iframe><p>As can be seen, based on the supplied Java bean, headers and labels, this class will construct an appropriate <strong>ArrayTableModel</strong>. If no labels are provided default property names will be used.</p><p>We will use this class to implement the new <strong>user-details</strong> command that will display details of a single <em>CliUser</em> as a table. To do so, add the following two methods to the UserCommand class:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e3fe4d7bf3878ca5ffadcbd22d956ce6/href">https://medium.com/media/e3fe4d7bf3878ca5ffadcbd22d956ce6/href</a></iframe><p>As can be seen from the code snippet above, in this example we have also provided some additional table formatting. Namely, we have set the columns’ width to 20 and 30 character respectively.</p><p>Finally, add also the following property to the <strong>UserCommand</strong> class:</p><pre>@Autowired<br><strong>private </strong>ObjectMapper <strong>objectMapper</strong>;</pre><p>Now, running of the command:</p><pre>user-details lmodric</pre><p>should display the details of my son’s favorite football player, as can be seen in the screenshot bellow ;-)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z38DDF02HFO15B0X7Vp9Yw.png" /></figure><p>As an exercise, you could now refactor the existing <strong>create-user</strong> command so that it uses this new <strong>displayUser()</strong> method and by doing so remove some unnecessary/duplicate lines of code.</p><p><strong>This concludes the fourth part of this series. In the next part we will address the problem of configuring Spring Security for the Spring Shell CLI applications.</strong></p><h3>Rest of the series:</h3><p>Part 1: <a href="https://medium.com/agency04/developing-cli-application-with-spring-shell-part-1-807cd3a32461"><em>Conveying contextual messages to the users in the CLI application</em></a></p><p>Part 2: <a href="https://medium.com/agency04/developing-cli-application-with-spring-shell-part-2-4be6ce252678"><em>Capturing user’s input in the CLI application</em></a></p><p>Part 3: <a href="https://medium.com/agency04/developing-cli-application-with-spring-shell-part-3-b4c247fdf558">Displaying the progress of CLI command execution with the use of counters, spinners and progress bars</a></p><p>Part 4: <em>Displaying the data with the use of tables in a Spring Shell based CLI application</em></p><p><strong>Part 5: </strong><a href="https://medium.com/agency04/developing-cli-application-with-spring-shell-part-5-c13403cb79b4"><strong><em>Securing CLI application with Spring Security</em></strong></a></p><h3>Sample Code:</h3><p>The entire source code for this tutorial is available at GitHub repository:</p><p><a href="https://github.com/dmadunic/clidemo">dmadunic/clidemo</a></p><h3>Additional resources:</h3><p>The Spring Shell project site:</p><p><a href="https://projects.spring.io/spring-shell/">https://projects.spring.io/spring-shell/</a></p><p>The Spring Shell official documentation:</p><p><a href="https://docs.spring.io/spring-shell/docs/current-SNAPSHOT/reference/htmlsingle/">https://docs.spring.io/spring-shell/docs/current-SNAPSHOT/reference/htmlsingle/</a></p><p><a href="https://docs.spring.io/spring-shell/docs/current/api/">https://docs.spring.io/spring-shell/docs/current/api/</a></p><p><strong>Thank you for reading! I do hope you enjoyed it and please share if you did.</strong></p><figure><a href="http://bit.ly/MediumAGENCY04"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tquvcAixKbvB7IvqqXTl8Q.png" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8bd2aafa7146" width="1" height="1" alt=""><hr><p><a href="https://medium.com/agency04/developing-cli-application-with-spring-shell-part-4-8bd2aafa7146">Developing CLI application with Spring Shell (part 4)</a> was originally published in <a href="https://medium.com/agency04">Agency04</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Developing CLI application with Spring Shell (part 3)]]></title>
            <link>https://medium.com/agency04/developing-cli-application-with-spring-shell-part-3-b4c247fdf558?source=rss-24eefdb9af7e------2</link>
            <guid isPermaLink="false">https://medium.com/p/b4c247fdf558</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[cli]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[spring-shell]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Domagoj Madunić]]></dc:creator>
            <pubDate>Tue, 14 May 2019 09:15:32 GMT</pubDate>
            <atom:updated>2020-02-24T11:06:56.260Z</atom:updated>
            <content:encoded><![CDATA[<h3>Part 3: Developing CLI application with Spring Shell</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FWMY93I3LBXRDZaTNO8TRg.png" /></figure><p>Sooner or later every application had to perform an operation that could not be finished in an instant. In web applications we expect to be presented with a spinner (of one sort or another) during the execution of our requests, these prevents us from nervously pressing submit button again and again tell us that all is well and our request is being taken care of. On the other hand when we copy a large amount of files from one location to another we expect our OS GUI to provide us with some sort of progress bar displaying the progress of initiated operation. Similarly when we start a <em>gradle</em> build of our project we are presented with a progress bar and numeric information indicating percentage completion of our build.</p><blockquote><strong>In this post we will cover the topic of displaying a progress of command execution to a user with the use of counters, spinners and the progress bar similar to the one used by <em>gradle</em> build tool.</strong></blockquote><h3>Implementing a simple spinner</h3><p>Let us begin with implementing the simple spinner to be used by our <em>clidemo</em> application. As a first step, in the package <strong>com.ag04.clidemo.shell</strong> create a new <strong>ProgressCounter</strong> class:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4ee1cd8b918a33f75ca9753e437e4c0a/href">https://medium.com/media/4ee1cd8b918a33f75ca9753e437e4c0a/href</a></iframe><p>As can be seen, this class exposes two public methods:</p><pre>public void display():<br>public void reset();</pre><p>The first one displays the next state of the rotating spinner, while the second one resets the spinner to its initial state.</p><p>To use this new class, we also need to configure it by adding the following configuration at the end of the <strong>SpringShellConfig</strong> class:</p><pre>@Bean<br><strong>public </strong>ProgressCounter progressCounter(@Lazy Terminal terminal) {<br>    <strong>return new </strong>ProgressCounter(terminal);<br>}</pre><p>To see it in action, we need to add another demo method in the existing <strong>echo command</strong>, as shown in the snippet bellow:</p><pre>@ShellMethod(<strong>&quot;Displays progress spinner&quot;</strong>)<br><strong>public void </strong>progressSpinner() <strong>throws </strong>InterruptedException {<br>    <strong>for </strong>(<strong>int </strong>i = 1; i &lt;=100; i++) {<br>        <strong>progressCounter</strong>.display();<br>        Thread.<em>sleep</em>(100);<br>    }<br>    <strong>progressCounter</strong>.reset();<br>}</pre><p>Now, rebuild, run <em>clidemo</em> and execute this new <strong>progress-spinner</strong> command. If all goes well you should see 10 seconds long rotating sequence of these characters:</p><pre>| / -\</pre><p><strong>NOTE:</strong> At the beginning of the <strong>ProgressCounter</strong> class, you might have notice a strange property:</p><pre><strong>private static final </strong>String <strong><em>CUU </em></strong>= <strong>&quot;\u001B[A&quot;</strong>;</pre><p>this is control character sequences “<strong>ESC A</strong>” known also as “<strong>CUU” command sequence </strong>instructing a terminal to move cursor up by one row. For more on control character sequences please see the following <a href="https://docs.microsoft.com/en-us/windows/console/console-virtual-terminal-sequences">link</a>.</p><figure><a href="http://bit.ly/MediumAGENCY04"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tquvcAixKbvB7IvqqXTl8Q.png" /></a></figure><h3>Implementing a counter with spinner</h3><p>Now lets improve <strong>ProgressCounter</strong> class by adding another method with the following signature:</p><pre><strong>public void </strong>display(<strong>int </strong>count, String message);</pre><p>This method will display spinner, and both current progress count and information message.</p><p>To do so, change the <strong>ProgressCounter</strong> class with the additions as displayed in the code bellow:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aae50255bcc7b77d5cd6375c0dc7ee85/href">https://medium.com/media/aae50255bcc7b77d5cd6375c0dc7ee85/href</a></iframe><p><strong>ProgressCounter</strong> class property “pattern” defines how counter and message are displayed, and it can be passed either through constructor or by use of setter method.</p><p>To test this new functionality, add another method to <strong>EchoCommand</strong> class, as shown bellow:</p><pre>@ShellMethod(<strong>&quot;Displays progress counter (with spinner)&quot;</strong>)<br><strong>public void </strong>progressCounter() <strong>throws </strong>InterruptedException {<br>    <strong>for </strong>(<strong>int </strong>i = 1; i &lt;=100; i++) {<br>        <strong>progressCounter</strong>.display(i, <strong>&quot;Processing&quot;</strong>);<br>        Thread.<em>sleep</em>(100);<br>    }<br>    <strong>progressCounter</strong>.reset();<br>}</pre><p>The final output after running this new <strong>progress-counter</strong> command should be similar to the bellow:</p><pre>CLI-DEMO:&gt;progress-counter <br>\ Processing: 100</pre><p>This <strong>ProgressCounter</strong> implementation is best suited to keep the user informed of the progress in situations when we do not know the exact number of records/lines/entities that we need to process, that is when we are only aware of the current state of execution with no hindsight concerning the scope of the remaining work.</p><p>In the situations when we are aware of the scope of work ahead of us, more suited would be the use of the progress bar to convey the information on the current state of progress to the user. Therefore, as the last exercise in this post, we will create simple progress bar, similar to the one used by the popular <em>gradle</em> tool during build process:</p><pre>&lt;================----&gt; 80%</pre><h3>Implementing a progress bar</h3><p>We will begin with creation of a new <strong>ProgressBar </strong>class, with two public methods, similar as the <strong>ProgressCounter</strong> class:</p><pre><strong>public void </strong>display(<strong>int </strong>percentage);<br><strong>public void </strong>reset();</pre><p>The first method will be responsible for displaying progress bar that matches current state of execution as declared by <em>percentage</em> parameter passed to it, while the second one will be responsible for cleaning up and resetting the bar to its initial state.</p><p>In the package <strong>com.ag04.clidemo.shell</strong> create <strong>ProgressBar</strong> class with the following code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5b87f0cebd18b67dae6da634e4dd9be5/href">https://medium.com/media/5b87f0cebd18b67dae6da634e4dd9be5/href</a></iframe><p>As usual, this should be followed by adding bean configuration block to the <strong>SpringShellConfig</strong> class:</p><pre>@Bean<br><strong>public </strong>ProgressBar progressBar(ShellHelper shellHelper) {<br>    <strong>return new </strong>ProgressBar(shellHelper);<br>}</pre><p>Now, add new test method to the end of the <strong>echo</strong> command, as shown bellow, so we can see the new <strong>ProgressBar</strong> in action:</p><pre>@ShellMethod(<strong>&quot;Displays progress bar&quot;</strong>)<br><strong>public void </strong>progressBar() <strong>throws </strong>InterruptedException {<br>    <strong>for </strong>(<strong>int </strong>i = 1; i &lt;=100; i++) {<br>        <strong>progressBar</strong>.display(i);<br>        Thread.<em>sleep</em>(100);<br>    }<br>    <strong>progressBar</strong>.reset();<br>}</pre><p>Rebuilding <em>clidemo</em> application and running this new <strong>progress-bar</strong> command should now result in the output similar to the one in the image bellow:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GWGqPpydVClKnNkscYfAKQ.png" /><figcaption>Progress bar in action.</figcaption></figure><p>If we would like our progress bar to reassemble the one used by <em>gradle</em> even more, we need to add the capability to pass optional “status message” parameter to the <em>display()</em> method. To do so, we need to expand the ProgressBar by adding a new <em>display()</em> method with the following signature:</p><pre>display(int percentage, String statusMessage); </pre><p>Accordingly, we will change the <strong>ProgressBar</strong> class to match the code snippet bellow:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ca80c2c04cbc1249e1ebc63836b50a8d/href">https://medium.com/media/ca80c2c04cbc1249e1ebc63836b50a8d/href</a></iframe><p>With these additions we are able to enrich our progress bar with display of additional status message, for example with info on duration of execution so far, or something similar.</p><h3>Putting it all together: displaying progress of UserService method</h3><p>Testing our progress bar and progress counter components with <strong>echo</strong> command is fine, but to make everything learned in this post so far less abstract we will close this post with the demonstration of progress bar component usage in a “real life” example.</p><h4>“Real life” example: massive update of (all) users</h4><p>Lets assume that <em>UserService</em> also defines the following method:</p><pre>long updateAll();</pre><p>This method is intended to synchronise and update all users in local database with some external source of data, and returns the number of updated users. Also, let us assume that there is a large number of users in our database and that this operation will take some time to finish.</p><p>For the purposes of this post we will modify <strong>MockUserService</strong> and add mock implementation of this method, one that will took time some to finish. Thus, add the method updateAll() to the <strong>UserService</strong> interface and add the following block of code to the <strong>MockUserService</strong>:</p><pre>@Override<br><strong>public long </strong>updateAll() {<br>    <strong>long </strong>numberOfUsers = 2000;<br>    <strong>for </strong>(<strong>long </strong>i = 1; i &lt;= numberOfUsers; i++) {<br>        <em>// do some operation ...<br>        </em><strong>try </strong>{<br>            Thread.<em>sleep</em>(10);<br>        } <strong>catch </strong>(InterruptedException e) {<br>            e.printStackTrace();<br>        }<br>    }<br>    <strong>return </strong>numberOfUsers;<br>}</pre><p>Now modify <strong>UserCommand</strong> by adding a method (see bellow) that invokes this new <strong>UserService</strong> method:</p><pre>@ShellMethod(<strong>&quot;Update and synchronize all users in local database with external source&quot;</strong>)<br><strong>public void </strong>updateAllUsers() {<br>    <strong>shellHelper</strong>.printInfo(<strong>&quot;Starting local user db update&quot;</strong>);<br>    <strong>long </strong>numOfUsers = <strong>userService</strong>.updateAll();<br>    String successMessage = <strong>shellHelper</strong>.getSuccessMessage(<strong>&quot;SUCCESS &gt;&gt;&quot;</strong>);<br>    successMessage = successMessage + String.<em>format</em>(<strong>&quot; Total of %d local db users updated!&quot;</strong>, numOfUsers);<br>    <strong>shellHelper</strong>.print(successMessage);<br>}</pre><p>Rebuilding and running of <strong><em>clidemo</em></strong> <strong>update-all-users</strong> command will now produce the following output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RtI1A_YrNX6G0OfW_GdkSQ.png" /><figcaption>User update without progress bar.</figcaption></figure><p>As you could see, by running this example, after the first message “<strong>Starting local user db update</strong>” is printed out, we are left to wait until user update operation has finished. What we would like to achieve is to present user with the progress bar displaying the progress of user update operation.</p><p>Moreover we would like to achieve this in a least intrusive way, thus we will implement it with the use of <em>Observer</em> pattern.</p><h4>Observer pattern in action</h4><p>Wikipedia defines <em>Observer</em> pattern as follows:</p><p><em>“The </em><strong><em>observer pattern</em></strong><em> is a </em><a href="https://en.wikipedia.org/wiki/Design_pattern_(computer_science)"><em>software design pattern</em></a><em> in which an </em><a href="https://en.wikipedia.org/wiki/Object_(computer_science)#Objects_in_object-oriented_programming"><em>object</em></a><em>, called the </em><strong><em>subject</em></strong><em>, maintains a list of its dependents, called </em><strong><em>observers</em></strong><em>, and notifies them automatically of any state changes, usually by calling one of their </em><a href="https://en.wikipedia.org/wiki/Method_(computer_science)"><em>methods</em></a><em>.”</em></p><p>In our case <em>Observable</em> object will be <strong>MockUserService</strong> class and we will also implement custom <em>Observer</em> class that will display operation progress at the terminal.</p><p>Detailed information concerning the Java support for the <em>Observer</em> pattern can be found on the following <a href="https://www.baeldung.com/java-observer-pattern">link</a>. Our solution, one that follows bellow, is based on the use of <strong>Observer/Observable</strong> classes as described in the previously linked post.</p><p>First we will create new <strong>ProgressUpdateObserver</strong> class, one that will be responsible for updating user’s terminal based on the the progress information.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/89f212efeaf4ad1ae2c3cf5385bdd420/href">https://medium.com/media/89f212efeaf4ad1ae2c3cf5385bdd420/href</a></iframe><p>In the same package we will now create <strong>ProgressUpdateEvent</strong> class that this Observer reacts on.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4a7f9cabb52c28258962797daaa4a7bd/href">https://medium.com/media/4a7f9cabb52c28258962797daaa4a7bd/href</a></iframe><p>What remains to be done is to modify <strong>MockUserService</strong> so that it fires up this event as the update operation progresses. Modify <strong>MockUserService</strong> class in accordance with the code bellow, add <em>Observer</em> property, modify <em>updateAll()</em> method and do not forget to remove @Service annotation, since we will configure this class later manually.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/092b82d90240582357f465c82c1eaa34/href">https://medium.com/media/092b82d90240582357f465c82c1eaa34/href</a></iframe><p>Finally, add <strong>UserServiceConfig</strong> class which contains method to create and configure <strong>MockUserService</strong> bean as shown in the code snippet bellow:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2b28448d5766789172ba029e4fe9506c/href">https://medium.com/media/2b28448d5766789172ba029e4fe9506c/href</a></iframe><p>Whit this we are all set! Running <em>clidemo</em> <strong>update-all-user </strong>command<strong> </strong>now, should produce the output as shown in the picture bellow:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Op8hoeU5uA6516AY39lCwQ.png" /><figcaption>update-all-users command final output</figcaption></figure><p><strong>This concludes the third part of this series. In </strong><a href="https://medium.com/@domagoj.madunic/developing-cli-application-with-spring-shell-part-4-8bd2aafa7146"><strong>the next part</strong></a><strong> we will focus on advanced built-in Spring Shell support for data display as tables within terminal.</strong></p><h3>Rest of the series:</h3><p>Part 1: <a href="https://medium.com/agency04/developing-cli-application-with-spring-shell-part-1-807cd3a32461"><em>Conveying contextual messages to the users in the CLI application</em></a></p><p>Part 2: <a href="https://medium.com/agency04/developing-cli-application-with-spring-shell-part-2-4be6ce252678"><em>Capturing user’s input in the CLI application</em></a></p><p>Part 3: <em>Displaying the progress of CLI command execution with the use of counters, spinners and progress bars</em></p><p><strong>Part 4: </strong><a href="https://medium.com/@domagoj.madunic/developing-cli-application-with-spring-shell-part-4-8bd2aafa7146"><strong><em>Displaying the data with the use of tables in a Spring Shell based CLI application</em></strong></a></p><p>Part 5: <a href="https://medium.com/agency04/developing-cli-application-with-spring-shell-part-5-c13403cb79b4"><em>Securing CLI application with Spring Security</em></a></p><h3>Sample Code:</h3><p>Entire source code for this tutorial is available at GitHub repository:</p><p><a href="https://github.com/dmadunic/clidemo">dmadunic/clidemo</a></p><h3>Additional resources:</h3><p>Spring Shell project site:</p><p><a href="https://projects.spring.io/spring-shell/">https://projects.spring.io/spring-shell/</a></p><p>Spring Shell official documentation:</p><p><a href="https://docs.spring.io/spring-shell/docs/current-SNAPSHOT/reference/htmlsingle/">https://docs.spring.io/spring-shell/docs/current-SNAPSHOT/reference/htmlsingle/</a></p><p><a href="https://docs.spring.io/spring-shell/docs/current/api/">https://docs.spring.io/spring-shell/docs/current/api/</a></p><p>JLine project site:</p><p>[<a href="https://jline.github.io/](https://jline.github.io/)">https://jline.github.io/](https://jline.github.io/)</a></p><p>Good overview of the Terminal control sequences:</p><p><a href="https://docs.microsoft.com/en-us/windows/console/console-virtual-terminal-sequences">https://docs.microsoft.com/en-us/windows/console/console-virtual-terminal-sequences</a></p><p><strong>Thank you for reading! I do hope you enjoyed it and please share if you did.</strong></p><figure><a href="http://bit.ly/MediumAGENCY04"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tquvcAixKbvB7IvqqXTl8Q.png" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b4c247fdf558" width="1" height="1" alt=""><hr><p><a href="https://medium.com/agency04/developing-cli-application-with-spring-shell-part-3-b4c247fdf558">Developing CLI application with Spring Shell (part 3)</a> was originally published in <a href="https://medium.com/agency04">Agency04</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Developing CLI application with Spring Shell (part 2)]]></title>
            <link>https://medium.com/agency04/developing-cli-application-with-spring-shell-part-2-4be6ce252678?source=rss-24eefdb9af7e------2</link>
            <guid isPermaLink="false">https://medium.com/p/4be6ce252678</guid>
            <category><![CDATA[cli]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[spring-shell]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Domagoj Madunić]]></dc:creator>
            <pubDate>Tue, 07 May 2019 13:49:29 GMT</pubDate>
            <atom:updated>2020-06-27T11:13:48.459Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7kkSiyG7HcnhGqFycsTvyA.png" /></figure><p>In the <a href="https://medium.com/agency04/developing-cli-application-with-spring-shell-part-1-807cd3a32461"><strong>previous post</strong></a> we have created the skeleton of the sample CLI application with some helper classes added to support display of contextual messages to the user (similar to the <strong>Bootstrap’s</strong> contextual messages).</p><blockquote><strong>In this blog post we go a step further and cover the topic of interacting with a user in a CLI application. What we will concentrate on will be capturing of the user’s input in the form of: free text, passwords, an option from the list of values, etc.</strong></blockquote><h3>What we will be building in this part?</h3><p>For the purposes of this tutorial we will build a command that captures data necessary to create a new user. This command will interact with user and ask him to provide the following data for the new user:</p><ul><li>Full name (free text)</li><li>password (hidden text)</li><li>gender (a choice from list of options)</li><li>superuser (input from list of available values — with default value)</li></ul><p><strong>NOTE:</strong> Spring Shell relies on <a href="https://jline.github.io/"><strong>JLine</strong></a> — a powerful Java library — and most of the examples provided in the rest of this post are mainly related to the use of <strong>JLine</strong> and are not Spring Shell specific.</p><h3>The model we will use</h3><p>Package <strong>com.ag04.clidemo.model</strong> contains <em>CliUser</em> class we will use to store user’s input and pass it on to user service for further processing.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e493979bffb5b2f9f143e173cfc740d8/href">https://medium.com/media/e493979bffb5b2f9f143e173cfc740d8/href</a></iframe><p>Enumeration Gender is pretty basic:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/84567126fe15d6442259e1e48b4c1959/href">https://medium.com/media/84567126fe15d6442259e1e48b4c1959/href</a></iframe><p>Simple <em>UserService</em> interface, together with its mock implementation, one we will invoke to process user provided data is available in the package: <strong>com.ag04.clidemo.service</strong>, and defines the following contract:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/413727d5eb8096a10a06f9cd5955209c/href">https://medium.com/media/413727d5eb8096a10a06f9cd5955209c/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0d2cf0a6891bbeed0e717fd168725524/href">https://medium.com/media/0d2cf0a6891bbeed0e717fd168725524/href</a></iframe><p>With this model at hand we can now proceed, and implement a command that will collect user input and then invoke <em>UserService.create()</em> method.</p><h3>Create new user</h3><p>Lets start with creating a new Spring Shell command named <strong>UserCommand</strong> with just one method designed to create a new user.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d235923847908f58e99a01cd1337cbc7/href">https://medium.com/media/d235923847908f58e99a01cd1337cbc7/href</a></iframe><p>After rebuilding and re-running application, invoking help command should provide output similar as bellow (listing also our new command among the list of available commands):</p><pre>CLI-DEMO:&gt;help<br>AVAILABLE COMMANDS</pre><pre>Built-In Commands<br>        clear: Clear the shell screen.<br>        exit, quit: Exit the shell.<br>        help: Display help about available commands.<br>        history: Display or save the history of previously run commands<br>        script: Read and execute commands from a file.<br>        stacktrace: Display the full stacktrace of the last error.</pre><pre>Echo Command<br>        echo: Displays greeting message to the user whose name is supplied</pre><pre>User Command<br>        create-user: Create new user with supplied username</pre><p>Available mock implementation of <em>UserService.exists()</em> method returns true for “admin” <em>username</em>. Now, invoke <strong>create-user</strong> command with <strong>admin</strong> as parameter and you should see the following output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KHM9vEUlg45BEHQA_kfY-Q.png" /></figure><p>With all these pieces in place we can now start collecting user input and implementing <strong>create-user</strong> command.</p><figure><a href="http://bit.ly/MediumAGENCY04"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tquvcAixKbvB7IvqqXTl8Q.png" /></a></figure><h3>Interacting with a user</h3><p>Similar to the <strong>ShellHelper</strong> class we created in the previous post, in this post we will create a new <strong>InputReader</strong> class that will contain various helper methods for interacting with a user. The first method we need is the one that prompts the user to enter data in free format.</p><p>Listing bellow, contains our first implementation of <strong>InputReader</strong> class, with three methods designed to capture user data in free entry format:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/632ef84b4b3baf07bb219be8f5a5c00f/href">https://medium.com/media/632ef84b4b3baf07bb219be8f5a5c00f/href</a></iframe><p>These three methods provide us with the capability to ask a user for an input with the display of customized prompt message at the beginning of the line. Additionally we have an option to supply the default return value in case a user just pressed enter, and to mask user’s entered input (in case we need to capture sensitive data, ie password).</p><p>In order to be able to use this class we also need to add the following configuration lines to an existing <strong>SpringShellConfig</strong> class:</p><pre><a href="http://twitter.com/Bean">@Bean</a><br>public InputReader inputReader(<a href="http://twitter.com/Lazy">@Lazy</a> LineReader lineReader) {<br> return new InputReader(lineReader);<br>}</pre><p>Now we can start implementing <strong>UserCommand</strong>.</p><h3>Prompt user for full name and password</h3><p>Now, lets modify <strong>UserCommand</strong> to resemble the code snippet bellow:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3fb1c65fc8e9404c28186897cd3d16e8/href">https://medium.com/media/3fb1c65fc8e9404c28186897cd3d16e8/href</a></iframe><p>Here, we have added two blocks of code that capture user’s data. One that loops until user’s <strong>full name,</strong> containing at least one <strong>non space character,</strong> was entered, and the other one that prompts user to enter password, which masks user input (replacing his entry with default mask: *) and returns “<strong>secret</strong>” as default password value if user just presses enter.</p><p>Finally, the last block of code we added, prints out user’s entered data and invokes <em>UserService.create()</em> method. In the real life application user’s password would not be printed, but we have done it here for the purposes of debugging.</p><p>Now, try it out, (press enter when prompted for password) and the output should be similar to this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zvffeYZXwCIGncMT0J4d4A.png" /><figcaption>Create user initial version</figcaption></figure><p>As can be seen, Gender property of <em>CliUser</em> is set to <em>null</em> and superuser property is set to <em>false</em>, which is fine since these are default values of <em>CliUser</em>. Now, lets improve <strong>InputReader</strong> and add support to allow user to chose one of the options from the list, and then expand <strong>UserCommand</strong> with the block of code that uses this functionality to capture user’s Gender data.</p><h3>Prompt user to select one value from the list of available options</h3><p>Now we are going to attempt something more ambitious, that is, to prompt a user to select one value from the list of values. Once implemented, we are going to use this capability to ask user to provide his gender in <strong>create-user</strong> command. As you could have noticed Gender <em>enumeration</em> defines three values. We will print each value, associate with each of them one character key, and ask user to enter one key as his choice.</p><p>What we will build, in the end will look as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rbPZv6jOeZ4lZrNluBbrOw.png" /></figure><p>First, add <strong>ShellHelper</strong> as class property and change constructor of the <strong>InputReader</strong> util class as follows:</p><pre>ShellHelper shellHelper;</pre><pre>public InputReader(LineReader lineReader, ShellHelper shellHelper) {<br>    this(lineReader, shellHelper, null);<br>}</pre><pre>public InputReader(LineReader lineReader, ShellHelper shellHelper, Character mask) {<br>    this.lineReader = lineReader;<br>    this.shellHelper = shellHelper;<br>    this.mask = mask != null ? mask : DEFAULT_MASK;<br>}</pre><p>Then, at the end of the <strong>InputReader</strong> class add the following methods:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e7bd7323fd04e86b91c43bc7d9672e7a/href">https://medium.com/media/e7bd7323fd04e86b91c43bc7d9672e7a/href</a></iframe><p><strong>Note</strong>: above implementation of <em>selectFromList()</em> method will also print default option value with different color style(<em>info</em>).</p><p>For this additions to work we also need to change the method that creates <strong>InputReader</strong> bean in <strong>SpringShellConfig</strong> class as follows:</p><pre><a href="http://twitter.com/Bean">@Bean</a><br>public InputReader inputReader(<a href="http://twitter.com/Lazy">@Lazy</a> LineReader lineReader, ShellHelper shellHelper) {<br>  return new InputReader(lineReader, shellHelper);<br>}</pre><p>Finally, modify the <strong>UserCommand</strong> by adding the following lines before print of user’s input:</p><pre>// 3. read user&#39;s Gender ----------------------------------------------<br>Map&lt;String, String&gt; options = new HashMap&lt;&gt;();<br>options.put(&quot;M&quot;, Gender.MALE.name());<br>options.put(&quot;F&quot;, Gender.FEMALE.name() );<br>options.put(&quot;D&quot;, Gender.DIVERSE.name());</pre><pre>String genderValue = inputReader.selectFromList(&quot;Gender&quot;, &quot;Please enter one of the [] values&quot;, options, true, null);<br>Gender gender = Gender.valueOf(options.get(genderValue.toUpperCase()));<br>user.setGender(gender);</pre><pre><em>// Print user&#39;s input ----------------------------------------------</em></pre><p>Gender property has no default value so we supplied <em>null</em> as fourth argument to the <em>selectFromList()</em> method.</p><p>Rebuild, run <strong>clidemo</strong> and invoke <strong>create-user</strong> command to test newly implemented features!</p><p>Method <em>selectFromList()</em> is convenient for cases when number of available options is greater than 2 or 3, and we would like to print each on single line. Yet, in cases when there are only two options for user to choose from (for example: <strong>Y/N</strong>) it would be more suited to have a method in <strong>InputReader</strong> that will present a user with a single prompt line, consisting of all available options.</p><p>To do so we will now modify <strong>InputReader</strong> class and add the two following methods:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6757743ca881679398c3fc08dd4b7092/href">https://medium.com/media/6757743ca881679398c3fc08dd4b7092/href</a></iframe><p>These methods provides previously described functionality, and similar to the previously created <em>selectFromList()</em> method, if default value is provided, option of that value will be printed with the <em>info</em> color style.</p><p>To see it in action, we will use this method to ask user, should newly created user be marked as superuser. In the <strong>UserCommand</strong> class after the block of code that asks user to provide Gender add the following lines of code:</p><pre>// 4. Prompt for superuser attribute ------------------------------<br>String superuserValue = inputReader.promptWithOptions(&quot;New user is superuser&quot;, &quot;N&quot;, Arrays.asList(&quot;Y&quot;, &quot;N&quot;));<br>if (&quot;Y&quot;.equals(superuserValue)) {<br>    user.setSuperuser(true);<br>} else {<br>    user.setSuperuser(false);<br>}<br>// Print user&#39;s input ----------------------------------------------<br>...</pre><p>As can be seen default value in this case is set to “N”, resulting in return of “N” by <em>InputReader.promptWithOptions()</em> method in case the user just pressed ENTER as its input.</p><p>Finally, running <strong>clidemo</strong> again should result in the following output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TZWxsw_llSxYBqOuhjB-aQ.png" /></figure><p>Create new user method of our <strong>UserCommand</strong> is now finished. We collect all the necessary data from a user, map it to the <strong>CliUser</strong> object and pass it to <em>UserService.create()</em> method in order to create a new user.</p><p>Additionally, we could also add one more action to this method, prompting a user to confirm that provided data is correct, using <em>InputReader.promptWithOptions()</em> as described above, after entered data is printed out and before invocation of <em>UserService.create()</em> method.</p><h3>Final fine tuning</h3><p>Yet, one small issue remains to be addressed. As can be seen in the pictures above, user input values are displayed with red color. This is the result of using SpringShell auto-configured <strong>LineReader</strong>, which is configured to display all user’s input in red color unless a input matches on of the shell commands.</p><p>To avoid this behavior we need to configure our own <strong>LineReader</strong> and pass it to <strong>InputReader’s</strong> constructor.</p><p>Modify <strong>SpringShellConfig</strong> class method <em>inputReader()</em> to match the code snippet bellow:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4050358cf0182b8e3233e32a74b81473/href">https://medium.com/media/4050358cf0182b8e3233e32a74b81473/href</a></iframe><p>Now all user’s input will be displayed with default color and bold style, as visible in the image bellow:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zG7vGVbQnKR_S2fGNfkHTQ.png" /><figcaption>Final output of the implemented UserCommand</figcaption></figure><p><strong>This concludes the second part of this series of posts. In the </strong><a href="https://medium.com/agency04/developing-cli-application-with-spring-shell-part-3-b4c247fdf558"><strong>next part</strong></a><strong> we will show you how to build progress bar component.</strong></p><h3>Rest of the series:</h3><p>Part 1: <a href="https://medium.com/agency04/developing-cli-application-with-spring-shell-part-1-807cd3a32461"><em>Conveying contextual messages to the users in the CLI application</em></a></p><p>Part 2: <em>Capturing user’s input in the CLI application</em></p><p><strong>Part 3: </strong><a href="https://medium.com/agency04/developing-cli-application-with-spring-shell-part-3-b4c247fdf558"><strong><em>Displaying the progress of CLI command execution with the use of counters, spinners and progress bars</em></strong></a></p><p>Part 4: <a href="https://medium.com/@domagoj.madunic/developing-cli-application-with-spring-shell-part-4-8bd2aafa7146"><em>Displaying the data with the use of tables in a Spring Shell based CLI application</em></a></p><p>Part 5: <a href="https://medium.com/agency04/developing-cli-application-with-spring-shell-part-5-c13403cb79b4"><em>Securing CLI application with Spring Security</em></a></p><h3>Sample Code:</h3><p>Entire source code for this tutorial is available at GitHub repository:</p><p><a href="https://github.com/dmadunic/clidemo">dmadunic/clidemo</a></p><h3>Additional resources:</h3><p>Spring Shell project site:</p><p><a href="https://projects.spring.io/spring-shell/">https://projects.spring.io/spring-shell/</a></p><p>Spring Shell official documentation:</p><p><a href="https://docs.spring.io/spring-shell/docs/current-SNAPSHOT/reference/htmlsingle/">https://docs.spring.io/spring-shell/docs/current-SNAPSHOT/reference/htmlsingle/</a></p><p><a href="https://docs.spring.io/spring-shell/docs/current/api/">https://docs.spring.io/spring-shell/docs/current/api/</a></p><p>Jline project site:</p><p><a href="https://jline.github.io/">https://jline.github.io/</a></p><p><strong>Keywords</strong>:</p><p>Java, Spring, Spring Shell, Spring boot, CLI, Terminal, JLine</p><p><strong>Thank you for reading! I do hope you enjoyed it and please share if you did.</strong></p><figure><a href="http://bit.ly/MediumAGENCY04"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tquvcAixKbvB7IvqqXTl8Q.png" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4be6ce252678" width="1" height="1" alt=""><hr><p><a href="https://medium.com/agency04/developing-cli-application-with-spring-shell-part-2-4be6ce252678">Developing CLI application with Spring Shell (part 2)</a> was originally published in <a href="https://medium.com/agency04">Agency04</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Developing CLI application with Spring Shell (part 1)]]></title>
            <link>https://medium.com/agency04/developing-cli-application-with-spring-shell-part-1-807cd3a32461?source=rss-24eefdb9af7e------2</link>
            <guid isPermaLink="false">https://medium.com/p/807cd3a32461</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-shell]]></category>
            <category><![CDATA[cli]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Domagoj Madunić]]></dc:creator>
            <pubDate>Tue, 30 Apr 2019 10:16:22 GMT</pubDate>
            <atom:updated>2020-02-24T11:03:29.462Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bZUh-PtvA1JFVN4IuHBhyw.png" /></figure><h4>The rest of the series:</h4><p>Part 2: <a href="https://medium.com/agency04/developing-cli-application-with-spring-shell-part-2-4be6ce252678"><em>Capturing user’s input in the CLI application</em></a></p><p>Part 3: <a href="https://medium.com/agency04/developing-cli-application-with-spring-shell-part-3-b4c247fdf558"><em>Displaying the progress of CLI command execution with the use of counters, spinners and progress bars</em></a></p><p>Part 4: <a href="https://medium.com/@domagoj.madunic/developing-cli-application-with-spring-shell-part-4-8bd2aafa7146"><em>Displaying the data with the use of tables in a Spring Shell based CLI application</em></a></p><p>Part 5: <a href="https://medium.com/agency04/developing-cli-application-with-spring-shell-part-5-c13403cb79b4"><em>Securing CLI application with Spring Security</em></a></p><p>The first application I ever wrote was my personal library management software. I did it in the late 90’s, and it was written as terminal application in <strong>C</strong> (back then, for me the most glamorous programming language — Unix was written in it!). Since then, I wrote literary tens of thousands of lines of code (in dozen of languages) and today I am mainly involved in development of enterprise grade IT solutions using languages and tools from the Java eccosystem (having Spring framework as the foundation) with some kind of single-page-application (SPA) serving as the front-end.</p><p>That said, my heart still skips a beat when seeing a nice terminal application.</p><p>In this series of the blog posts I will walk you through the steps of creating a simple command line interpreter (<em>CLI</em>) application using one of the less known Spring projects: <a href="https://projects.spring.io/spring-shell/"><strong>Spring Shell</strong></a>.</p><h3>About Spring Shell</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/819/1*iSy_K6bOh4QxeQ746BGpJA.png" /></figure><p>As the authors of the Spring Shell library say on their web site:</p><blockquote><em>”</em>Not all applications need a fancy web user interface! Sometimes, interacting with an application using an interactive terminal is the most appropriate way to get things done.<em>”</em></blockquote><p>Spring Shell aims to fill in this gap and provide Spring users with library designed to support development of CLI applications using all familiar concepts and design patterns (<em>DI</em> and <em>IoC</em> for example) from Spring framework.</p><p>At the time of writing of this article, Spring Shell is in its second incarnation (version 2.0.1 is the latest release). This version represents a complete rewrite of the previous 1.2.x version, adjusted to the changes introduced in the Spring eccosystem with the release of Spring Boot 2.x.</p><figure><a href="http://bit.ly/MediumAGENCY04"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tquvcAixKbvB7IvqqXTl8Q.png" /></a></figure><h3>About this blog posts series</h3><p>This series of blog posts is an extension to the <a href="https://docs.spring.io/spring-shell/docs/current-SNAPSHOT/reference/htmlsingle/#_let_s_write_a_simple_boot_app"><strong>getting started</strong></a><strong> </strong>guide, in which we go a step further and cover some of the base building blocks of CLI applications not addressed in the reference documentation. This first blog post will lead you through the process of setting up and configuring a simple demo application and will also cover the following topics:</p><ul><li>base customization of the <em>CLI</em> application</li><li>conveying contextual information to the user through the use of colored messages</li></ul><p>In the next posts we will tackle some of the more complex topics such as:</p><ul><li>Capturing user input (free text, passwords, input from the list of select values, etc)</li><li>Displaying operation progress information (spinners, counter, progress bars)</li><li>Displaying data as tables using Spring Shell built-in util classes</li><li>Integrating Spring Shell and Spring Security</li></ul><h3>Generate and configure spring-boot/gradle project</h3><p>Simplest way to start new Spring based project is to use Spring <strong>Initializr</strong>. To do so open a browser of your choice and navigate to: <a href="https://start.spring.io/">https://start.spring.io/</a></p><p>Fill in the form by entering the defaults, as displayed in the picture bellow:</p><ul><li>Select: Gradle Project and Java as the project language</li><li>Choose: Spring Boot 2.1.3 (or the latest version at the moment)</li><li>Under dependencies enter “spring shell” and press enter</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W05VARNX02kQgWWX6ER50Q.png" /></figure><p>Finally, press “Generate Project”, download the zip file, unpack it and import the project into your favorite IDE (<em>IntelliJ Idea, VSS Code, Eclipse</em>, …).</p><p>Now we are ready to make some changes in the build file. First of all, lets upgrade Spring Shell library to its latest RELEASE (2.0.1).</p><p>In the generated <strong>build.gradle</strong> file find the following block of code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9a799b6491d5a1bc030b693e12267a52/href">https://medium.com/media/9a799b6491d5a1bc030b693e12267a52/href</a></iframe><p>and change it to look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4e3deb23e694df290b4f5296c70e2519/href">https://medium.com/media/4e3deb23e694df290b4f5296c70e2519/href</a></iframe><p>Finally, delete the integration tests found in `<strong>src/test/java/</strong>` folder generated by Spring Initializr (see <a href="https://docs.spring.io/spring-shell/docs/current-SNAPSHOT/reference/htmlsingle/#_adding_a_dependency_on_spring_shell"><strong>this link</strong></a> for a detailed explanation), and execute the following command from your terminal inside the root <strong>clidemo/</strong> folder in order to compile and build the application:</p><pre>./gradlew clean build</pre><p>If all went well, start the application by running:</p><pre>java -jar build/libs/clidemo-0.0.1-SNAPSHOT.jar</pre><p>And soon, you should see the familiar output of a SpringBoot application starting:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7GZzHTW5imTi5LkjXWzg_w.png" /><figcaption>CLI application started</figcaption></figure><p>The last line says that our application is now ready to accept our input. At this point just type in ”<strong>help</strong>” to see the list of predefined commands available by default in a Spring Shell application, and you should see an output similar to this one:</p><pre>shell:&gt;help<br>AVAILABLE COMMANDS<br>Built-In Commands<br> clear: Clear the shell screen.<br> exit, quit: Exit the shell.<br> help: Display help about available commands.<br> history: Display or save the history of previously run commands<br> script: Read and execute commands from a file.<br> stacktrace: Display the full stacktrace of the last error.<br>shell:&gt;</pre><p><strong>Voila</strong>, we have a nice CLI application running with set of available (<em>built-in</em>) commands.</p><h3>Customizing our application</h3><p>Banner and log level can be customized to suit our specific needs same as in any other Spring Boot application (please refer to the official Spring Boot docs for this). <strong>Spring Shell</strong> CLI applications, however, offer some specific customization options, the most notable one being the ability to adjust the shell prompt. As can be seen from the examples above, the application greets the users with a default prompt message: “<strong>shell:&gt;</strong>”</p><p>We will change this message into “<strong>cli-demo:&gt;</strong>”</p><p>In order to do so, we need to configure our Spring application with a Bean implementing the <em>PromptProvider</em> interface:</p><pre>public interface PromptProvider {<br> AttributedString getPrompt();<br>}</pre><p>In the package <em>com.ag04.clidemo.shell</em> simply add a Java class named <em>ClidemoPromptProvider</em> with the following content:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e35b99af9e10e4c9299d81848b0e3959/href">https://medium.com/media/e35b99af9e10e4c9299d81848b0e3959/href</a></iframe><p>In this simple implementation, we have changed the prompt from <strong>shell:&gt;</strong> to <strong>CLI-DEMO:&gt;</strong> and have also changed its color to blue. This class is annotated with the <a href="http://twitter.com/Component">@Component</a> annotation so that Spring can discover and register this bean during start up. No further changes are needed, simply, build and rerun the application and you should be greeted with a new custom prompt.</p><p>Real life <em>PromptProvider</em> implementations can be far more complex, than this simple example. They can contain complex application logic that changes the prompt to reflect, for example, user status (signed in or not), application state, current folder path etc.</p><p>Now its time to add some functionality to our CLI application.</p><h3>Hello world: implement your first command</h3><p>As always it‘s good to start with a simple Hello World example. In our case it will be an ”<strong>echo</strong>” command that prints a greeting message to a person whose name was supplied as a parameter to the command.</p><p>Commands are the core of the <strong>Spring Shell</strong> library, they are equivalent to the <em>Controller</em> object in the classical Web or Rest API application. In short, Commands are the higher level components responsible for processing user input.</p><p>Start by creating the following class named <strong>EchoCommand.java</strong> in the package: <strong>com.ag04.clidemo.command</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/17e18048d339067842b5bac396100571/href">https://medium.com/media/17e18048d339067842b5bac396100571/href</a></iframe><p>Try it out! Build and rerun your app and type: “<strong>echo Domagoj</strong>”, you should see the following output.</p><pre>shell:&gt;echo Domagoj<br>Hello Domagoj! You are running spring shell cli-demo.<br>shell:&gt;</pre><p><strong>HINT:</strong> Execute the <strong>help</strong> command again and you should see our new <strong>echo</strong> command listed, with the appropriate command description.</p><pre>shell:&gt;help<br>AVAILABLE COMMANDS<br>Built-In Commands<br> clear: Clear the shell screen.<br> exit, quit: Exit the shell.<br> help: Display help about available commands.<br> history: Display or save the history of previously run commands<br> script: Read and execute commands from a file.<br> stacktrace: Display the full stacktrace of the last error.</pre><pre>Echo Command<br> echo: Displays greeting message to the user whose name is supplied</pre><p>This is a result of the <em>@ShellMethod</em> and <em>@ShellOption</em> annotations added to the <strong>EchoCommand</strong>, which provide the necessary information to Spring Shell. For more information concerning the options on customizing your commands please consult the official Spring Shell documentation.</p><p>Now that we have our first command, its time to make our application output a little bit more attractive/engaging by adding some colors to it.</p><h3>ShellHelper: adding some color to the output</h3><p>At the moment our application uses the same (standard) terminal color for displaying the entire echo message. What if we would like to display the first part of the message <em>”Hello %s!”</em> in a different color, say green? One of the great novelties made by <a href="https://getbootstrap.com/"><strong>Bootstrap</strong></a> was introduction of the practice to convey meaning to the users by using colors, with a handful of color utility CSS classes available to the developers. Thus came into existence the use of: success, info, danger and other familiar Bootstrap CSS styles. Lets attempt to emulate this practice in our CLI application.</p><p>To do so we will create a <em>ShellHelper</em> util class that we will use to color the output of our commands. First, in the package <strong>com.ag04.clidemo.shell </strong>create a new Java <em>enumeration</em> of the name <strong>PromptColor</strong>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/215f6898f000ef140b0c4325d082e4d0/href">https://medium.com/media/215f6898f000ef140b0c4325d082e4d0/href</a></iframe><p>With this <em>enumeration</em> in place we can proceed and define which colors will be used for which “style” of message in our application. In the <strong>application.properties</strong> file (empty at the moment) found in the <strong>src/resources/</strong> folder, add the following lines:</p><pre># — contextual colors — — — — — — — — — — — — — — — — — — — — <br>shell.out.info=CYAN<br>shell.out.success=GREEN<br>shell.out.warning=YELLOW<br>shell.out.error=RED</pre><p>Now, in the same package crate a Java class named <strong>ShellHelper</strong>, with the following code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5b0fadd26d3176bf3bf6b79b2fa025d7/href">https://medium.com/media/5b0fadd26d3176bf3bf6b79b2fa025d7/href</a></iframe><p>Now we can use this class in our commands to display entire, or just part of the, message in particular style. Before we do this, we need to make this class available to our application. Add Spring configuration class <em>SpringShellConfig</em> in the package <strong>com.ag04.clidemo.config</strong>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0b7c50738379f59774ff05f8c11c06b2/href">https://medium.com/media/0b7c50738379f59774ff05f8c11c06b2/href</a></iframe><p>Finally, change <em>EchoCommand</em> so that it uses this util class to construct the returning String:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4ed75673b897331e4436a244720289e8/href">https://medium.com/media/4ed75673b897331e4436a244720289e8/href</a></iframe><p>To see all the applied changes in action, rebuild and execute <strong>clidemo</strong> again. The output of the <strong>echo</strong> command should now consist of the message displayed in two colors, as visible in the image bellow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sWUjOLcAc-e9cALbytsVHw.png" /><figcaption>Echo command with colored output</figcaption></figure><p>In the current implementation, our <strong>echo</strong> command returns a String (as a result of command execution) which is then also displayed in the terminal, yet there are cases when we would also like to print some informational messages to the user during the execution of our commands.</p><p>To support this, lets expand <strong>ShellHelper</strong> class and add several print methods as shown in the code snippet bellow.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2e1930a56b7526df1422b4fed3f431bc/href">https://medium.com/media/2e1930a56b7526df1422b4fed3f431bc/href</a></iframe><p>With these tools at hand, we can now modify our <strong>echo</strong> command and demonstrate the capability to print contextual messages, we just added. Thus change the body of the echo method to look as in the code snippet below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7d2c8afdff68a1f88275553872829d37/href">https://medium.com/media/7d2c8afdff68a1f88275553872829d37/href</a></iframe><p>Finally, rebuild and execute <strong>clidemo</strong> once more and you should see the following output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8jHmQ7RRxLwH6aXCO4ssAg.png" /></figure><p><strong>With this we conclude the first part. In the </strong><a href="https://medium.com/agency04/developing-cli-application-with-spring-shell-part-1-807cd3a32461"><strong>next part</strong></a><strong> we will expand this sample skeleton application with examples of how to capture user input.</strong></p><p><strong>HINT</strong>: Both <em>PromptColor</em> and <em>ShellHelper</em> classes are written in such a way that they can be easily taken out of this project and put in a separate <strong>shell-utils</strong> library (jar) for re-use in various different CLI projects.</p><h4>Rest of the series:</h4><p><strong>Part 2: </strong><a href="https://medium.com/agency04/developing-cli-application-with-spring-shell-part-2-4be6ce252678"><strong><em>Capturing user’s input in the CLI application</em></strong></a></p><p>Part 3: <a href="https://medium.com/agency04/developing-cli-application-with-spring-shell-part-3-b4c247fdf558"><em>Displaying the progress of CLI command execution with the use of counters, spinners and progress bars</em></a></p><p>Part 4: <a href="https://medium.com/@domagoj.madunic/developing-cli-application-with-spring-shell-part-4-8bd2aafa7146"><em>Displaying the data with the use of tables in a Spring Shell based CLI application</em></a></p><p>Part 5: <a href="https://medium.com/agency04/developing-cli-application-with-spring-shell-part-5-c13403cb79b4"><em>Securing CLI application with Spring Security</em></a></p><h4>Sample Code:</h4><p>The entire source code for this tutorial is available at the following GitHub repository:</p><p><a href="https://github.com/dmadunic/clidemo">dmadunic/clidemo</a></p><h4>Additional resources:</h4><p>Spring Shell project site:</p><ul><li><a href="https://projects.spring.io/spring-shell/">https://projects.spring.io/spring-shell/</a></li></ul><p>Spring Shell official documentation:</p><ul><li><a href="https://docs.spring.io/spring-shell/docs/current-SNAPSHOT/reference/htmlsingle/">https://docs.spring.io/spring-shell/docs/current-SNAPSHOT/reference/htmlsingle/</a></li><li><a href="https://docs.spring.io/spring-shell/docs/current/api/">https://docs.spring.io/spring-shell/docs/current/api/</a></li></ul><p><strong>Thank you for reading! I do hope you enjoyed it and please share if you did.</strong></p><figure><a href="http://bit.ly/MediumAGENCY04"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tquvcAixKbvB7IvqqXTl8Q.png" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=807cd3a32461" width="1" height="1" alt=""><hr><p><a href="https://medium.com/agency04/developing-cli-application-with-spring-shell-part-1-807cd3a32461">Developing CLI application with Spring Shell (part 1)</a> was originally published in <a href="https://medium.com/agency04">Agency04</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>