<?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 Firas Messaoudi on Medium]]></title>
        <description><![CDATA[Stories by Firas Messaoudi on Medium]]></description>
        <link>https://medium.com/@firas-messaoudi?source=rss-15d89be443e9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*rA4MzCM47VtO7oXiIeWeMA.jpeg</url>
            <title>Stories by Firas Messaoudi on Medium</title>
            <link>https://medium.com/@firas-messaoudi?source=rss-15d89be443e9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 21:06:42 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@firas-messaoudi/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[Spring AI: Build AI features for spring applications]]></title>
            <link>https://firas-messaoudi.medium.com/spring-ai-build-ai-features-for-spring-applications-f9c2df55bff8?source=rss-15d89be443e9------2</link>
            <guid isPermaLink="false">https://medium.com/p/f9c2df55bff8</guid>
            <category><![CDATA[spring-ai]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Firas Messaoudi]]></dc:creator>
            <pubDate>Sat, 02 May 2026 14:57:49 GMT</pubDate>
            <atom:updated>2026-05-02T15:02:40.638Z</atom:updated>
            <content:encoded><![CDATA[<p>In this new story we are going to learn how to use spring AI in order to build AI features in java spring applications.</p><p>We will learn how to use RAG one of the main AI cores , also embeddings , vectors db , chat prompts and other features within a spring boot application.</p><p>During this course and in order to apply and practice most of the features , we will try to build an internal document assistant , think of it as chatGpt for your own personal documents or books . we will implement the following features:</p><ul><li>User uploads document/Book</li><li>Extract text</li><li>Split document into chunks</li><li>Convert chunks into vectors and store it into vector DB (pg vector)</li><li>User asks a question</li><li>Return AI answer with source chunks</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7seh5Gx5vUtFJvxodRHjNQ.png" /></figure><h4>Key concepts</h4><ul><li><strong>Chunks</strong>: Small pieces of the document, as LLMs cannot handle large document at once so we split it into chunks(small paragraphs)</li><li><strong>Embedding</strong>: It’s a method to convert text to mathematical vectors(numbers) so we can do the search by meaning and not by keyword</li><li><strong>Vectors</strong>: The result of the embedding which is the numerical representation of the meaning: Very close vectors have similar meaning</li><li><strong>RAG</strong> (Retrieval Augmented Generation): The technique of retrieve relevant data and uses it to generate the answer</li></ul><h4>How does RAG works ?</h4><ul><li>Step 1 : Users asks “What is spring ai ?</li><li>Step 2: Question will be converted to vector using embedding method</li><li>Step 3: Search for similar chunks From vector DB and return Top K similar chunks of the question (filtered by userId and docId)</li><li>Step 4: Build the prompt that will be send to the LLM: context(chunks) + question</li><li>Step 5: Send the prompt to LLM which will answer using only the context</li></ul><h4>Why is RAG important?</h4><p>The answer will be more accurate as it will be only from the user’s document , so there will be no hallucination and if there is no answer the LLM will respond with a default answer as he doesn’t know.</p><h4>Implementation</h4><p>After we went through most of the concepts , we will move to the implementation , we will focus mainly on the upload , document processing and the chat flow.</p><p><strong>Stack</strong>: Spring boot , Spring AI , Postgres (Pg Vector)</p><p><strong>Configuartion:</strong></p><p>Define open ai and vectorstore properties</p><p>Open AI api key could be generated from : <a href="https://platform.openai.com/">https://platform.openai.com/</a></p><pre>spring:<br>  datasource:<br>    url: jdbc:postgresql://localhost:5432/chatbooks<br>    username: postgres<br>    driver-class-name: org.postgresql.Driver<br>  jpa:<br>    hibernate:<br>      ddl-auto: update<br><br>  ai:<br>    openai:<br>      api-key: ${OPEN_AI_API_KEY}<br>      embedding:<br>        options:<br>          model: text-embedding-3-small<br><br>    vectorstore:<br>      pgvector:<br>        initialize-schema: true<br>        table-name: vector_store<br>        dimensions: 1536</pre><p><strong>Document upload</strong></p><p>Once the user uploads a book or a document it will pass through these difference steps:</p><ul><li>Upload and save the book entity</li></ul><pre>@Transactional<br>public BookEntity uploadBook(MultipartFile file, Long userId) {<br>    String filePath = fileStorageService.store(file);<br>    UserEntity user = userRepository.findById(userId).orElseThrow(() -&gt; new RuntimeException(&quot;User not found&quot;));<br>    BookEntity book = BookEntity.builder()<br>            .title(extractTitle(file.getOriginalFilename()))<br>            .originalFileName(file.getOriginalFilename())<br>            .filePath(filePath)<br>            .status(BookStatus.PROCESSING)<br>            .user(user)<br>            .build();<br><br>    BookEntity savedBook = bookRepository.save(book);<br><br>    documentProcessingService.processBook(savedBook);<br><br>    return savedBook;<br>}</pre><ul><li>Process the book : Extract it as text, split int into chunks , convert chunks into embedding vectors and store it in vectorstore</li></ul><p>Splitting startegy will be around 1000, 1200 characters and 200 characters overlap to prevent losing meaning between chunks. It is very important</p><pre>@Transactional<br>public void processBook(BookEntity book) {<br>    try {<br>        String text = pdfTextExtractionService.extractText(Path.of(book.getFilePath()));<br><br>        List&lt;DocumentChunkEntity&gt; chunks = splitIntoChunks(text, book);<br><br>        chunkRepository.saveAll(chunks);<br><br>        embeddingService.storeBookChunks(book, chunks);<br><br>        book.setStatus(BookStatus.READY);<br>        bookRepository.save(book);<br><br>    } catch (Exception e) {<br>        book.setStatus(BookStatus.FAILED);<br>        book.setProcessingError(e.getMessage());<br>        bookRepository.save(book);<br>        throw e;<br>    }<br>}<br>    private List&lt;DocumentChunkEntity&gt; splitIntoChunks(String text, BookEntity book) {<br>        int chunkSize = 1200;<br>        int overlap = 200;<br><br>        List&lt;DocumentChunkEntity&gt; chunks = new ArrayList&lt;&gt;();<br><br>        int start = 0;<br>        int index = 0;<br><br>        while (start &lt; text.length()) {<br>            int end = Math.min(start + chunkSize, text.length());<br><br>            String chunkText = text.substring(start, end).trim();<br><br>            if (!chunkText.isBlank()) {<br>                chunks.add(DocumentChunkEntity.builder()<br>                        .book(book)<br>                        .user(book.getUser())<br>                        .content(chunkText)<br>                        .chunkIndex(index)<br>                        .startCharIndex(start)<br>                        .endCharIndex(end)<br>                        .build());<br>            }<br><br>            index++;<br>            start += chunkSize - overlap;<br>        }<br><br>        return chunks;<br>    }</pre><pre>@Service<br>@RequiredArgsConstructor<br>public class EmbeddingService {<br><br>    private final VectorStore vectorStore;<br><br>    @Transactional<br>    public void storeBookChunks(BookEntity book, List&lt;DocumentChunkEntity&gt; chunks) {<br>        List&lt;Document&gt; documents = chunks.stream()<br>                .map(chunk -&gt; new Document(<br>                        chunk.getContent(),<br>                        Map.of(<br>                                &quot;userId&quot;, book.getUser().getId().toString(),<br>                                &quot;bookId&quot;, book.getId().toString(),<br>                                &quot;chunkId&quot;, chunk.getId().toString(),<br>                                &quot;chunkIndex&quot;, chunk.getChunkIndex(),<br>                                &quot;pageNumber&quot;, chunk.getPageNumber() == null ? -1 : chunk.getPageNumber()<br>                        )<br>                ))<br>                .toList();<br><br>        vectorStore.add(documents);<br>    }<br>}</pre><p>Now we finished the upload process and we have the document splited into chunks that are converted into vectors and stored.</p><h4>Chat Process</h4><p>First of all we need to add the chatClient as a bean :</p><pre>@Configuration<br>public class ChatClientConfig {<br><br>    @Bean<br>    public ChatClient chatClient(ChatClient.Builder builder) {<br>        return builder<br>                .defaultSystem(&quot;&quot;&quot;<br>                        You are a helpful AI reading assistant.<br>                        Answer questions using the provided book context.<br>                        If the answer is not in the context, say you could not find it in the book.<br>                        &quot;&quot;&quot;)<br>                .build();<br>    }<br>}</pre><p>Retrieve the relevant top 5 chunks related to the question:</p><pre>private List&lt;Document&gt; retrieveRelevantChunks(Long userId, Long bookId, String question) {<br>    SearchRequest request = SearchRequest.builder()<br>            .query(question)<br>            .topK(5)<br>            .similarityThreshold(0.5) // accuracy of the similarity <br>            .filterExpression(<br>                    &quot;userId == &#39;&quot; + userId + &quot;&#39; &amp;&amp; bookId == &#39;&quot; + bookId + &quot;&#39;&quot;<br>            )<br>            .build();<br><br>    return vectorStore.similaritySearch(request);<br>}</pre><p>Build the context that will be sent to the chatclient:</p><pre>private String buildContext(List&lt;Document&gt; documents) {<br>    if (documents == null || documents.isEmpty()) {<br>        return &quot;&quot;;<br>    }<br><br>    StringBuilder context = new StringBuilder();<br><br>    for (int i = 0; i &lt; documents.size(); i++) {<br>        Document doc = documents.get(i);<br><br>        context.append(&quot;Source &quot;)<br>                .append(i + 1)<br>                .append(&quot;:\n&quot;)<br>                .append(doc.getText())<br>                .append(&quot;\n\n&quot;);<br>    }<br><br>    return context.toString();<br>}</pre><p>The final step will be calling the chatClient with the context and the question and getting the answer.</p><p>For this step we will consider the case when the user resume a previous conversation , as the LLM is stateless and does not keep conversation history automatically , we will use the chatMessageHistory and combine it within the RAG implementation, meaning sending the last 10 conversation for example along the context to the model.</p><pre>List&lt;ChatMessageEntity&gt; history = chatMessageRepository.findTop10ByChatSessionIdOrderByCreatedAtDesc(sessionId);</pre><pre>    private String buildConversationHistory(List&lt;ChatMessageEntity&gt; messages) {<br>        if (messages == null || messages.isEmpty()) {<br>            return &quot;No previous conversation.&quot;;<br>        }<br><br>        return messages.stream()<br>                .map(message -&gt; {<br>                    String role = switch (message.getRole()) {<br>                        case USER -&gt; &quot;User&quot;;<br>                        case ASSISTANT -&gt; &quot;Assistant&quot;;<br>                        case SYSTEM -&gt; &quot;System&quot;;<br>                    };<br><br>                    return role + &quot;: &quot; + message.getContent();<br>                })<br>                .collect(Collectors.joining(&quot;\n\n&quot;));<br>    }</pre><p>Now we combine it with the context and the question and call the chatClient.</p><pre>String answer = chatClient.prompt()<br>        .system(&quot;&quot;&quot;<br>                You are a helpful AI reading assistant.<br><br>                Rules:<br>                - Answer only using the provided book context.<br>                - Use the conversation history only to understand follow-up questions.<br>                - Do not use outside knowledge.<br>                - If the answer is not present in the context, say:<br>                  &quot;I could not find the answer in this book.&quot;<br>                - Be concise but clear.<br>                &quot;&quot;&quot;)<br>        .user(&quot;&quot;&quot;<br>                Book title: %s<br><br>                Context:<br>                %s<br>                <br>                History:<br>                %s<br><br>                User question:<br>                %s<br>                &quot;&quot;&quot;.formatted(book.getTitle(), context, buildConversationHistory(history), question))<br>        .call()<br>        .content();</pre><p>As described the answer will be based only on the context provided and use the history conversation without outside resources.</p><p>During this article we were able to learn how to use ai features such as RAG, chat prompts , vectors .. into spring based application. This will allow to implement more and more advanced features in our spring application.</p><p>Git repo: <a href="https://github.com/FirasMessaoudi/spring-ai">https://github.com/FirasMessaoudi/spring-ai</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f9c2df55bff8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Restricting access to services deployed on Aks using nginx-ingress controller]]></title>
            <link>https://firas-messaoudi.medium.com/restricting-access-to-services-deployed-on-aks-using-nginx-ingress-conroller-89291df69036?source=rss-15d89be443e9------2</link>
            <guid isPermaLink="false">https://medium.com/p/89291df69036</guid>
            <category><![CDATA[ingress]]></category>
            <category><![CDATA[azure-kubernetes-service]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[Firas Messaoudi]]></dc:creator>
            <pubDate>Mon, 31 Oct 2022 15:39:13 GMT</pubDate>
            <atom:updated>2022-11-01T08:25:36.131Z</atom:updated>
            <content:encoded><![CDATA[<p>While working with services deployed on azure kubernetes services (AKS) we might need to expose those services outside our cluster.</p><p>To do so we will need to create an ingress resource for the service that we need to expose.</p><h4>What is ingress ?</h4><p>Ingress exposes HTTP and HTTPS routes from outside the cluster to services within the cluster. Traffic routing is controlled by rules defined on the Ingress resource.</p><p>Here is an overview of the traffic managed by ingress:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_FhZf00AIH1zi2cHsSRsaQ.png" /><figcaption>Ingress</figcaption></figure><h3>Prerequisites</h3><p>In order to create an ingress resource, we must install an ingress controller in our cluster.</p><p>We will use helm to install nginx-ingress controller(there are many other ingress controllers other than nginx) as below:</p><pre>NAMESPACE=ingress-basic<br>helm repo add ingress-nginx <a href="https://kubernetes.github.io/ingress-nginx">https://kubernetes.github.io/ingress-nginx</a><br>helm repo update<br>helm install ingress-nginx ingress-nginx/ingress-nginx \<br>  --create-namespace \<br>  --namespace $NAMESPACE \<br>  --set controller.service.externalTrafficPolicy=Local \<br>  --set controller.service.annotations.&quot;service\.beta\.kubernetes\.io/azure-load-balancer-health-probe-request-path&quot;=/healthz</pre><h4>Create ingress resources</h4><p>Now that our cluster has an ingress controller we can start creating ingress resources for our services.</p><p>First we need to fetch th external ip provided by the ingress controller</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uaeCoCkD_3bPVSODKoNcww.png" /><figcaption>External Ip</figcaption></figure><p>Once we got our external Ip we can create an ingress. In this example we are creating an ingress for a keycloak service deployed in our cluster.</p><pre>apiVersion: networking.k8s.io/v1<br>kind: Ingress<br>metadata:<br>  name: keycloak-ingress<br>  annotations:<br>    kubernetes.io/ingress.class: &quot;nginx&quot;<br>    nginx.ingress.kubernetes.io/ssl-passthrough: &quot;true&quot;<br>spec:<br>  rules:<br>  - host: keycloak.YOUR-EXTERNAL-IP.nip.io<br>    http:<br>      paths:<br>      - path: /<br>        pathType: Prefix<br>        backend:<br>          service:<br>            name: keycloak<br>            port:<br>              number: 8080</pre><p>Now we just need to apply this yaml file.</p><pre>kubectl apply -f &quot;PATH to your ingress yaml file&quot;</pre><p>We can check that our ingress resource works by visiting the host adress , we will be redirected to the keycloak welcome page.</p><h4>IP Whitelisting</h4><p>Now we come to the most interesting part , our ingress resource is working fine , but it’s accessible to everyone who possesses that host adresse.</p><p>In order to prevent anyone from accessing our exposed services , we will add some “Whitelisted static ip” to the ingress ressources so that only traffic coming from this Ip will be allowed , otherwise we will return a forbidden error message.</p><p>To do so we need to go back to our ingress definition and add this property:</p><pre>nginx.ingress.kubernetes.io/whitelist-source-range: &quot;41.231.58.146&quot;</pre><p>We can add multiple IPs separated by “,” or a subnet like this “41.231.X.X/32”</p><p>So the final ingress resource definition will be as below:</p><pre>apiVersion: networking.k8s.io/v1<br>kind: Ingress<br>metadata:<br>  name: keycloak-ingress<br>  annotations:<br>    kubernetes.io/ingress.class: &quot;nginx&quot;<br>    nginx.ingress.kubernetes.io/ssl-passthrough: &quot;true&quot;<br>    nginx.ingress.kubernetes.io/whitelist-source-range: &quot;41.231.58.146&quot;<br>spec:<br>  rules:<br>  - host: keycloak.EXTERNAL-IP.nip.io<br>    http:<br>      paths:<br>      - path: /<br>        pathType: Prefix<br>        backend:<br>          service:<br>            name: keycloak<br>            port:<br>              number: 8080</pre><p>We need to apply this modification by applying again:</p><pre>kubectl apply -f &quot;PATH to your ingress yaml file&quot;</pre><p>No if we try to access our resources from an Ip not in the whitelist , we will receive something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ztM34TL0-eNYlR2Tetes_Q.png" /><figcaption>Test whitelist Ip</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=89291df69036" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploy Wso2 Api Manager with ELK stack and prometheus operator using Azure Kubernetes Service(AKS)]]></title>
            <link>https://firas-messaoudi.medium.com/deploy-wso2-api-manager-with-elk-stack-and-prometheus-operator-using-azure-kuberenetes-service-aks-9a7c6f68bf4f?source=rss-15d89be443e9------2</link>
            <guid isPermaLink="false">https://medium.com/p/9a7c6f68bf4f</guid>
            <category><![CDATA[choreo]]></category>
            <category><![CDATA[elk-stack]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[wso2]]></category>
            <category><![CDATA[prometheus]]></category>
            <dc:creator><![CDATA[Firas Messaoudi]]></dc:creator>
            <pubDate>Mon, 05 Sep 2022 15:56:25 GMT</pubDate>
            <atom:updated>2022-09-24T15:27:53.315Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://wso2.com/api-management/">API management</a> involves managing the API life cycle from creation, testing, documentation, publishing, discovering and monetizing. In addition to this, an API management platform enforces security and provides in-depth analytics on API usage. This ensures that the APIs are secure and consumable.</p><p>This is a sample overview of the api management and the interactions between its components.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RWmi5dd3F_C1R79iuv3pbA.png" /></figure><ul><li>The api managers will create the apis from the publisher portal, deploy it in the gateway and publish it in developer portal</li><li>The Api developer will subscribe to these apis from developer portal and invoke them from application</li><li>The api gateway will handle the upcoming requests and get the response from the backend where the api is implemented</li></ul><p><strong>What are we going to use ?</strong></p><ul><li>Wso2 Api Manager to manage api lifecycle</li><li>Elasticstack(elasticsearch,logstash and kibana) for logging system</li><li>Prometheus , garafana and alert manager for monitoring</li><li>Wso2 choreo for analytics</li><li>Slack as a notfication channel(you can use any other channel like teams or email..)</li></ul><h4>Pre-requisites</h4><ul><li>Aks cluster or any other cluster like minikube</li><li>clone the git repo “<a href="https://github.com/FirasMessaoudi/wso2-deployment">https://github.com/FirasMessaoudi/wso2-deployment</a>” which contains all required yaml files and the steps to follow</li></ul><p>This is the architecture of the system that we are going to implement.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IJjLqnUC-0XOxgCS1Ec8Bg.png" /><figcaption>Architecture</figcaption></figure><ul><li>Wso2 and Kibana ingress will expose the related services and manager the external access.</li><li>Wso2,kibana and elasticsearch services (SVC) will expose the applications running inside the pods.</li><li>Wso2 and logstash are two containers running the same pod that have access to a shared volume that contains logs generated by wso2. Logstash processes these logs and sends them to elasticsearch</li><li>We have two init Containers inside the pods where logstash and<br>Kibana are running to ensure that the elasticsearch service is running correctly before the creation of the containers.</li><li>For analytics we have configured wso2 api manager to send<br>api’s statistics to choreo</li><li>For the monitoring part, prometheus server retrieves the standard metrics<br>exposed by the pods and other metrics exposed by the export node(cpu,memory…).grafana will interrogate prometheus to get these metrics and create dashboards.</li><li>In case an unexpected behavior happens in nodes or pods(use<br>excessive memory or cpu for example), we will create alerts to notify users about these behavior.</li></ul><h3>Steps</h3><p>After creating and connecting the cluster in aks , the first step will be to create the namespaces where we are going to isolate our resources. we’ll have two namespace wso2 and monitoring.</p><ul><li>Wso2 namespace will regroup wso2 api manager and elk stack resources</li><li>monitoring namespace will regroup prometheus , grafana and alert manager resources</li></ul><p>To create the namespaces we go under the bash folder and execute the file create-namespace.sh</p><pre>./create-namespace.sh</pre><p>Then we need to install the ingress controller service in order to get the external ip adress which is required in the next steps.</p><p>To create install nginx ingress we will use helm (pre installed in the cluster)</p><pre>NAMESPACE=ingress-basic<br>helm repo add ingress-nginx <a href="https://kubernetes.github.io/ingress-nginx">https://kubernetes.github.io/ingress-nginx</a><br>helm repo update<br>helm install ingress-nginx ingress-nginx/ingress-nginx \<br>--create-namespace \<br>--namespace $NAMESPACE \<br>--set controller.service.externalTrafficPolicy=Local \<br>--set controller.service.annotations.&quot;service\.beta\.kubernetes\.io/azure-load-balancer-health-probe-request-path&quot;=/healthz</pre><p>No we can get the external Ip</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C2Tz57Vx0il1y_G1fOl2JA.png" /><figcaption>External Ip</figcaption></figure><p>Then go the the choreo console and generate a key to use it to send analytics data from wso2</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1gV_7riSsXjkdOVjGkuuFw.png" /><figcaption>On Prem Key</figcaption></figure><p>No we go to the deployment file under configs/apim and update the following properties:</p><pre>hostname = &quot;wso2apim-portal.20.124.60.109.nip.io&quot;<br>service_url = &quot;https://wso2apim-gateway.20.124.60.109.nip.io/services/&quot;<br>http_endpoint = &quot;http://wso2apim-gateway.20.124.60.109.nip.io&quot;<br>https_endpoint = &quot;https://wso2apim-gateway.20.124.60.109.nip.io&quot;<br>[apim.analytics]<br>enable = true<br>config_endpoint = &quot;https://analytics-event-auth.choreo.dev/auth/v1&quot;<br>auth_token = &quot;YOUR GENERATED ON-PREM-KEY&quot;</pre><p>Note that the hostname will be the same in the ingress host of wso2 api manager and the endpoint will be the same as the ingress host of wso2 apim gateway that we’ll create later</p><p>After updating the deployment we can create our config maps by executing ./create-config.sh under the bash folder</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/632/1*r1y9wMJTSAxgzfql7P_AWw.png" /><figcaption>config maps</figcaption></figure><p>Now that our configs are there , we are ready to deploy our ressources</p><p>we need to start with elasticsearch which is mandatory for the other resources. You can create all resources by executing the bash scripts under bash folder in that order:</p><ul><li>./create-deploy.sh =&gt; this will create deployment for elasticsearch, wso2 api-manager and logstash, kibana</li><li>./create-service.sh =&gt; will create services for elasticsearch, wso2 api manager and kibana.</li></ul><p>We still miss the monitoring part right ?</p><p>To install prometheus ,grafana and alert manager we are going to use the prometheus operator repository which comes with all the required resources for monitoring.</p><pre>helm repo add prometheus-community <a href="https://prometheus-community.github.io/helm-charts">https://prometheus-community.github.io/helm-charts</a><br>helm repo update<br>helm install prometheus prometheus-community/kube-prometheus-stack --namespace monitoring</pre><p>Now we can just check that all our pods and services are running fine before we continue</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o5Q9LVc4Sw7kJWYfDoTi3w.png" /><figcaption>Test deployment</figcaption></figure><p>It seems that everything is fine, as a final a step as we said we’re gonna expose those services using nginx ingress so we need to create an ingress for each service that we need to expose like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IbEhAToWcsHE8hHY_8_wqA.png" /><figcaption>Ingress</figcaption></figure><p>We can notice the presence of the whitelist-range-source annotation, we use this to prevent the ingress to be accessible to anyone , in that case the ingress will accept the trafic only from the ip listed on the whitelist range.</p><p>Now we execute the create-ingress.sh under /bash folder to create all the required ingress.</p><p>This is the list of the ingress created with their hosts:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mlfqdR_hVOrzlzeLirIr0w.png" /><figcaption>Ingress List</figcaption></figure><h3>Monitoring</h3><p><strong>Dashboards</strong></p><p>Now that all our resources are deployed and running , prometheus will scrap the metrics from the pods and the node exporter and grafana will ask prometheus for those metrics to create dashbords and alerts. We just need to navigate to grafana host(garafana.20.124.60.109.nip.io) to explore these dashbords.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wsBuHZSNwRzAryz0718N2A.png" /><figcaption>Grafana dashbord</figcaption></figure><p><strong>Alerts</strong></p><p>From these dashbords we can create alert rules to notify users about any abnormal behaviour in the cluster resources , in this exemple we will create an alert rule about the memory usage , if it passes 2GB we will send a notification in slack application(we can use teams,email…)</p><ol><li>Create slack channel and get webhook link (<a href="https://www.youtube.com/watch?v=6NJuntZSJVA&amp;ab_channel=BoyumITSolutions">https://www.youtube.com/watch?v=6NJuntZSJVA&amp;ab_channel=BoyumITSolutions</a>)</li><li>Create contact point from grafana alerting menu</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QEw9QjweYh7rMPEeuYiCEg.png" /></figure><p>After clicking on test we will receive a notification test to make sure the contact point is working fine</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9XBaSWJGp0OOe8jnl5N7jg.png" /><figcaption>Test slack</figcaption></figure><p>3. Select any panel from dashboards(we will select the memory usage panel) and click on create alert rule</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1SNDpPTmI3GtbbjH90wPsQ.png" /></figure><p>4. Configure Alert rule</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AGUVIZeQIZyI18VtkLYCmg.png" /><figcaption>Configure Alert</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4Ud19um3GLZt_0vgv-dovA.png" /><figcaption>Configure alert 2</figcaption></figure><p>When the condition of the alert is reached the state of the alert will be firing and a notification with details will be sent to the slack channel</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7iGPN3wtJo_8tU7YEvUZKQ.png" /><figcaption>Alerting</figcaption></figure><h3>Manage Api</h3><p>Now we will see , how to deploy a sample api with wso2 api manager publisher portal and consume this api from developer portal by following these steps.</p><ul><li><strong>Deploy sample Api</strong></li></ul><p>From the publisher portal of wso2 api manager (<strong>wso2apim-portal.20.124.60.109.nip.io/publisher</strong>)select deploy sample Api</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-ZhNyGG6XOr6DyR6B4IpnQ.png" /></figure><p>This will create , deploy and publish a sample api with some resources to be directly consumed in developer portal</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zK7X-YEcNSolF7oYqBFunQ.png" /></figure><ul><li><strong>Create Application in developer portal</strong></li></ul><p>Now we switch to the developer portal(<strong>wso2apim-portal.20.124.60.109.nip.io/devportal</strong>) and from the application menu create a new application in order to susbscribe into it</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nQwGZPQs1_W1yFzkScfOjQ.png" /></figure><ul><li><strong>Subscribe to application</strong></li></ul><p>Now from the Api’s menu select the desired api and choose the subscriptions side menu in order to subscribe to the recently created application</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LS03pmOgZHA8s1kzScJZiw.png" /><figcaption>Subscribe</figcaption></figure><ul><li><strong>Generate Key</strong></li></ul><p>In order to consume this api we need an access token which can be generated by selecting the application and the type of the token production or sandbox</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pK8X92G4jfAwIZo2P3zuxw.png" /><figcaption>prod key</figcaption></figure><p>Now we just click on generate keys and copy the access token</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NahficRvD5WBxz5-E3mC6w.png" /><figcaption>Generate access token</figcaption></figure><ul><li><strong>Consume Api</strong></li></ul><p>The final step will be of course consuming the api , we can consume it directly from the developer portal from the try out menu</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A-ZFcKUqbWcX6NLdHMY14Q.png" /></figure><p>We can see here the application that we used in subscription and the type of the generated key , we just need to put the token and select any resource to execute</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-m5ufkwG841XFZ4jxQDGrQ.png" /></figure><p>Wso2 api manager has two other portals:</p><ul><li><strong>Admin Portal (</strong>wso2apim-portal.20.124.60.109.nip.io/admin) where we can add key managers and manage policies and gateways</li><li><strong>Wso2 carbon (</strong>wso2apim-portal.20.124.60.109.nip.io/carbon) where me manager users and roles.</li></ul><h3>Logging</h3><p>After executing some apis and manipulating the api manager , many logs have been generated and logstash has collected these logs to index them in elasticsearch in order to be visualized from kibana.</p><ul><li><strong>Create index Pattern in kibana</strong></li></ul><p>In order to view this logs in kibana we need to navigate to kibana host(wso2-kibana-dahboard.20.124.60.109.nip.io) and create an index pattern from stack management / index pattern</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W9RzfqE2iyHP7eKwcthCvQ.png" /><figcaption>Index pattern</figcaption></figure><ul><li><strong>View logs</strong></li></ul><p>Now we go back to discover menu in order to explore the logs</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aNkHDobEq7chAb5JyoOi2Q.png" /><figcaption>Kiban Logs</figcaption></figure><h3>Statistics and reporting</h3><p>In The final part of this tutorial will focus on the api statistics and reporting from the choreo console</p><p>we just need to navigate to the choreo console and from the insight menu we select the on-prem-key that we generated in order to get the stats</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CFw03GR3W5W6SY0LKy0SXw.png" /><figcaption>Stats</figcaption></figure><p>There are a lot of stats about the usage of the Apis offered by choreo , this is the overview dashboard</p><p>To generate reports we must go to usage report and download the reports with the selected filters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cjvdiEbz4p45q4puvR6ZOA.png" /><figcaption>Reports</figcaption></figure><h3>Conclusion</h3><p>In this tutorial we have seen the steps to deploy wso2 api manager , elk stack and prometheus operator in azure kubernetes service , and expose the services of the cluster using nginx ingress controller. We created alerts to to send notification about any abnormal behavior that could happen in the cluster.</p><p>Finally we manage to configure wso2 api manager to send analytics data to choreo in order to generate dashboards and reports about api usage</p><p>You can find all the required yaml files in order to deploy all the resources , along with the steps , in this git repo (branch master)</p><p><a href="https://github.com/FirasMessaoudi/wso2-deployment">https://github.com/FirasMessaoudi/wso2-deployment</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9a7c6f68bf4f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular End-To-End (E2E) testing using protractor and Jasmine]]></title>
            <link>https://firas-messaoudi.medium.com/angular-end-to-end-e2e-testing-using-protractor-and-jasmine-dbedea91cbc?source=rss-15d89be443e9------2</link>
            <guid isPermaLink="false">https://medium.com/p/dbedea91cbc</guid>
            <category><![CDATA[protractor-framework]]></category>
            <category><![CDATA[e2e-testing]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[jasmine]]></category>
            <dc:creator><![CDATA[Firas Messaoudi]]></dc:creator>
            <pubDate>Mon, 29 Mar 2021 19:08:09 GMT</pubDate>
            <atom:updated>2021-03-31T01:44:03.735Z</atom:updated>
            <content:encoded><![CDATA[<p>Testing is one of the most important phase of the software developement life cycle and yet the most ignored one. It helps reducing the chances of defects in the system.</p><p>E2E (end to end ) as the name says, is meant for testing the application from the start to the end. It will test the behaviour of our application, the UI and how much they respect the requirements.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/526/1*x85BQ0FjMD7wmwa5IE15Rg.png" /></figure><h4>Differences between E2E testing and unit testing</h4><p>Unit testing are used to ensure that the services and the components of the application behave as they are intended (generally the logic of services and components). While e2e makes sure that the high level functionnality of the application (UI for exemple) works as <strong>expected</strong>.</p><h4>Protractor and jasmine</h4><p>In this tutorial we will be using protractor and jasmine as our tools for e2e testing.</p><p><strong>Protractor </strong>is an end-to-end test framework for Angular and AngularJS applications. Protractor runs tests against your application running in a real browser, interacting with it as a user would.</p><p>Protractor provides a very large APIs that we’ll use for our e2e testing, and these are the main ones:</p><ul><li><strong>browser()</strong>: brings all the browser-level operations such as navigation, debugging, etc.</li><li><strong>element():</strong> This is used to look up an element in the DOM based on a search condition or a chain of conditions. It returns an ElementFinder object, and you can perform actions such as getText() or click() on them.</li><li><strong>by.css() , by.name(), by.buttonText(): </strong>locators to find element based on css selector, name attribute or button text.</li></ul><p><strong>Jasmine </strong>is a behavior-driven development framework for testing JavaScript code. It does not depend on any other JavaScript frameworks. It does not require a DOM. And it has a clean, obvious syntax so that you can easily write tests.</p><p>In this tutorial we’re going to focus more on protractor, our e2e testing framework, but we have to introduce some of Jasmine syntax because protractors depends on it to run its tests.</p><p>Jasmine has 3 global functions that we’ll be using during this whole tutorial, the test case below will help us more understand those functions:</p><pre>describe(&quot;A suite is just a function&quot;, <strong>function</strong>() {<br>  <strong>var</strong> a;<br><br>  it(&quot;and so is a spec&quot;, <strong>function</strong>() {<br>    a <strong>=</strong> <strong>true</strong>;<br><br>    expect(a).toBe(<strong>true</strong>);<br>  });<br>});</pre><ul><li><strong>describe():</strong>is the global jasmine function , with two parameters: a string and a function. The string is a name or title for a spec suite — usually what is being tested. The function is a block of code that implements the suite.</li><li><strong>it() :</strong> it’s the function which define the spec , like describe takes a string and a function. The string is the title of the spec and the function is the spec, or test.</li><li><strong>expect():</strong> An expectation in Jasmine is an assertion that is either true or false. A spec with all true expectations is a passing spec. A spec with one or more false expectations is a failing spec.</li><li><strong>beforeEach()</strong> and <strong>afterEach()</strong>: As the name implies, the beforeEach function is called once before each spec in the describe in which it is called, and the afterEach function is called once after each spec.</li></ul><p>these are the famous jasmine functions and the ones we’re gonna need.</p><p>to dive more into jasmine i suggest to follow this course <a href="https://jasmine.github.io/2.4/introduction.html">https://jasmine.github.io/2.4/introduction.html</a>.</p><h4>Configuring Protractor</h4><p>Assuming now we’re familiar with the jasmine syntax, we’re gonna start playing with protratcor in a real application (CRUD application for players management system).</p><p>we will create 3 components that we are going to test later:</p><ul><li>ViewPlayers: Displays all the players</li><li>AddPlayer: add new player</li><li>UpdatePlayer: update an exsiting player.</li></ul><p>to install protractor we just have to run the following command:</p><pre>npm install protractor</pre><p>and this is the structure of our project:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/313/1*yFwA4WP3uNXOBlQtphdDKw.png" /></figure><p>we can see that we have an e2e folder generated automatically when we installed protractor.</p><p>in this folder we will write our e2e tests .</p><h4><strong>Page Object Model (POM)</strong></h4><p>If we take a look at the e2e folder we will notice that besides the protractor configuration file we have two additional files: one app.e2e-spec.ts file (the test file for the appComponent) and another app.po.ts.</p><p>So what is this latter file ?</p><p>this file is typescript file called PageObject , a Design Pattern which has become popular in test automation for enhancing test maintenance and reducing code duplication. A page object is an object-oriented class that serves as an interface to a page of your application. In this page objects we will be fetching the elements used in our tests (tables, headers, buttons , inputs…) and uses them later with the spec files.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xpqm7BgaY4phyu8HKYGzPg.png" /></figure><h4>Testing the viewPlayers component</h4><p>In this tutorial we’ll work on the viewPlayers component to run our tests (you’ll find the rest of the tests related to the other componenets on the git repository)</p><p>To better organise our test architecture, let’s create a page-object folder and create a file <strong>main.po.ts</strong> which will have the shared methods between the other page-objects classes and <strong>view.po.ts</strong> that extends from it and fetch the elements of the viewPlayers</p><p><strong>Main.po.ts</strong></p><pre>import { browser, by, element, promise, ElementFinder } from &#39;protractor&#39;;</pre><pre>export class Main{</pre><pre>navigateToHome():promise.Promise&lt;any&gt; {</pre><pre>return browser.get(&#39;/&#39;);</pre><pre>}</pre><pre>/* Mock data for creating a new Player and editing existing Player */</pre><pre>getMockPlayer(): any {</pre><pre>let player: any = { name: &quot;SALAH&quot;,age: &quot;28&quot;,club: &quot;LIVERPOOL&quot;,country:&#39;EGYPT&#39;}</pre><pre>return player;</pre><pre>}</pre><pre>getEditedMockPlayer(): any {</pre><pre>let player: any = {&quot;name&quot;:&#39;RONALDO&#39;,&#39;age&#39;:&#39;36&#39;,&#39;club&#39;:&#39;JUVENTUS&#39;,&#39;country&#39;:&#39;PORTUGAL&#39;}</pre><pre>return player;</pre><pre>}</pre><pre>/* Methods shared by addPlayer and updatePlayer */</pre><pre>getInputName():ElementFinder {</pre><pre>return element(by.name(&quot;name&quot;));</pre><pre>}</pre><pre>getInputAge(): ElementFinder {</pre><pre>return element(by.name(&quot;age&quot;));</pre><pre>}</pre><pre>getInputClub(): ElementFinder {</pre><pre>return element(by.name(&quot;club&quot;));</pre><pre>}</pre><pre>getInputCountry(): ElementFinder{</pre><pre>return element(by.name(&quot;country&quot;));</pre><pre>}</pre><pre>}</pre><p><strong>View.po.ts</strong></p><pre>import { promise, by, ElementFinder, ElementArrayFinder, element } from &quot;protractor&quot;;</pre><pre>import { Main } from &quot;./main.po&quot;;</pre><pre>export class View extends Main {</pre><pre>getViewContainer():ElementFinder {</pre><pre>return element(by.css(&#39;.container&#39;));</pre><pre>}</pre><pre>getViewContainerHeading(): promise.Promise&lt;string&gt; {</pre><pre>return this.getViewContainer().element(by.css(&quot;h2&quot;)).getText();</pre><pre>}</pre><pre>/*Table Data */</pre><pre>getTable():ElementFinder {</pre><pre>return element(by.css(&#39;table&#39;));</pre><pre>}</pre><pre>getTableHeader(): promise.Promise&lt;string&gt; {</pre><pre>return this.getViewContainer().all(by.tagName(&#39;tr&#39;)).get(0).getText();</pre><pre>}</pre><pre>getTableRow(): ElementArrayFinder {</pre><pre>return this.getViewContainer().all(by.tagName(&#39;tr&#39;));</pre><pre>}</pre><pre>getFirstRowData(): promise.Promise&lt;string&gt; {</pre><pre>return this.getTableRow().get(1).getText();</pre><pre>}</pre><pre>getLastRowData(): promise.Promise&lt;string&gt; {</pre><pre>return this.getTableRow().last().getText();</pre><pre>}</pre><pre>getAddPlayerTag(): ElementFinder {</pre><pre>return this.getViewContainer().element(by.tagName(&#39;app-add-player&#39;));</pre><pre>}</pre><pre>isAddPlayerTagPresent(): promise.Promise&lt;boolean&gt; {</pre><pre>return this.getAddPlayerTag().isPresent();</pre><pre>}</pre><pre>}</pre><p>Now that we have the code for the page object ready, let’s import it into our spec. Here’s the code for our viewPlayers test:</p><pre>import { browser, protractor } from &#39;protractor&#39;;</pre><pre>import { View } from &#39;./page-objects/view.po&#39;;</pre><pre>describe (&#39;View players page&#39;, ()=&gt;{</pre><pre>const view: View = new View;</pre><pre>// executed before each spec</pre><pre>beforeEach( async ()=&gt;{</pre><pre>await view.navigateToHome();</pre><pre>});</pre><pre>it(&#39;Should display Players management system as a title&#39; ,async ()=&gt;{</pre><pre>expect (await view.getViewContainerHeading()).toEqual(&quot;Players management system&quot;);</pre><pre>});</pre><pre>it (&#39;Should have a table &#39;, async () =&gt; {</pre><pre>expect(await view.getTable()).toBeTruthy();</pre><pre>});</pre><pre>it(&#39;Should have the app add player tag&#39;, async () =&gt; {</pre><pre>expect(await view.getAddPlayerTag()).toBeTruthy();</pre><pre>})</pre><pre>it(&#39;Should have a table with headers &#39;, async () =&gt; {</pre><pre>expect (await view.getTableHeader()).toContain(&#39;NAME AGE CLUB COUNTRY&#39;);</pre><pre>})</pre><pre>})</pre><p>The scenarios that were tested above are:</p><ul><li>The viewPlayers should display players management system as a title</li><li>A table should exist</li><li>the app-add-player selector should exist</li><li>The table should have the headers (NAME, AGE, CLUB, COUNTRY)</li></ul><p>Now everything is set up , let’s try it out by running the following command:</p><pre>ng e2e</pre><p>We can see later that all our so huge tests :p were passed succesfully:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1004/1*wuI3lTc6j9ZlSzdgTjYb0g.png" /></figure><p>Now let’s go back to our viewPlayers component and change the title to something different to the one on the tests and run the command again:</p><p>we can see that the test for the heading title is failed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/836/1*tYJ7iDQc7R0PWTLc82xuKA.png" /></figure><p>And that’s where the importance of the E2E testing comes, this is where we can make sure that our frontend (UI) is matching with the requirements.</p><p>Finally let’s Sum up what we’ve done so far:</p><ul><li>We’ve seen the importance of the E2E testing and the difference between unit testing.</li><li>Protractor API and jasmine syntax</li><li>Page Object Model</li><li>Using protractor to test the viewPlayers component.</li></ul><p>I hope that everything is clear enough and after reading this article you can all start writing tests for your application because like we Said in the beginning that testing is a major step of the software developement life cycle.</p><p>You’ll find the rest of the tests in the git responsitory.</p><p><a href="https://github.com/FirasMessaoudi/angular-e2e-testing">FirasMessaoudi/angular-e2e-testing</a></p><p>Don’t forget to clap and leave your feedbacks on the comment section.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dbedea91cbc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Spring Boot Microservices , Monitoring with prometheus and grafana and log aggregation…]]></title>
            <link>https://firas-messaoudi.medium.com/building-spring-boot-microservices-monitoring-with-prometheus-and-grafana-and-log-aggregation-1e51016210ba?source=rss-15d89be443e9------2</link>
            <guid isPermaLink="false">https://medium.com/p/1e51016210ba</guid>
            <category><![CDATA[kibana]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[loggin]]></category>
            <category><![CDATA[logstash]]></category>
            <category><![CDATA[elasticsearch]]></category>
            <dc:creator><![CDATA[Firas Messaoudi]]></dc:creator>
            <pubDate>Sat, 20 Feb 2021 18:12:48 GMT</pubDate>
            <atom:updated>2021-02-22T08:31:15.022Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building Spring Boot Microservices , Monitoring with prometheus and grafana and log aggregation using ELK stack: Part III</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/337/1*GuJPp5hcevkj0rG8xg5k3Q.png" /><figcaption>ELK</figcaption></figure><p>In the <a href="https://firas-messaoudi.medium.com/building-spring-boot-microservices-monitoring-with-prometheus-and-grafana-and-log-aggregation-5ed9ca7dda36">previous parts</a> we maneged to create 3 springboot microservices and monitor them with prometheus and grafana.</p><p>In this part we’re gonna focus on the Log aggregation and analysis.</p><h4>Why it is so important ?</h4><p>Logs are essential informations, allowing us to better understand, analyze and diagnose certain malfunctions, as they can help us follow and trace the different actions carried out by the actors of our system. Only, it becomes very complex to exploit this critical data with so many applications, equipment, services, systems and managed elements in an information system.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*mvjmHh-S4tHW1sY0rWQqhA.png" /><figcaption>log analysis</figcaption></figure><p>As a solution for this problem, we’re gonna use ELK stack, one of the best and efficient tool for log aggregation and analysis.</p><h4>So what is Elk stack ?</h4><p>Composed of Elasticsearch, Logstash and Kibana, ELK is a suite of three complementary open source projects. This trio of tools will make it possible to display an overview to the system administrator while offering him a quick graphical analysis of the elements he is in charge of.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*2MJNL99XfZZhB5px2DUIlg.png" /><figcaption>ELK</figcaption></figure><p><strong>1-Elasticsearch: </strong>Elasticsearch is a real-time distributed and open source full-text search and analytics engine. It is accessible from RESTful web service interface and uses JSON documents to store data. It is built on Java programming language and hence Elasticsearch can run on different platforms. It enables users to explore very large amount of data at very high speed.</p><p><strong>2-Logstash: </strong>Back then, logstash has been used to process logs from applications and send them to Elasticsearch. But , since then logstash has evolved into more general purpose tool that makes it a data processing pipeline.</p><p>The data collected by logstash will be processed and shipped of to one or more destinations (Elasticsearch, kafka, e-mail…).</p><p><strong>3-Kibana: </strong>Kibana is basically an analytics and visualization platform, which lets you easily visualize data from Elasticsearch and analyze it to make sense of it. You can assume Kibana as an Elasticsearch dashboard where you can create visualizations such as pie charts, line charts, and many others.</p><h4>Global Architecture</h4><p>The following is the architecture of ELK Stack which shows the proper order of log flow within ELK. Here, the logs generated from various sources are collected and processed by Logstash, based on the provided filter criteria. Logstash then pipes those logs to Elasticsearch which then analyzes and searches the data. Finally, using Kibana, the logs are visualized and managed as per the requirements.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/660/1*6zntB1gugyuF3nohPjGjPg.png" /><figcaption>elk architecture</figcaption></figure><h4>Elk with microservices</h4><p>All our microservices will push their respective logs to Logstash, which will use Elasticsearch to index them. The indexed logs can be consumed later by Kibana.</p><p>We will use Logback as a logging framework.</p><p>Logback offers a faster implementation , provides more options for configuration, and more flexibility in archiving old log files.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*YOe_Pltc-N6ZqV1WlNon0Q.png" /></figure><h4>Setting up ELK with spring boot microservice</h4><p><strong>1-Installing Elasticsearch</strong></p><p>Download Elasticsearch zip file from <a href="https://www.elastic.co/downloads/elasticsearch">https://www.elastic.co/downloads/elasticsearch</a></p><p>Unzip it then run it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/466/1*LISldpQZT56W_0Xmc4o6AQ.png" /></figure><p>To make sure ecerything works fine open the browser on : <a href="http://localhost/">http://localhost</a> :9200. You must see something similar to this cluster informations :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/525/1*Duxp8Ug1Tod6dlodFG4F5g.png" /></figure><p><strong>2-Installing Kibana</strong></p><p>Download Elasticsearch zip file from <a href="https://www.elastic.co/downloads/kibana">https://www.elastic.co/downloads/kibana</a></p><p>Unzip it then run it.</p><p>Open up Kibana in your browser with: <a href="http://localhost:5601.">http://localhost:5601.</a> You will be presented with the Kibana home page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*nBSsdOsaCtxXe5_qvGKVeQ.png" /></figure><p><strong>3-Installing &amp; configuring logstash</strong></p><p>Download Elasticsearch zip file from <a href="https://www.elastic.co/downloads/logstash">https://www.elastic.co/downloads/logstash</a></p><p>Unzip it.</p><p>A logstash configuration consists mainly on 3 stages:</p><p>1. <strong>Input</strong></p><p>The input section in the configuration file defines the input plugin to use. Each plugin has its own configuration options, which you should research before using.In our cas it will be a json flow fetched from the logback of our microservices and we will be using the tcp plugin wich will listen to any logs sent.</p><p>2. <strong>Filtre</strong></p><p>The filter section in the configuration file defines what filter plugins we want to use, or in other words, what processing we want to apply to the logs. Each plugin has its own configuration options, which you should research before using.</p><p>3. <strong>Output</strong></p><p>The output section in the configuration file defines the destination to which we want to send the logs to(elasticsearch for example). As before, each plugin has its own configuration options, which you should research before using.</p><p>So our logstash file config will be similar to this:</p><pre>input {<br> tcp {<br>  port =&gt; 7000<br>  codec =&gt; &quot;json&quot;<br> }<br>}</pre><pre>output {<br> elasticsearch {<br>   hosts =&gt; [&quot;localhost:9200&quot;]<br>   index =&gt;&quot;ecommerce&quot;<br> }<br>}</pre><p>Run it</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/559/1*-N3P0ruPOxCK-_5PA6XqGA.png" /></figure><p>Losgatsh will start and exposes two ports:</p><ul><li>9600 logstash api endpoint</li><li>7000 tcp input listener defined previously.</li></ul><p><strong>4-Configuring logback</strong></p><p>We need first to add these maven dependencies to each of our microservices:</p><pre>&lt;dependency&gt;</pre><pre>&lt;groupId&gt;net.logstash.logback&lt;/groupId&gt;</pre><pre>&lt;artifactId&gt;logstash-logback-encoder&lt;/artifactId&gt;</pre><pre>&lt;version&gt;5.1&lt;/version&gt;</pre><pre>&lt;/dependency&gt;</pre><pre>&lt;dependency&gt;</pre><pre>&lt;groupId&gt;ch.qos.logback&lt;/groupId&gt;</pre><pre>&lt;artifactId&gt;logback-core&lt;/artifactId&gt;</pre><pre>&lt;/dependency&gt;</pre><pre>&lt;dependency&gt;</pre><pre>&lt;groupId&gt;ch.qos.logback&lt;/groupId&gt;</pre><pre>&lt;artifactId&gt;logback-classic&lt;/artifactId&gt;</pre><pre>&lt;/dependency&gt;</pre><p>Then add these config class :</p><pre>@Configuration</pre><pre>public class LogbackConfiguration {</pre><pre>private static final String LOGSTASH_APPENDER_NAME = &quot;LOGSTASH&quot;;</pre><pre>private static final String ASYNC_LOGSTASH_APPENDER_NAME = &quot;ASYNC_LOGSTASH&quot;;</pre><pre>private final Logger LOG = LoggerFactory.getLogger(LoggingConfiguration.class);</pre><pre>private final LoggerContext CONTEXT = (LoggerContext) LoggerFactory.getILoggerFactory();</pre><pre>private final String appName;</pre><pre>private final String logstashHost;</pre><pre>private final Integer logstashPort;</pre><pre>private final Integer logstashQueueSize;</pre><pre>public LogbackConfiguration(</pre><pre>@Value(&quot;${spring.application.name}&quot;) String appName,</pre><pre>@Value(&quot;${logstash.host}&quot;) String logstashHost,</pre><pre>@Value(&quot;${logstash.port}&quot;) Integer logstashPort,</pre><pre>@Value(&quot;${logstash.queue-size}&quot;) Integer logstashQueueSize) {</pre><pre>this.appName = appName; </pre><pre>this.logstashHost = logstashHost; </pre><pre>this.logstashPort = logstashPort; </pre><pre>this.logstashQueueSize = logstashQueueSize; </pre><pre>addLogstashAppender(CONTEXT);</pre><pre>}</pre><pre>private void addLogstashAppender(LoggerContext context) {</pre><pre>LOG.info(&quot;Initializing Logstash logging&quot;);</pre><pre>LogstashTcpSocketAppender logstashAppender = new LogstashTcpSocketAppender(); </pre><pre>logstashAppender.setName(LOGSTASH_APPENDER_NAME);</pre><pre>logstashAppender.setContext(context);</pre><pre>String customFields = &quot;{\&quot;servicename\&quot;:\&quot;&quot; + this.appName + &quot;\&quot;}&quot;; &lt;3&gt;</pre><pre>// More documentation is available at: <a href="https://github.com/logstash/logstash-logback-encoder">https://github.com/logstash/logstash-logback-encoder</a></pre><pre>LogstashEncoder logstashEncoder = new LogstashEncoder();</pre><pre>// Set the Logstash appender config</pre><pre>logstashEncoder.setCustomFields(customFields);</pre><pre>logstashAppender.addDestinations( </pre><pre>new InetSocketAddress(this.logstashHost, this.logstashPort) </pre><pre>);</pre><pre>ShortenedThrowableConverter throwableConverter = new ShortenedThrowableConverter();</pre><pre>throwableConverter.setRootCauseFirst(true);</pre><pre>logstashEncoder.setThrowableConverter(throwableConverter);</pre><pre>logstashEncoder.setCustomFields(customFields);</pre><pre>logstashAppender.setEncoder(logstashEncoder);</pre><pre>logstashAppender.start();</pre><pre>// Wrap the appender in an Async appender for performance</pre><pre>AsyncAppender asyncLogstashAppender = new AsyncAppender();</pre><pre>asyncLogstashAppender.setContext(context); </pre><pre>asyncLogstashAppender.setName(ASYNC_LOGSTASH_APPENDER_NAME); </pre><pre>asyncLogstashAppender.setQueueSize(this.logstashQueueSize); </pre><pre>asyncLogstashAppender.addAppender(logstashAppender); </pre><pre>asyncLogstashAppender.start(); </pre><pre>context.getLogger(&quot;ROOT&quot;).addAppender(asyncLogstashAppender); </pre><pre>}</pre><pre>}</pre><p>And finally add these properties:</p><pre>logstash.host= localhost</pre><pre>logstash.port= 7000</pre><pre>logstash.queue-size= 512</pre><p>Now let’s run our microservices and go to kibana and start playing with our index.</p><p>In kibana , go to management and click on create index pattern:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*afmAGAR0GZTMKd3oJuZ4kw.png" /></figure><p>We will find the name of the index mentionned in the logstash config file.</p><p>Now go to the discover section and you will find the log flow generated by our microservices:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K_1O98EbanJgZNkw7NNjxQ.png" /></figure><p>Now you can play with kibana and generate cool dashbords depending on what you need.</p><p>The latest version of the project is available in the git repository.</p><p><a href="https://github.com/FirasMessaoudi/ecommerce">https://github.com/FirasMessaoudi/ecommerce</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1e51016210ba" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Spring Boot Microservices , Monitoring with prometheus and grafana and log aggregation…]]></title>
            <link>https://firas-messaoudi.medium.com/building-spring-boot-microservices-monitoring-with-prometheus-and-grafana-and-log-aggregation-5ed9ca7dda36?source=rss-15d89be443e9------2</link>
            <guid isPermaLink="false">https://medium.com/p/5ed9ca7dda36</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[grafana]]></category>
            <category><![CDATA[prometheus]]></category>
            <category><![CDATA[microservices]]></category>
            <dc:creator><![CDATA[Firas Messaoudi]]></dc:creator>
            <pubDate>Sat, 30 Jan 2021 10:17:12 GMT</pubDate>
            <atom:updated>2021-02-22T08:31:24.146Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building Spring Boot Microservices , Monitoring with prometheus and grafana and log aggregation using ELK stack: Part II</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/656/1*dzODOIDqXTsWauf5eM8Trw.gif" /></figure><p><a href="https://medium.com/nerd-for-tech/creating-spring-boot-microservices-monitoring-with-prometheus-and-grafana-and-log-aggregation-ba4f20496942">In the first part</a> we learned how to build spring boot microservices by creating 3 microservices (Product-Microservice, Order-Microservice, Client-Microservice).</p><p>As for now everything looks fine, but while working with such a complex architecture we need to keep an eye on our system in case of a any potential failure.</p><p>To do so , in this part we’re gonna see how to monitor,trace and observe the behaviour of our microservices using prometheus and grafana.</p><h4>What is prometheus ?</h4><p>Prometheus is an open source time-series database originally developed by SoundCloud. It comes with its proper query language PromQL and used for event monitoring and alerting.</p><h4>Adding Micrometer Prometheus Registry to Spring Boot microservice</h4><p>Spring boot uses <a href="https://micrometer.io/">Micrometer </a>an application metrics facade to integrate actuator metrics with external monitoring systems.</p><p>It supports several monitoring systems like SignalFx, Graphite, Wavefront, Prometheus …</p><p>To integrate actuator with Prometheus, you need to add the following dependencies to each of your microservices:</p><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>    &lt;artifactId&gt;spring-boot-starter-actuator&lt;/artifactId&gt;<br>&lt;/dependency&gt;<br>&lt;dependency&gt;<br>    &lt;groupId&gt;io.micrometer&lt;/groupId&gt;<br>    &lt;artifactId&gt;micrometer-registry-prometheus&lt;/artifactId&gt;<br>&lt;/dependency&gt;</pre><p>and the following properties:</p><pre>management.endpoint.metrics.enabled=<strong>true<br></strong>management.endpoints.web.exposure.include=*<br>management.endpoint.prometheus.enabled=<strong>true<br></strong>management.metrics.export.prometheus.enabled=<strong>true</strong></pre><p>Once you add the above dependency, Spring Boot will automatically configure a <a href="https://github.com/micrometer-metrics/micrometer/blob/master/implementations/micrometer-registry-prometheus/src/main/java/io/micrometer/prometheus/PrometheusMeterRegistry.java">PrometheusMeterRegistry</a> to collect and export metrics data in a format that can be scraped by a Prometheus server.</p><p>To explore prometheus endpoint go to <a href="http://localhost:9001/actuator">http://localhost:9001/actuator</a></p><p>we’re gonna work on the product micoroservice for example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/1*qr4TROccZI7vveAU_MtbIA.png" /><figcaption>actuator</figcaption></figure><p>as we can see , actuator exposes a lot of endpoints , we’re just gonna focus on prometheus endpoint.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/867/1*05g-cpHKtpYhsGOAu5VJ6A.png" /><figcaption>prometheus endpoint</figcaption></figure><h4>Downloading and installing prometheus</h4><p>Prometheus is available as a docker image and if you don’t have docker you can download it from here <a href="https://prometheus.io/download/">https://prometheus.io/download/</a>.</p><p>we’re not gonna work with docker because not everyone is familiar with it.</p><p>After installing prometheus(with or without docker) , we have to create prometheus.yml file to configure Prometheus to scrape metrics data from Spring Boot Actuator’s /prometheus endpoint.</p><p>The configuration should look like this :</p><pre>scrape_configs:<br>  - job_name: &#39;microservice-product&#39;<br>    scrape_interval: 2s<br>    metrics_path: &#39;/actuator/prometheus&#39; ##prometheus endpoint<br>    static_configs:<br>      - targets: [&#39;localhost:9001&#39;] ## host and port for your mis<br>  - job_name: &#39;microservice-order&#39;<br>    scrape_interval: 2s<br>    metrics_path: &#39;/actuator/prometheus&#39;<br>    static_configs:<br>      - targets: [&#39;localhost:9002&#39;]<br>  - job_name: &#39;microservice-client&#39;<br>    scrape_interval: 2s<br>    metrics_path: &#39;/actuator/prometheus&#39;<br>    static_configs:<br>      - targets: [&#39;localhost:8080&#39;]</pre><h4>Running prometheus</h4><p>Open your terminal on your prometheus folder and run the following command:&gt;</p><pre>prometheus.exe --config.file &lt;PATH TO YOUR PROMETHEUS.YML&gt;</pre><p>Navigate to <a href="http://localhost:9090/">http://localhost:9090</a> and explore prometheus.</p><p>Once all our microservices are up we should have something like that:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ueKkRSkPR8FQyIIGjQskSQ.png" /><figcaption>targets</figcaption></figure><p>We can now explore all the metrics in prometheus and keep an eye on the behaviour of our microservices , this example shows the system’s CPU usage of our microservices:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f5K3GLFXYTO7SVgQRVnM0A.png" /></figure><h3>Grafana</h3><p>So far our microservices are exposing the actautor’s endpoint into prometheus server which is so interesting , but when we have this amount of information we need another system to help us better visualize , analyse our microservices.</p><p>Grafana is open source visualization and analytics software. It allows you to query, visualize, alert on, and explore your metrics no matter where they are stored. In plain English, it provides you with tools to turn your time-series database (prometheus for example )data into beautiful graphs and visualizations.</p><h4>Downloading and installing grafana</h4><p>You can download grafana from here <a href="https://grafana.com/grafana/download">https://grafana.com/grafana/download</a> then go to bin under grafana and execute the grafana-server.exe</p><p>Grafana run by default on port 3000, navigate to <a href="http://localhost:3000/">http://localhost:3000</a> and log in to Grafana with the default username admin and password admin.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YiW1qAqU2BV4jHYCMHYHTw.png" /><figcaption>grafana</figcaption></figure><h4>Configuring Grafana to import metrics data from Prometheus</h4><p>Like we said before grafana imports metrics from time series database in order to visualize them , to do so we need to configure grafana to import these metrcis from the prometheus server.</p><p>the following image shows how grafana and prometheus interact with each other:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/819/1*pfHETCjMOrNdGL0UPGC_Og.png" /><figcaption>architecture</figcaption></figure><p>To import prometheus metrcis into grafana we have to follow these steps:</p><h4>1. Add the Prometheus data source in Grafana</h4><p>go to configuration/datasource and click to add new datasource</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*58aQTWztQyMGfaIt5r8T8A.png" /></figure><p>Grafana provides a lot of databases , we just need to select prometheus</p><p>After selecting your TSDB , add the following configuration to connect garafana with your prometheus server :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DMEqPAKL7JZ7wukRlsCHTw.png" /></figure><h4>2.Create a new dashboard</h4><p>Select the (+) icon form the left menu and click dashboard:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rxjCAaV2H_Swn6nhlpQeVg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JfZ2ix8BQr4l8jG3yZzcnw.png" /></figure><h4>3.Visualize your dashboard</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/877/1*IOw6nT8uTL_Hlafa0OnU6Q.png" /></figure><h4>Importing pre-built dashboards</h4><p>Grafana.com maintains <a href="https://grafana.com/dashboards">a collection of shared dashboards</a> which can be downloaded and used with standalone instances of Grafana. Use the Grafana.com “Filter” option to browse dashboards for the “Prometheus” data source only.</p><p>we’re gonna search for the spring boot statistics dashboard for example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wwYpgm8jrrdmJEBOeafC2g.png" /></figure><p>copy the id and go to dashboard/import and click load</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zf-cs1znXWKNnA-hwynK5w.png" /></figure><p>Your dashboard is ready to explore. Now it’s up to you andr needs , you can do whatever you want and you can keep and eye on your whole system.<br>In the next and final part we’re gonna see how to aggregate the microservices logs with Elastic stack.</p><p>You can find the update source code on the git repository:</p><p><a href="https://github.com/FirasMessaoudi/ecommerce">FirasMessaoudi/ecommerce</a></p><p>I’ll notify you in the comments when the final part is ready.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5ed9ca7dda36" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating Spring Boot Microservices , Monitoring with prometheus and grafana and log aggregation…]]></title>
            <link>https://firas-messaoudi.medium.com/creating-spring-boot-microservices-monitoring-with-prometheus-and-grafana-and-log-aggregation-ba4f20496942?source=rss-15d89be443e9------2</link>
            <guid isPermaLink="false">https://medium.com/p/ba4f20496942</guid>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[eureka]]></category>
            <category><![CDATA[zuul]]></category>
            <category><![CDATA[spring-cloud]]></category>
            <dc:creator><![CDATA[Firas Messaoudi]]></dc:creator>
            <pubDate>Fri, 15 Jan 2021 18:00:34 GMT</pubDate>
            <atom:updated>2021-02-22T08:31:51.420Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building Spring Boot Microservices , Monitoring with prometheus and grafana and log aggregation using ELK stack: Part I</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/987/1*BicliTTLme6W9DBVjj8CjA.png" /></figure><p><strong>Introduction</strong></p><p>while developing a number of complex applications (E-commerce,streaming video, banking…), most developers are facing a lot of challenges such as:</p><p><strong>-Availabilty:</strong> How can we make sure our application will always be available regardless of the behaviour of the users?</p><p><strong>-Maintainability: </strong>Our application must evolve frequently and respond to quickly to new features without shutting down the whole application.</p><p><strong>-Evolution:</strong> Technology used to develop the application evovle every day , so we must make sure our application has the ability to adapt to this evolution</p><p>And of course a lot of other problems and challenges that we are going to face.</p><p>During the first part of this post we are going to find out how the microservice architecture came to solve this issues and satisfy the challenges.</p><h3><strong>What is the microservice architecture ?</strong></h3><p>The Microservices architecture offers a simple solution: split the application into small services , called Microservices, which are <strong>perfectly autonomous,</strong> and expose a <em>REST</em> API that other Microservices can consume.</p><p>The figure below represents a simplified overview of the microservice architecture:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*RIQEqTXOBs91fQM_qXiauw.png" /><figcaption>Global architecture</figcaption></figure><h3>How does the microservice architecture responds to the above issues ?</h3><p>As we can see in the previous image, each microservice is perfectly autonomous and can be deployed on various servers and different instances which make our microservices available and scalable. In that case the microservice responsible of the UI will call one of the instances and receive the same response regardless of the instance chosen.</p><p>We don’t have to worry about the maintainability anymore , each microservice works independently from the others , so whenever we want to work on a microservice we don’t have to stop the whole application (the case of the monolothic application) we just have to access the microservice in question.</p><p>And due to the various technology offered, each microservice can use a different technology ,microservice A can be in java , microservice B can be in php … the main thing is that each one exposes a rest API. This advantage will give us the ability to take care about the business logic of the application without worrying about the technology.</p><p>After we took a quick look about the microservice architecture and its benefits we are going to put all this in practice in order to cover most of the topics.</p><p>We are going to use the famous<strong> Spring boot framework </strong>to create s simple e-commerce application with three microservices (ProductMicroservice ,OrderMicroservice and clientMicroservices).</p><h3><strong>Creating the microservices</strong></h3><p>The first step consists of creating three spring initializer projects which will represents our microservices.</p><p>These projects will have one class each (Product, order and Client ) and these dependencies for now :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1005/1*7tYxeGMFxUtojklL_jFpFA.png" /><figcaption>Dependencies</figcaption></figure><p>The product Microservice will have two simple operations: find a product by id and get all the product.</p><p>The order microservice: Add a new order and find and order by its id.</p><p>The client will consume the microservices.</p><p>After creating the microservices and their methods we have to see this tree of packages in each microservice:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*Gv4sEzv1ATv2NOlbd0Gzsg.png" /><figcaption>Package</figcaption></figure><p>Don’t worry about the source code you will find the link to the whole code at the end of this course, now we just have to understand each step.</p><p>For now we have two spring boot application running independently, everything is familiar so far.</p><h3>Eureka Server</h3><p>As we said, for now everything is so familiar, each microservice with its instances is running independently. But we need something to register all this instances.</p><p>Eureka service owned by Netflix respond to this need, eureka will register every microservice.</p><p>Each microservice registered in eureka server is called eureka client.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/515/1*fRhh9GzAD404swvSBbtwZA.png" /><figcaption>Eureka</figcaption></figure><p>The figure above how our microservices interact with eureka server.</p><p>To set up Eureka server we need to create an eureka microservice and add its configuration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*4pyJ7s9VO6cupQS0u55yZA.png" /><figcaption>Eureka service</figcaption></figure><p>After adding the dependencies go to application.properties and add this configurations</p><pre>server.port:9102<br><br>spring.application.name=eureka-server<br><br>eureka.client.serviceUrl.defaultZone:http://localhost:9102/eureka/<br><br>eureka.client.registerWithEureka:false</pre><pre>#set to false because we&#39;re not in cluster mode<br>eureka.client.fetchRegistry:false<br>#set to false because we&#39;re not in cluster mode</pre><p>Enable Eureka server:</p><pre>@SpringBootApplication<br>@EnableEurekaServer<br>public class EurekaServerApplication {<br>   public static void main(String[] args) {<br><br>      SpringApplication.run(EurekaServerApplication.class, args);<br><br>   }<br><br>}</pre><p>Then go to http: // localhost: 9102 /. You will then arrive on a page which presents a certain amount of information about your Eureka server.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/609/1*aLOC3QC2hkTQ93knDLK_PA.png" /></figure><p>This is where you will see the list of Microservices instances that will register.</p><h3>Eureka Client</h3><p>In order for the different Microservices to start registering in our Eureka server, we need to add the Eureka client to each of them.</p><p>Go to pom.xml and add this dependency:</p><pre><strong>&lt;dependency&gt;</strong></pre><pre><strong>&lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;</strong></pre><pre><strong>&lt;artifactId&gt;spring-cloud-starter-netflix-eureka-server&lt;/artifactId&gt;</strong></pre><pre><strong>&lt;/dependency&gt;</strong></pre><p>Then to the application.properties :</p><pre><strong>eureka.client.serviceUrl.defaultZone: </strong><a href="http://localhost:9102/eureka/"><strong>http://localhost:9102/eureka/</strong></a></pre><p>This line indicates the URL of Eureka to which to register.</p><p>Finally go to each microservice and the annotation @EnableDiscoveryClient:</p><pre>@SpringBootApplication<br><br>@EnableDiscoveryClient<br><br>public class ProductApplication {<br><br>    public static void main(String[] args) {<br><br>        SpringApplication.<em>run</em>(ProductApplication.class, args);<br><br>    }<br><br><br><br>}</pre><p>Your Microservice now benefits from the Eureka client, which will register your instance on each startup.</p><p>Start your service and go to http: // localhost: 9102</p><h3><strong>Communicate your microservices with Feign</strong></h3><p>For now the two microservices Product and Order and a client that are running independently and registered on Eureka. But what if we need one of them to communicate with the other. That’s why we will need a service or protocol to assure that.</p><p><strong>Feign</strong> is an HTTP client that greatly facilitates the call of APIs exposed by the different Microservices. It is therefore capable of creating and executing HTTP requests based on the annotations and information provided</p><p>In our case we will need the client microservice to communicate with the product and order microservices.</p><p>Let’s start by adding Feign to our <em>pom.xml </em>in the client Microservice</p><pre>&lt;dependency&gt;</pre><pre>&lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;</pre><pre>&lt;artifactId&gt;spring-cloud-starter-openfeign&lt;/artifactId&gt;</pre><pre>&lt;/dependency&gt;</pre><p>In order to activate Feign in this Microservice, go to <em>ClientUiApplication</em> and add the <strong><em>@EnableFeignClients</em></strong> annotation <strong><em>:</em></strong></p><pre>@SpringBootApplication</pre><pre>@EnableFeignClients(&quot;com.ecommerce.clientui&quot;)</pre><pre>public class ClientUiApplication {</pre><pre>public static void main(String[] args) {</pre><pre>SpringApplication.run(ClientUiApplication.class, args);</pre><pre>}</pre><pre>}</pre><p>The annotation @EnableFeignClients asks Feign to scan the <em>&quot;com.</em> ecommerce<em> .clientui&quot;</em> package to find classes that declare themselves Feign clients.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/741/1*kIaxLBrsqZqNVsECTuwWuw.png" /><figcaption>FeignClient</figcaption></figure><p>While the client mis will use feign to retrieve the list of product , we will have to create a Product class in the client mis similar to the one on the product microservice in order to store the objects:</p><p>We are going to create a class product under the package DTO.</p><pre>@Data<br>public class ProductDTO {<br><br>    private int id;<br><br>    private String titre;<br><br>    private String description;<br><br>    private String image;<br><br>    private Double prix;<br>}</pre><p>We are now going to create an <strong>interface which will group together the requests</strong> that we want to pass to the ProductMicroservice<em>. </em>This interface is what we call a <strong>proxy, </strong>because it is positioned as an intermediate class which makes the link with the external Microservices to be called.</p><pre>@FeignClient(name = &quot;microservice-product&quot;, url = &quot;localhost:9001&quot;)<br>public interface ProductMicroserviceProxy{<br><br>    @GetMapping(value = &quot;/Products&quot;)<br>    List&lt;ProductDTO&gt; findAll();<br><br>    @GetMapping( value = &quot;/products/{id}&quot;)<br>    ProductDTO findById(@PathVariable(&quot;id&quot;) int id);<br><br><br>}</pre><p>-Feign will use the information provided to make the appropriate HTTP requests to invoke the ProductMicroservice<em>.</em></p><p><em>-</em>The first param is the name of the microservice which will be called. This name is already set in the application.properties</p><p>- The second parameter is the URL of the Microservice (localhost: 9001)</p><p>All that remains is to use this proxy. Go back to the controller:</p><pre>@RestController<br>@CrossOrigin(&quot;*&quot;)<br>@RequestMapping(&quot;/client&quot;)<br>public class ClientController {<br><br>    @Autowired<br>    private ProductMicroserviceProxy ProductProxy;<br><br>   <br>    @GetMapping(&quot;/products&quot;)<br>    public List&lt;ProductDTO&gt; findAll(){<br><br>        List&lt;ProductDTO&gt; list=  ProducstsProxy.findAll();<br>        return LIST;<br><br>    }<br><br>   <br>    @GetMapping(&quot;/findById/{id}&quot;)<br>    public ProductDTO findByd(@PathVariable int id){<br><br>        ProductBean prod = ProductsProxy.findById(id);<br><br>        return prod;<br>    }</pre><p>Let’s do a quick resume , so far we managed to create 3 microservices (Product, Order and client ) each is registered on Eureka Server and communicating with FeignClient.</p><p>We achieved a great step for now but as we can see , we’re still missing some pieces.</p><h3><strong>ZULL API gateway</strong></h3><p>ZUUL is going to be a unique entry point for our application. So when Client microservice for example, wants to call one of the Microservices, it will go through <strong>ZUUL</strong> . which will take care of dispatching, modifying and applying filters and rules to these requests.</p><p>ZUUL works natively with Eureka. It retrieves the list of all Microservices available in Eureka and exposes them via the URL: localhost: 9004 / microservice-name .</p><p>Thus, to retrieve the list of products, just call: localhost: 9004 / microservice-products/ Products .</p><p>You then retrieve the list of products as if you had called Microservice-products directly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/704/1*WFW6okrMvd4UG5XiDXLZcg.png" /><figcaption>Zuul</figcaption></figure><p>We have to create another microservice (Zuul) and register it in eureka.</p><p>Add the following properties to zuul microservice properties</p><pre>server.port 9004<br>#Eureka<br>eureka.client.serviceUrl.defaultZone:http://localhost:9102/eureka/</pre><p>And activate Eureka and Zuul</p><pre>@SpringBootApplication<br>@EnableZuulProxy<br>@EnableDiscoveryClient<br>public class ZuulServerApplication {<br><br>   public static void main(String[] args) {<br>      SpringApplication.run(ZuulServerApplication.class, args);<br>   }<br>}</pre><p>Start zuul and verify Eureka you’ll find the zuul microservice among the other microservices.</p><p>In order for our client to go through ZUUL, we need to tell the Feign proxies to contact ZUUL and not the Microservices directly.</p><p>Then replace the name of the destination Microservice with that of ZUUL</p><p>We add <em>/ </em>microservice-products<em> / in</em> front of all URIs. Feign will then contact ZUUL with the URI “/ microservice-products / Products”. As ZUUL then extracts the name of the Microservice concerned from the “microservice-products” URL, it can redirect the request to the desired destination.</p><pre>@FeignClient(name = &quot;zuul-server&quot;)<br>public interface ProductMicroserviceProxy{<br><br>    @GetMapping(value = &quot;microservice-product/Products&quot;)<br>    List&lt;ProductDTO&gt; findAll();<br><br>    @GetMapping( value = &quot;microservice-product/products/{id}&quot;)<br>    ProductDTO findById(@PathVariable(&quot;id&quot;) int id);<br><br><br>}</pre><h3>Conclusion</h3><p>The first part of this post has already covered how we create a microservice , register it in Eureka , communicate with other microservice and how to create an API gateway.</p><p>In the <a href="https://firas-messaoudi.medium.com/building-spring-boot-microservices-monitoring-with-prometheus-and-grafana-and-log-aggregation-5ed9ca7dda36">next part</a> we will discover how we can monitor our microservices with Prometheus and Grafana.</p><p>As promissed this is the link to the github repository for this part</p><p><a href="https://github.com/FirasMessaoudi/ecommerce">FirasMessaoudi/ecommerce</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ba4f20496942" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring boot external configuration with spring cloud config and spring actuator]]></title>
            <link>https://firas-messaoudi.medium.com/spring-boot-external-configuration-with-spring-cloud-config-and-spring-actuator-60603f2ff23f?source=rss-15d89be443e9------2</link>
            <guid isPermaLink="false">https://medium.com/p/60603f2ff23f</guid>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[spring-actuator]]></category>
            <category><![CDATA[spring-cloud-config]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Firas Messaoudi]]></dc:creator>
            <pubDate>Mon, 06 Jul 2020 11:05:36 GMT</pubDate>
            <atom:updated>2021-01-21T16:02:13.261Z</atom:updated>
            <content:encoded><![CDATA[<p>While developing a spring boot application , most developers have to define some fixed properties in their application.properties like the secret key for the token , the session timeout, the path of uploaded files and a lot of other properties.</p><p>The problem with this approch is that these properties are loaded only once when the server starts. So what’s gonna happen when we want to change some properties while the app is in prod. In this cas we have to shut down the server , change the properties and restart the server.</p><p>Even worse , what if we’re working multiple microservices , it would be a disaster if we shut down all microservices.</p><h3>Solution?</h3><p>To avoid these complications we have to externalize our config files in a distance github repository and access these files using s<strong>pring cloud config </strong>which represtents a distributed file server as described below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/795/1*KJZEN-WOvn2GzOXZMZj1dw.png" /><figcaption>Externalization</figcaption></figure><h3>1-Create a git repository</h3><p>As a first a step we have to create a git repository where we will store the configuartions of our application or microservices and name it for example“configuration-server-repo”.</p><p>In this repo we create a propertie file and name it with the exact name defined in the propertie : spring.application.name of the app , because that’s how our config server will link the application with it’s distant configuration.</p><p>For example we have an ecommerce application, in its application.properties file we add this line:</p><pre><strong>spring.application.name</strong>=<strong>ecommerce-application</strong></pre><p>And the application.propeties file in the git repo will have the same name: <strong>ecommerce-application.properties</strong></p><p>Now we move all the properties of the app (except the propertie spring.application.name )into the <strong>ecommerce-application.properties </strong>file in the git repo and commit the changes.</p><p>Our git repo will look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/985/1*-HPMVWm5k4JnQyyR-6aYHg.png" /><figcaption>Git repo</figcaption></figure><h3>2-Create the config server application</h3><p>Now go to spring initializr or from any IDE and create a new spring boot application with spring cloud config as starter</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Kh9N6nqrsdqsVD9jrU4KJQ.png" /><figcaption>config-server</figcaption></figure><p>Open the project with your IDE and go to application.properties and put the following properties:</p><pre><strong>spring.application.name</strong>=<strong>config-server<br>server.port</strong>:<strong>9101 #config server port <br>spring.cloud.config.server.git.uri</strong>=<a href="https://github.com/FirasMessaoudi/configuration-server-repo">https://github.com/FirasMessaoudi/configuration-server-repo</a>.git #url of the git repo containing the propertie file of the application.</pre><p>We have now to define the app as a config server by adding the annotation @EnableConfigServer</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/778/1*NxTQcxSNQ0JYnyQB1E7lEw.png" /><figcaption>ConfigServerApplication</figcaption></figure><p>Start the server and navigate to <a href="http://localhost:9100/microservice-produits/default">http://localhost:9101/ecommerce-application/default</a>. You will see your application.properties retrieved from the git repo:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/992/1*dEkvUsKUkTWoouux0g_Teg.png" /></figure><h3>3-Linking ecommerce application with the server config</h3><p>As for now we have a distant repo linked to the server config, we must now tell the ecommerce application to get its configurations from the config server.</p><p>Update the pom.xml with the following dependency:</p><pre>&lt;dependency&gt;<br>     &lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;<br>     &lt;artifactId&gt;spring-cloud-starter-config&lt;/artifactId&gt;<br>&lt;/dependency&gt;</pre><p>Go to the application.properties of the ecommerce application which only has the propretie “spring.application.name” and add the following propertie:</p><pre><strong>spring.cloud.config.uri</strong>=<strong>http://localhost:9101</strong></pre><p>Start the ecommerce application and you should see this log in the console :</p><pre>Fetching config from server at: <a href="http://localhost:9101/">http://localhost:9101</a></pre><p>Which means that the ecommerce application is now fetching its configuration from the config server.</p><h3>4-Refresh configuartions</h3><p>We have one last problem to solve: if you try to change the property upload.path and upload a new image from your application , you will notice that the path didn’t change. So do we still have to restart the config server ?</p><p>Not if we use spring Actuator which provides an endpoint to our application to refresh the configuration without restarting the app nor the the config server.</p><p>Go to pom.xml in the ecommerce application and the following starter:</p><pre>&lt;dependency&gt;<br>        &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>        &lt;artifactId&gt;spring-boot-starter-actuator&lt;/artifactId&gt;<br>&lt;/dependency&gt;</pre><p>And add the following propertie ( in the propertie file in the app or in the distant repo):</p><pre>management.endpoints.web.exposure.include=*</pre><p>Finally we have to inform all the beans consuming any of the properties to get refreshed each time we make a change, by adding the following annotation:</p><pre>@RefreshScope</pre><p>Restart the ecommerce application , change your upload.path propertie from the git , commit the changes and trigger the resfresh event by making a post request:</p><p><a href="http://localhost:9001/actuator/refresh">http://localhost:8080/actuator/refresh</a>.</p><p>Now go back and upload another image , and you’ll see the new path being considered by your application.</p><h3>Final result</h3><p>So now we have our ecommerce application fetching its config from a distant git repo through the config-server. And we can change our configurations with no need to restart the application nor the config server.</p><p>Enjoy reading and clap if you like this article.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=60603f2ff23f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Boot authentication with Angular 8 using Ngxs+ JWT+Http Only Cookie+Spring Session JDBC]]></title>
            <link>https://medium.com/swlh/spring-boot-authentication-with-angular-8-using-ngxs-jwt-http-only-cookie-spring-session-jdbc-a28481a8b833?source=rss-15d89be443e9------2</link>
            <guid isPermaLink="false">https://medium.com/p/a28481a8b833</guid>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[jwt-token]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[spring-security]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Firas Messaoudi]]></dc:creator>
            <pubDate>Tue, 07 Apr 2020 12:54:17 GMT</pubDate>
            <atom:updated>2020-04-07T18:14:00.316Z</atom:updated>
            <content:encoded><![CDATA[<h3>Spring Boot authentication with Angular 8 using NGXS+ JWT+Http Only Cookie+Spring Session JDBC</h3><p>Whenever we talk about web development, our biggest concern goes to the security of our application.How can we protect our resources ?and how can we protect the users informations ?.<br>In this article we are going to implement a web application using spring boot as a back end framework and angular as a front end.<br>We are going to use spring security with jwt and http only cookies.<br>A good pratice is to use two tokens : access token(short duration) and refresh token(long duration) , if the client has an invalid access token and a valid refresh token the acces token will be re-created.<br>Also, we are not going to store our tokens in local storage beacause it’s vulnerable to XSS attacks and can be easily stolen , instead we will store them encrypted in http only cookies,<br>these cookies are set in the api server and sent in the http header with each request. And that way our tokens will be safe.<br>this schema will give us a glimps of how this will work:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/762/1*6v5zghajmOFticf4REN91Q.png" /></figure><p>One more thing , we will have one session for each user , so that the same user can’t log in from different browsers.</p><p>Now let’s take a look at our pom.xml and see what dependencies we need:</p><pre>&lt;dependencies&gt;<br> &lt;dependency&gt;<br> &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br> &lt;artifactId&gt;spring-boot-starter-data-jpa&lt;/artifactId&gt;<br> &lt;/dependency&gt;<br> &lt;dependency&gt;<br> &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; <br>&lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt; <br>&lt;/dependency&gt;<br> &lt;dependency&gt; <br>&lt;groupId&gt;org.postgresql&lt;/groupId&gt; &lt;artifactId&gt;postgresql&lt;/artifactId&gt;<br> &lt;scope&gt;runtime&lt;/scope&gt; <br>&lt;/dependency&gt; <br>&lt;dependency&gt; <br>&lt;groupId&gt;org.projectlombok&lt;/groupId&gt;<br> &lt;artifactId&gt;lombok&lt;/artifactId&gt; <br>&lt;optional&gt;true&lt;/optional&gt;<br> &lt;/dependency&gt;<br> &lt;dependency&gt;<br> &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br> &lt;artifactId&gt;spring-boot-starter-test&lt;/artifactId&gt; &lt;scope&gt;test&lt;/scope&gt;<br> &lt;/dependency&gt;<br> &lt;dependency&gt; <br>&lt;! - Automated JSON API documentation for API&#39;s built with Spring → &lt;groupId&gt;io.springfox&lt;/groupId&gt; <br>&lt;artifactId&gt;springfox-swagger2&lt;/artifactId&gt; &lt;version&gt;2.8.0&lt;/version&gt; &lt;/dependency&gt;<br> &lt;dependency&gt; <br>&lt;groupId&gt;io.springfox&lt;/groupId&gt; <br>&lt;artifactId&gt;springfox-swagger-ui&lt;/artifactId&gt; &lt;version&gt;2.8.0&lt;/version&gt; <br>&lt;/dependency&gt;<br>&lt;! - security → &lt;dependency&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br> &lt;artifactId&gt;spring-boot-starter-security&lt;/artifactId&gt;<br> &lt;/dependency&gt;<br>&lt;dependency&gt; <br>&lt;groupId&gt;io.jsonwebtoken&lt;/groupId&gt;<br> &lt;artifactId&gt;jjwt&lt;/artifactId&gt;<br> &lt;version&gt;0.7.0&lt;/version&gt;<br> &lt;/dependency&gt; <br>&lt;dependency&gt;<br> &lt;groupId&gt;org.springframework.session&lt;/groupId&gt; <br>&lt;artifactId&gt;spring-session-jdbc&lt;/artifactId&gt; <br>&lt;/dependency&gt;<br> &lt;dependency&gt;<br> &lt;groupId&gt;org.springframework.session&lt;/groupId&gt;<br> &lt;artifactId&gt;spring-session-core&lt;/artifactId&gt; <br>&lt;/dependency&gt;<br> &lt;/dependencies&gt;</pre><p>application.properties : where we will keep token and session configurations:</p><pre>spring.jpa.hibernate.ddl-auto = create-drop<br>spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect<br>spring.jackson.serialization.fail-on-empty-beans=false<br>server.port=8080<br>spring.main.allow-bean-definition-overriding=true<br>spring.datasource.url= jdbc:postgresql://localhost:5432/dbtest<br>spring.datasource.username=postgres<br>spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true<br>authentication-test.auth.accessTokenCookieName=AuthToken<br>authentication-test.auth.refreshTokenCookieName=RefreshToken<br>sessionTimePki.app.jwtExpiration=5400000 <br>#authentication-test.auth.refreshTokenExpirationMsec=7776000000<br>authentication-test.auth.refreshTokenExpirationMsec=10800000 <br>app.jwtSecret=jwtAliSecretKey<br>#always<br>spring.session.jdbc.initialize-schema=always<br>spring.session.store-type=jdbc<br>spring.session.jdbc.schema=classpath:org/springframework/session/jdbc/schema-@@platform@@.sql<br>spring.session.jdbc.table-name=SPRING_SESSION<br>server.servlet.session.cookie.http-only=true<br>server.servlet.session.timeout=20m</pre><p>SecurityConfig.java , We will keep the spring boot standard configuration and we will add the specific configuration for our session management:</p><pre><a href="http://twitter.com/Override">@Override</a><br>    protected void configure(HttpSecurity http) throws Exception {<br>        http.cors().and().csrf().disable().exceptionHandling().and().authorizeRequests()<br>                .antMatchers(&quot;/auth/**&quot;).permitAll()<br>                .anyRequest().authenticated().and()<br>                .formLogin().disable().httpBasic().disable()<br>                .sessionManagement()<br>                .sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)<br>                .maximumSessions(1)<br>                .maxSessionsPreventsLogin(true)<br>                .sessionRegistry(sessionRegistry()).and()<br>                .sessionFixation().migrateSession();<br>    <br>         <br>        http.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);</pre><pre>}</pre><pre><a href="http://twitter.com/Bean">@Bean</a><br>    public SessionRegistry sessionRegistry() {<br>        SessionRegistry sessionRegistry = new SessionRegistryImpl();<br>        return sessionRegistry;<br>    }</pre><pre><a href="http://twitter.com/Bean">@Bean</a><br>    public HttpSessionEventPublisher httpSessionEventPublisher() {<br>        return new HttpSessionEventPublisher();<br>    }</pre><p>JwtAuthenticationFilter: Interception the request and and check if there is a valid token in the cookie:</p><pre><a href="http://twitter.com/Override">@Override</a><br>        protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {<br>            try {<br>                String jwt = getJwtToken(httpServletRequest, true);<br>                if (StringUtils.hasText(jwt) &amp;&amp; jwtTokenUtil.validateToken(jwt)) {<br>                    String username = jwtTokenUtil.getUsername(jwt);<br>                    UserDetails userDetails = jwtUserDetailsService.loadUserByUsername(username);<br>                    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());<br>                    authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(httpServletRequest));<br>                    SecurityContextHolder.getContext().setAuthentication(authentication);<br>                }<br>                else if(!jwtTokenUtil.validateToken(jwt)){<br>                    httpServletResponse.addHeader(&quot;Message&quot;,&quot;Invalid Token&quot;);<br>                }<br>            } catch (Exception ex) {<br>                ex.printStackTrace();<br>            }</pre><pre>filterChain.doFilter(httpServletRequest, httpServletResponse);<br>        }</pre><pre>private String getJwtFromRequest(HttpServletRequest request) {<br>        String bearerToken = request.getHeader(&quot;Authorization&quot;);<br>        if (StringUtils.hasText(bearerToken) &amp;&amp; bearerToken.startsWith(&quot;Bearer &quot;)) {<br>            String accessToken = bearerToken.substring(7);<br>            if (accessToken == null) return null;</pre><pre>return SecurityCipher.decrypt(accessToken);<br>        }<br>        return null;<br>    }<br>    <br>      private String getJwtFromCookie(HttpServletRequest request) {<br>            Cookie[] cookies = request.getCookies();<br>            if(cookies==null)<br>                return &quot;&quot;;<br>            for (Cookie cookie : cookies) {<br>                if (accessTokenCookieName.equals(cookie.getName())) {<br>                    String accessToken = cookie.getValue();<br>                    if (accessToken == null) return null;</pre><pre>return SecurityCipher.decrypt(accessToken);<br>                }<br>            }<br>            return null;<br>        }<br>      <br>       private String getJwtToken(HttpServletRequest request, boolean fromCookie) {<br>            if (fromCookie) return getJwtFromCookie(request);</pre><pre>return getJwtFromRequest(request);<br>        }</pre><p>JwtTokenProvider: this is where we are going to create our tokens</p><pre>public boolean validateToken(String token) {<br>        try {<br>            Jwts.parser().setSigningKey(jwtSecret).parseClaimsJws(token);<br>            return true;<br>        } catch (SignatureException ex) {<br>            System.out.println(&quot;Invalid JWT Signature&quot;);<br>        } catch (MalformedJwtException ex) {<br>            System.out.println(&quot;Invalid JWT token&quot;);<br>        } catch (ExpiredJwtException ex) {<br>            System.out.println(&quot;Expired JWT token&quot;);<br>        } catch (UnsupportedJwtException ex) {<br>            System.out.println(&quot;Unsupported JWT exception&quot;);<br>        } catch (IllegalArgumentException ex) {<br>            System.out.println(&quot;Jwt claims string is empty&quot;);<br>        }<br>        return false;<br>    }</pre><pre>public Token generateToken(User user ) {</pre><pre>Claims claims = Jwts.claims().setSubject(user.getUsername());</pre><pre>claims.put(&quot;auth&quot;, user.getRoles().stream().map(s -&gt; new SimpleGrantedAuthority(s.getAuthority())).filter(Objects::nonNull).collect(Collectors.toList()));</pre><pre>Date now = new Date();<br>        Long duration = now.getTime() + jwtExpirationInMs;<br>         Date expiryDate = new Date(now.getTime() + jwtExpirationInMs);<br>        Calendar calendar = Calendar.getInstance();<br>        calendar.setTime(now);<br>        calendar.add(Calendar.HOUR_OF_DAY, 8);</pre><pre>String token = Jwts.builder().setClaims(claims).setSubject((user.getUsername())).setIssuedAt(new Date())<br>                .setExpiration(expiryDate).signWith(SignatureAlgorithm.HS256, jwtSecret).compact();<br>        <br>        return new Token(Token.TokenType.ACCESS, token, duration, LocalDateTime.ofInstant(expiryDate.toInstant(), ZoneId.systemDefault()));</pre><pre>}</pre><pre>public Token generateRefreshToken(User user) {</pre><pre>Claims claims = Jwts.claims().setSubject(user.getUsername());</pre><pre>claims.put(&quot;auth&quot;, user.getRoles().stream().map(s -&gt; new SimpleGrantedAuthority(s.getAuthority())).filter(Objects::nonNull).collect(Collectors.toList()));<br>        Date now = new Date();<br>            Long duration = now.getTime() + refreshTokenExpirationMsec;<br>             Date expiryDate = new Date(now.getTime() + refreshTokenExpirationMsec);<br>            Calendar calendar = Calendar.getInstance();<br>            calendar.setTime(now);<br>            calendar.add(Calendar.HOUR_OF_DAY, 8);<br>            String token = Jwts.builder().setClaims(claims).setSubject((user.getUsername())).setIssuedAt(new Date())<br>                    .setExpiration(expiryDate).signWith(SignatureAlgorithm.HS256, jwtSecret).compact();<br>            <br>            return new Token(Token.TokenType.REFRESH, token, duration, LocalDateTime.ofInstant(expiryDate.toInstant(), ZoneId.systemDefault()));</pre><pre>}</pre><p>CookieUtil: create http cookies</p><pre>public HttpCookie createAccessTokenCookie(String token, Long duration) {<br>        String encryptedToken = SecurityCipher.encrypt(token);<br>        return ResponseCookie.from(accessTokenCookieName, encryptedToken)<br>                .maxAge(duration)<br>                .httpOnly(true)<br>                .path(&quot;/&quot;)<br>                .build();<br>    }</pre><pre>public HttpCookie createRefreshTokenCookie(String token, Long duration) {<br>        String encryptedToken = SecurityCipher.encrypt(token);<br>        return ResponseCookie.from(refreshTokenCookieName, encryptedToken)<br>                .maxAge(duration)<br>                .httpOnly(true)<br>                .path(&quot;/&quot;)<br>                .build();<br>    }</pre><p>AuthController: controller for authentification , refresh and logout</p><pre><a href="http://twitter.com/RestController">@RestController</a><br><a href="http://twitter.com/RequestMapping">@RequestMapping</a>(&quot;/auth&quot;)<br>public class AuthController {<br>    <a href="http://twitter.com/Autowired">@Autowired</a><br>    private AuthenticationManager authenticationManager;<br>    <a href="http://twitter.com/Autowired">@Autowired</a><br>    private UserService userService;<br>    <a href="http://twitter.com/Autowired">@Autowired</a><br>    FindByIndexNameSessionRepository sessionRepository;<br>    <a href="http://twitter.com/PostMapping">@PostMapping</a>(value = &quot;/login&quot;, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)<br>    public ResponseEntity&lt;LoginResponse&gt; login(<br>            <a href="http://twitter.com/CookieValue">@CookieValue</a>(name = &quot;accessToken&quot;, required = false) String accessToken,<br>            <a href="http://twitter.com/CookieValue">@CookieValue</a>(name = &quot;refreshToken&quot;, required = false) String refreshToken,<br>            <a href="http://twitter.com/Valid">@Valid</a> <a href="http://twitter.com/RequestBody">@RequestBody</a> LoginRequest loginRequest<br>    ) {<br>        Authentication authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword()));<br>       if(isAlreadyLoggedIn(loginRequest.getUsername())){<br>           LoginResponse loginResponse = new LoginResponse();<br>           loginResponse.setError(&quot;User Already logged in&quot;);<br>           return ResponseEntity.ok(loginResponse);<br>       }<br>        SecurityContextHolder.getContext().setAuthentication(authentication);<br>        String decryptedAccessToken = SecurityCipher.decrypt(accessToken);<br>        String decryptedRefreshToken = SecurityCipher.decrypt(refreshToken);<br>        return userService.login(loginRequest, decryptedAccessToken, decryptedRefreshToken);<br>    }</pre><pre><a href="http://twitter.com/PostMapping">@PostMapping</a>(value = &quot;/refresh&quot;, produces = MediaType.APPLICATION_JSON_VALUE)<br>    public ResponseEntity&lt;LoginResponse&gt; refreshToken(<a href="http://twitter.com/CookieValue">@CookieValue</a>(name = &quot;accessToken&quot;, required = false) String accessToken,<br>                                                      <a href="http://twitter.com/CookieValue">@CookieValue</a>(name = &quot;refreshToken&quot;, required = false) String refreshToken) {<br>        String decryptedAccessToken = SecurityCipher.decrypt(accessToken);<br>        String decryptedRefreshToken = SecurityCipher.decrypt(refreshToken);<br>        return userService.refresh(decryptedAccessToken, decryptedRefreshToken);<br>    }<br>    <a href="http://twitter.com/GetMapping">@GetMapping</a>(&quot;/logout&quot;)<br>    public ResponseEntity&lt;String&gt; logOut(HttpServletRequest request, HttpServletResponse response){</pre><pre>return new ResponseEntity (new ApiResponseMessage(true, userService.logout(request, response)), HttpStatus.OK);</pre><pre>}<br>    private Boolean isAlreadyLoggedIn(String pricipalName) {</pre><pre>Map user = sessionRepository.findByIndexNameAndIndexValue(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME,pricipalName);<br>        return user.size()&gt;0;<br>    }<br>}</pre><p>Full structure of our backend:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/355/1*zfP-rzQfFenAQrUyN0_pEw.png" /><figcaption>Back end structure</figcaption></figure><p>Now as have finished the back end , let’s move to the client side , as we said before we are going to use angular , in this tutorial we are going to focus on the<br>intercetor beacuase it’s where most of the work will be done.<br>Like we said in the beginning we are not going to use local storage to store our tokens , so there is no way to decode the token from cookie and read the user’s information because the token is encrypted in http only cookie.<br>So we need some kind of store to save the current user.<br>We are going to use Ngxs store which is a global state manager that dispatches actions and provides a way to select data slices out from the global state.</p><p>we need 3 dependencies in order to use NGXS:</p><pre>npm install <a href="https://npmjs.com/package/@ngxs/store">@ngxs/store</a><br>npm install <a href="https://npmjs.com/package/@ngxs/logger-plugin">@ngxs/logger-plugin</a><br>npm install <a href="https://npmjs.com/package/@ngxs/storage-plugin"><strong>@ngxs/storage-plugin</strong></a></pre><p>And then we implement our actions and states:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/402/1*FYOvwiIGxUzxIrzwB_slmQ.png" /><figcaption>action.ts</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/678/1*AL3-e9K2CWGPuw7_IXpxlg.png" /><figcaption>state.ts</figcaption></figure><p>After setting up our state we will implement our authentication service:</p><pre>const URL_BASE = environment.baseUrl;</pre><pre>@Injectable({</pre><pre>providedIn: &#39;root&#39;</pre><pre>})<br>export class AuthService {<br>constructor(private router: Router, private store: Store,private  httpClient: HttpClient) {</pre><pre>}</pre><pre>signIn(request: LoginRequest):Observable&lt;any&gt;{</pre><pre>return this.httpClient.post&lt;any&gt;(URL_BASE + &#39;/auth/login&#39;, request, {withCredentials: true});}</pre><pre>refresh():Observable&lt;any&gt;{</pre><pre>return this.httpClient.post&lt;any&gt;(URL_BASE+&#39;/auth/refresh&#39;, {withCredentials: true});</pre><pre>}</pre><pre>getUser(): Observable&lt;any&gt; {</pre><pre>return this.httpClient.get&lt;any&gt;(URL_BASE+&#39;/profile/me&#39;, {withCredentials: true})</pre><pre>.pipe(</pre><pre>tap(user =&gt; {</pre><pre>console.log(user);</pre><pre>})</pre><pre>);</pre><pre>;</pre><pre>}</pre><pre>logOut():Observable&lt;any&gt;{</pre><pre>return this.httpClient.get(URL_BASE+&#39;/auth/logout&#39;,{withCredentials: true}).pipe(</pre><pre>tap(res =&gt; {</pre><pre>console.log(res);</pre><pre>this.store.dispatch(new Reset());</pre><pre>localStorage.clear();</pre><pre>this.router.navigate([&#39;&#39;]);</pre><pre>})</pre><pre>)</pre><pre>}</pre><pre>}</pre><p>And now the most important part is implementing the interceptor: This is where we are going to send the cookies in the header of our request and handle the server’s response.</p><pre>@Injectable()</pre><pre>export class Interceptor implements HttpInterceptor {</pre><pre>constructor(private auth: AuthService,</pre><pre>private  toaster: ToastrService</pre><pre>) {</pre><pre>}</pre><pre>intercept(request: HttpRequest&lt;any&gt;, next: HttpHandler): Observable&lt;HttpEvent&lt;any&gt;&gt; {</pre><pre>const re1 = &#39;/assets&#39;;</pre><pre>const re2 = &#39;/auth/logout&#39;;</pre><pre>const re3 = &#39;/auth/login&#39;;</pre><pre>if (request.url.search(re1) === -1</pre><pre>&amp;&amp; request.url.search(re2) === -1</pre><pre>&amp;&amp; request.url.search(re3) === -1</pre><pre>)</pre><pre>{</pre><pre>request = request.clone({</pre><pre>withCredentials: true</pre><pre>});</pre><pre>}</pre><pre>return next.handle(request).pipe(</pre><pre>catchError((err: any) =&gt; {</pre><pre>if(err.status==401){</pre><pre>// if request is unauthorized</pre><pre>if(err.headers.get(&#39;Message&#39;)==&#39;Invalid token&#39;){</pre><pre>// if token is invalid</pre><pre>return this.refreshToken(request, next);</pre><pre>} else {</pre><pre>// if session is expired</pre><pre>this.toaster.info(&#39;Votre session à étè expirée&#39;);</pre><pre>this.auth.logOut().subscribe(</pre><pre>res =&gt; console.log(res),</pre><pre>err =&gt; console.log(err)</pre><pre>)</pre><pre>}</pre><pre>}</pre><pre>})</pre><pre>);</pre><pre>}</pre><pre>private refreshToken(request: HttpRequest&lt;any&gt;, next: HttpHandler): Observable&lt;HttpEvent&lt;any&gt;&gt; {</pre><pre>return this.auth.refresh().pipe(</pre><pre>switchMap(</pre><pre>(res) =&gt; {</pre><pre>return next.handle(this.addAuthorizationHeader(request, res.status));</pre><pre>},</pre><pre>)</pre><pre>);</pre><pre>}</pre><pre>private addAuthorizationHeader(request: HttpRequest&lt;any&gt;, res: string): HttpRequest&lt;any&gt; {</pre><pre>if (res.toString()==&#39;SUCCESS&#39;) {</pre><pre>// if refresh token is valid</pre><pre>return request.clone({withCredentials: true});</pre><pre>}</pre><pre>// if refresh token is invalid</pre><pre>this.auth.logOut().subscribe(</pre><pre>res =&gt; console.log(res),</pre><pre>err =&gt; console.log(err)</pre><pre>)</pre><pre>}}</pre><p>We are going to handle 3 types kinds of errors:</p><ul><li>if the server returns an error with 401 status then we should check if it’s due to invalid token if it’s the case then we will call the refresh token to get an another access token</li><li>if the server returns 401 status but it’s <strong>not an invalid token </strong>then it’s definetly a session expiracy so we have to logout the user directly.</li><li>The third option and happens rarely if the refresh token is expired , this is unlikely to happen cause our refresh token will expire after 3 months but we need to handle this situation anyways , so if the access token is expired and we call the refresh token and still get 401 unauthorized than the refresh token is definetly expired in that case we have logout the user and destroy the session.</li></ul><p>As a final result we can see the access token , refresh token and the session stored as http only cookie.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t5kZHnTpcJH3aZ-tu-W_nA.png" /></figure><p>You can find the full source code in the git repository below:</p><p><a href="https://github.com/FirasMessaoudi/springboot-angular-authentication">FirasMessaoudi/springboot-angular-authentication</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a28481a8b833" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/spring-boot-authentication-with-angular-8-using-ngxs-jwt-http-only-cookie-spring-session-jdbc-a28481a8b833">Spring Boot authentication with Angular 8 using Ngxs+ JWT+Http Only Cookie+Spring Session JDBC</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>