<?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 Patroclos Lemoniatis on Medium]]></title>
        <description><![CDATA[Stories by Patroclos Lemoniatis on Medium]]></description>
        <link>https://medium.com/@patroclosdev?source=rss-ba0dd9b6831f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*IiGZxwBGs_c6x8mGLzEfOw.jpeg</url>
            <title>Stories by Patroclos Lemoniatis on Medium</title>
            <link>https://medium.com/@patroclosdev?source=rss-ba0dd9b6831f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 09:43:00 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@patroclosdev/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How i extented my AI Agent’s knowledge using MCP]]></title>
            <link>https://patroclosdev.medium.com/how-i-extented-my-ai-agents-knowledge-using-mcp-aac7ecbaf4b0?source=rss-ba0dd9b6831f------2</link>
            <guid isPermaLink="false">https://medium.com/p/aac7ecbaf4b0</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[mcp-protocol]]></category>
            <dc:creator><![CDATA[Patroclos Lemoniatis]]></dc:creator>
            <pubDate>Fri, 21 Nov 2025 06:04:44 GMT</pubDate>
            <atom:updated>2025-11-21T06:04:44.421Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eEPQI7pED2xZq9i8bz9T0A.jpeg" /><figcaption>Image by rawpixel.com on <a href="https://www.freepik.com/free-vector/ai-technology-microchip-background-vector-digital-transformation-concept_16268313.htm#fromView=search&amp;page=1&amp;position=2&amp;uuid=09d0f9a0-2859-4452-861a-afaf5b06e3e6&amp;query=ai">Freepik</a></figcaption></figure><p>For a long time i have been trying to found ways of training an AI Agent, but without the hussle of fine tuning or training an LLM from scratch.</p><p>Until i read about MCP protocol</p><h3>What is MCP (Model Context Protocol)?</h3><p><strong>MCP (Model Context Protocol)</strong> is an open standard created by <strong>Anthropic</strong> that allows AI models to connect to external tools, databases, APIs, or local systems in a <strong>safe, structured, and permission-controlled way</strong>.</p><p>It defines <strong>how AI models communicate with external resources</strong>, similar to how browsers use HTTP or apps use APIs.</p><p><em>For my implementation of an LLM extending it’s knowledge, i used Docker AI and SpringBoot AI MCP libraries</em></p><p>Let’s go through the whole process …</p><p>First, I installed Docker Desktop and dowloaded <strong>ai/gemma3</strong> model, from Models tab.</p><p>Then, I initiated a spring boot project. whole code can be found here…</p><p><a href="https://github.com/patroklos83/springboot-ai-mcp">https://github.com/patroklos83/springboot-ai-mcp</a></p><p>In my springboot project i have implemented an MCP server and an MCP client.</p><h4><strong>Why is that?</strong></h4><p>The process where the LLM connects to the external source through MCP, protocol</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/661/1*iQ8lhXJZVYWBH6JtjYayVg.png" /></figure><p>I added some information — data in a Postgres local database</p><pre>INSERT INTO dragonball.&quot;characters&quot; (&quot;name&quot;,info) VALUES<br>  (&#39;Goku&#39;,&#39;Son Goku, born Kakarot, is a male Saiyan and the main protagonist of the Dragon Ball metaseries created by Akira Toriyama&#39;);</pre><p>The idea here, is that the LLM does not know anything about Goku a character from dragonball. Therefore it will try to fetch this information from the Postgres database.</p><p>Let’s give it a go !</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*notfXnMwgGU0VH3rcA7w_Q.png" /></figure><p><strong><em>So … now my AI Agent knows a thing or two about Goku !</em></strong></p><p><a href="https://github.com/patroklos83/springboot-ai-mcp">https://github.com/patroklos83/springboot-ai-mcp</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aac7ecbaf4b0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Microservices using Spring boot 3.5 Keycloak, Caching and API limiting]]></title>
            <link>https://medium.com/codex/microservices-using-spring-boot-3-5-keycloak-caching-and-api-limiting-e5c945959d5d?source=rss-ba0dd9b6831f------2</link>
            <guid isPermaLink="false">https://medium.com/p/e5c945959d5d</guid>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[microservice-architecture]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[spring-boot-3]]></category>
            <dc:creator><![CDATA[Patroclos Lemoniatis]]></dc:creator>
            <pubDate>Sun, 12 Oct 2025 09:24:38 GMT</pubDate>
            <atom:updated>2026-03-10T07:56:34.505Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hkn23RZ4gPn_D7ao9qhTXg.png" /></figure><h3>Project Overview</h3><p>This project is a <strong>Spring Boot 3.5</strong>–based web application designed to demonstrate a modern, production-ready microservice architecture. The core functionality is a simple “Hello World” REST API, but the application integrates several enterprise-grade features that highlight best practices in scalability, security, and performance optimization.</p><h3>Security and JWT-Based Authorization</h3><p>The application uses <strong>Keycloak</strong> as an external <strong>Authorization Server</strong>, implementing <strong>OAuth2</strong> and <strong>OpenID Connect</strong> standards. When a user logs in, Keycloak issues a <strong>JWT (JSON Web Token)</strong>, which is then included in the Authorization header of API requests. The Spring Boot application validates this JWT to authenticate users and determine their access permissions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7IsWyQ1H8tZx_so4rtW6kg.png" /></figure><p>Access to the controller endpoints is protected using <strong>role-based authorization</strong>, specifically requiring the <strong>ROLE_USER</strong> authority. This ensures that only authenticated users with the appropriate role can access secured APIs, maintaining a strong and flexible security boundary between users and services.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9bQzpXq3GL3oFO1sbDskDg.png" /></figure><h3>Performance Optimization with Redis</h3><p>To enhance performance and reduce latency, the project incorporates <strong>Redis</strong> as a distributed caching layer. Frequently accessed data and authentication tokens are cached to minimize repetitive database calls and improve response times. This integration demonstrates how Spring Boot applications can achieve high performance and scalability through efficient caching strategies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QMSGg-nsCk45qKysIxES9g.png" /></figure><h3>API Rate Limiting and Resilience</h3><p>The project also includes <strong>Resilience4j</strong>, a lightweight fault tolerance library, to implement API rate limiting and improve system resilience. By configuring rate limiters, circuit breakers, and bulkhead patterns, the application prevents overloading, ensures graceful degradation under heavy traffic, and protects backend services from abuse or failure cascades.</p><h3>Containerization and Deployment</h3><p>A <strong>Docker Compose</strong> configuration is included to simplify local deployment and environment setup. The docker-compose.yml file orchestrates three core services:</p><ul><li><strong>Redis</strong> — for caching and performance optimization</li><li><strong>Keycloak</strong> — for authentication and token management</li><li><strong>Spring Boot Application</strong> — the main service providing the REST API</li></ul><p>This setup allows the entire stack to be started with a single command, ensuring consistent and reproducible environments for development and testing.</p><h3>Summary</h3><p>Overall, this project showcases how to build a secure, performant, and resilient microservice using Spring Boot 3.5. It combines modern Java development practices with powerful open-source tools — Keycloak for security, Redis for caching, and Resilience4j for stability — resulting in a clean, extensible foundation suitable for enterprise-grade applications.</p><p><a href="https://github.com/patroklos83/spring-boot-3-keycloak-redis">GitHub - patroklos83/spring-boot-3-keycloak-redis: A sample spring boot 3.5 app integrating with Keycloak and Redis Cache</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e5c945959d5d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/microservices-using-spring-boot-3-5-keycloak-caching-and-api-limiting-e5c945959d5d">Microservices using Spring boot 3.5 Keycloak, Caching and API limiting</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AI driven Activity monitoring — Docker AI models & Spring framework]]></title>
            <link>https://medium.com/codex/ai-driven-activity-monitoring-docker-ai-models-spring-framework-efe3793c982d?source=rss-ba0dd9b6831f------2</link>
            <guid isPermaLink="false">https://medium.com/p/efe3793c982d</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[docker-ai]]></category>
            <category><![CDATA[spring-framework]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Patroclos Lemoniatis]]></dc:creator>
            <pubDate>Sun, 21 Sep 2025 11:57:12 GMT</pubDate>
            <atom:updated>2025-09-29T10:45:43.508Z</atom:updated>
            <content:encoded><![CDATA[<h3>AI driven Activity monitoring — Docker AI models &amp; Spring framework</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ISDqtvswvHMR34G-HYR-tA.jpeg" /><figcaption>image from <a href="https://www.freepik.com/">FreePic</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*WQA7XtDACJyLKVm-GSGHcQ.gif" /><figcaption>dashboard AI generated message, summarizing recent system activity logs, by integrating with Docker AI model<strong> gemma3</strong></figcaption></figure><p>AI-driven Audit Monitoring leverages the power of artificial intelligence to provide continuous, intelligent oversight of business processes and system activities. By integrating AI models packaged in Docker containers with a Spring MVC–based Java application, organizations can achieve scalable, real-time monitoring without disrupting existing infrastructures.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hrziAxiiXEdwJqF4cliWgA.png" /></figure><p>The Spring MVC framework ensures a modular and maintainable backend that efficiently routes and manages audit data, while Docker enables seamless deployment and scaling of AI models across environments.</p><p>These AI models can automatically detect anomalies, flag suspicious transactions, and generate predictive insights, reducing manual audit workloads and improving compliance accuracy. This architecture not only enhances transparency and reliability in audit processes but also offers a flexible foundation to incorporate future AI advancements with minimal operational overhead.</p><p><strong><em>Sample System Activity Logs</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hK8MeoXNLnAoreXzXCkxfQ.png" /></figure><h3>How to set up <strong>Docker Desktop</strong> and pull the <strong>Gemma3 model</strong>:</h3><h3>Install Docker Desktop</h3><ul><li>Go to <a href="https://www.docker.com/products/docker-desktop/">Docker Desktop download page</a>.</li><li>Download the installer for your OS (<strong>Windows</strong> or <strong>macOS</strong>).</li><li>Run the installer and follow the setup wizard.</li><li>After installation, open Docker Desktop and ensure the Docker Engine is running.</li></ul><h3>Pull and Run Gemma3 Model with Docker</h3><p><strong>Use AI Models inside Docker</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ga7GVDOX0IIYI2gsNytA4Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BzAAKlElETD4pLzLLtmhRQ.png" /></figure><p>Code snippet from Spring MVC dashboardController</p><pre>@Slf4j<br>@Component<br>public class AIUtil {<br> <br> private ObjectMapper mapper = new ObjectMapper();<br><br>    private final WebClient webClient;<br><br>    public AIUtil() {<br>        this.webClient = WebClient.builder()<br>                .baseUrl(&quot;http://localhost:12434&quot;)<br>                .build();<br>    }<br><br>    public String callModelRunner(ChatRequestDTO chatRequestDTO) {<br>        try {<br>   var response = webClient.post()<br>           .uri(&quot;/engines/llama.cpp/v1/chat/completions&quot;)<br>           .header(&quot;Content-Type&quot;, &quot;application/json&quot;)<br>           .bodyValue(mapper.writeValueAsString(chatRequestDTO))<br>           .retrieve()<br>           .bodyToMono(ChatCompletionResponseDTO.class)<br>           .onErrorResume(e -&gt; {<br>               e.printStackTrace();<br>               return Mono.empty();<br>           })<br>           .block();<br>   log.info(&quot;AI Response: &quot; + response.getChoices().get(0).getMessage().getContent());<br>  <br>   return response.getChoices().get(0).getMessage().getContent();<br>  <br>  } catch (Exception e) {<br>   // TODO Auto-generated catch block<br>   e.printStackTrace();<br>  }<br>  return null;<br>    }<br>}</pre><pre>  AIUtil aiUtil = new AIUtil();<br>  var request = ChatRequestDTO.builder()<br>  .model(&quot;ai/gemma3&quot;)<br>  .messages(new ArrayList&lt;&gt;())<br>  .build();<br>  Message m = new Message();<br>  m.setRole(&quot;user&quot;);<br>  m.setContent(&quot;You are an AI assistant that helps users to understand the latest activities in their system. &quot;<br>    + &quot;Based on the following activity summaries, provide a concise and friendly welcome message for the dashboard, &quot;<br>    + &quot;highlighting key actions and encouraging further engagement. &quot;<br>    + &quot;Make it engaging and relevant to the user&#39;s recent activities. &quot;<br>    + &quot;Also suggest one or two actions the user might want to take next based on these activities. &quot;<br>    + &quot;Kepp an eye on security-related activities and mention them if relevant. &quot;<br>    + &quot;Here are the activity summaries: &quot; + activitySummaries.toString());<br>  request.getMessages().add(m);<br>  String response = aiUtil.callModelRunner(request);<br>  if (response != null &amp;&amp; response.length() &gt; 0) {<br>   model.addAttribute(&quot;message&quot;, <br>     response.replace(&quot;\\&quot;, &quot;\\\\&quot;)   // backslash<br>        .replace(&quot;\&quot;&quot;, &quot;\\\&quot;&quot;)   // double quote<br>        .replace(&quot;\r&quot;, &quot;\\r&quot;)    // carriage return<br>        .replace(&quot;\n&quot;, &quot;\\n&quot;));<br>  }<br> </pre><p>application.properties</p><pre>spring.ai.chat.client.enabled=true<br>spring.ai.openai.api-key=ignored<br>spring.ai.openai.base-url=http://localhost:12434/engines<br>spring.ai.openai.chat.options.model=ai/gemma3</pre><p><strong><em>You can download full Spring MVC code from below link</em></strong></p><p><a href="https://github.com/patroklos83/SpringMVC">https://github.com/patroklos83/SpringMVC</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=efe3793c982d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/ai-driven-activity-monitoring-docker-ai-models-spring-framework-efe3793c982d">AI driven Activity monitoring — Docker AI models &amp; Spring framework</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LLM Artificial Intelligence: RAG or Fine-tuning]]></title>
            <link>https://blog.devops.dev/llm-artificial-intelligence-rag-or-fine-tuning-809553d73bcc?source=rss-ba0dd9b6831f------2</link>
            <guid isPermaLink="false">https://medium.com/p/809553d73bcc</guid>
            <category><![CDATA[business]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Patroclos Lemoniatis]]></dc:creator>
            <pubDate>Sun, 15 Sep 2024 10:23:14 GMT</pubDate>
            <atom:updated>2025-09-29T14:52:54.147Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KdOaAprVlCscFy28RR3LVA.jpeg" /><figcaption><a href="https://www.vecteezy.com/free-vector/ai-training">Ai Training Vectors by Vecteezy</a></figcaption></figure><h3>What are LLMs?</h3><p>Large language models (LLMs) are machine learning models that can understand and generate human language text. LLMs acquire these abilities by learning statistical relationships from vast amounts of text during a self-supervised and semi-supervised training process.</p><h3>What ways are there to train LLMs?</h3><ul><li><strong>Pretraining</strong></li></ul><p>Models gain a general understanding of natural language after being exposed to a vast dataset of information. During this phase, the LLM learns grammar rules, linguistic patterns, factual information, and reasoning abilities.</p><p><em>Text generation</em> : Models can generate poetry, write essays and articles, as well as provide responses that feel remarkably human.</p><p><em>Language translation</em> : Imagine a Model that can understand everything you say in any language and being able to provide a response in any language!</p><ul><li><strong>Fine Tuning</strong></li></ul><p>Is an approach to transfer learning in which the parameters of a pre-trained model are trained on new data¹. Fine-tuning can be done on the entire neural network, or on only a subset of its layers, in which case the layers that are not being fine-tuned are “frozen” (or, not changed during the backpropagation step)². Fine-tuning is typically accomplished with supervised learning, but there are also techniques to fine-tune a model using weak supervision.³</p><ul><li><strong>RAG</strong></li></ul><p><strong>Retrieval augmented generation</strong> (<strong>RAG</strong>) is a type of generative artificial intelligence that has information retrieval capabilities. It modifies interactions with a large language model (LLM) so that the model responds to user queries with reference to a specified set of documents, using this information in preference to information drawn from its own vast, static training data.⁴ The RAG process is made up of four key stages. First, all the data must be prepared and indexed for use by the LLM. Thereafter, each query consists of a retrieval, augmentation and a generation phase.⁵</p><p>In general terms, there is no need to train the model, just store the additional information into a vector database and query the data from there.</p><h3>RAG example</h3><pre>&gt;&gt; docker pull ollama/ollama<br><br>#pull and run llama3 llm<br>#Make sure ollama container exposes port 11434</pre><pre># activate python environment<br>&gt;&gt; source .venv/bin/activate<br><br><br># Install python dependencies<br>#------------------------------------------------------------------------<br>&gt;&gt; pip install ollama-python pypdf2<br>&gt;&gt; pip install llama-index-llms-ollama<br>&gt;&gt; pip install llama-index llama-index-llms-openllm llama-index-embeddings-huggingface<br>&gt;&gt; python -m pip install langchain<br>&gt;&gt; pip install -U langchain-community llama-index-embeddings-langchain</pre><p><em>Python script </em><strong>train-llamaindex<em>.py</em></strong></p><p>Be sure, to add in the same folder, a sample file containing the additional information, needed by the LLM to generate a response. In this example i have used file ‘rag-training.txt’.</p><pre>from llama_index.core import VectorStoreIndex, SimpleDirectoryReader, ServiceContext, StorageContext<br>#from llama_index.llms.openllm import OpenLLMAPI<br>from llama_index.core.node_parser import SentenceSplitter<br>from langchain.embeddings import OllamaEmbeddings<br>from llama_index.core import Settings<br>from llama_index.llms.ollama import Ollama<br><br>emb = OllamaEmbeddings(model=&quot;llama3&quot;)<br><br>Settings.embed_model = emb<br>Settings.node_parser = SentenceSplitter(chunk_size=512, chunk_overlap=20)<br>Settings.num_output = 512<br>Settings.context_window = 3900<br>Settings.transformations = [SentenceSplitter(chunk_size=1024)]<br><br>#listens to localhost:11434 by default<br>llm = Ollama(base_url=&quot;http://localhost:11434&quot;, model=&quot;llama3&quot;, request_timeout=120.0)<br><br>Settings.llm = llm<br><br># Break down the document into manageable chunks (each of size 1024 characters, with a 20-character overlap)<br>text_splitter = SentenceSplitter(chunk_size=1024, chunk_overlap=20)<br><br>storage_context = StorageContext.from_defaults(<br>    vector_store=emb<br>)<br><br># Load documents from the data directory<br>documents = SimpleDirectoryReader(<br>    input_files=[&quot;rag-training.txt&quot;]<br>)<br><br>documents = documents.load_data();<br><br># Build an index over the documents<br>index = VectorStoreIndex.from_documents(<br>    documents, embed_model=emb, transformations=Settings.transformations<br>)<br><br># Query your data using the built index<br>query_engine = index.as_query_engine()<br>response = query_engine.query(&quot;Who is Patroclos?&quot;)<br>print(response)</pre><pre>&gt;&gt; python train-llamaindex.py</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BDej_saKw4s3ET4VKgtu9w.png" /></figure><p>by modifying the prompt …</p><pre>response = query_engine.query(&quot;Patroclos and Cyprus relation&quot;)</pre><p>we get …</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vf3I_dLqLDz20Wzl7v4qdQ.png" /></figure><p>Consequently, using additional information from a custom text file, we have added knowledge to the current LLM used.</p><h3>Fine-Tuning</h3><p><em>Improving LLM on particular and specific tasks</em></p><p>For this example, we have used <strong>Apple M2 pro</strong> with <strong>16GB</strong> memory</p><h4>Create mlxo directory</h4><pre><br>&gt;&gt; mkdir mlxo<br>&gt;&gt; cd mlxo<br></pre><h4>Create python virtual environment and install dependencies⁷</h4><pre>&gt;&gt; python -m venv .venv<br>&gt;&gt; source .venv/bin/activate<br><br><br>&gt;&gt; pip install -U mlx-lm<br>&gt;&gt; pip install pandas<br>&gt;&gt; pip install pyarrow</pre><h4>Setup Huggingface-CLI⁷</h4><ol><li>Create an account at <strong>hugginface</strong> webpage: <a href="https://huggingface.co/welcome">https://huggingface.co/welcome</a></li></ol><p>2. Set an access token from <a href="https://huggingface.co/settings/tokens">https://huggingface.co/settings/tokens</a></p><pre>&gt;&gt; pip install huggingface_hub<br>&gt;&gt; pip install &quot;huggingface_hub[cli]&quot;</pre><pre># login to huggingface through cli<br># it will ask the access token previously created <br>❯❯ huggingface-cli login</pre><h4>Prepare a dataset</h4><p>For more information on the correct format for preparing a dataset please refer to <a href="https://github.com/ml-explore/mlx-examples/blob/main/llms/mlx_lm/LORA.md#Data">https://github.com/ml-explore/mlx-examples/blob/main/llms/mlx_lm/LORA.md#Data</a></p><p><strong><em>Sample training files content</em></strong></p><pre>#train<br>{&quot;prompt&quot;: &quot;Who is Patroclos Lemoniatis?&quot;, &quot;completion&quot;: &quot;A software developer from Cyprus&quot;}<br><br>#test<br>{&quot;prompt&quot;: &quot;Who is Patroclos Lemoniatis?&quot;, &quot;completion&quot;: &quot;A software developer from Cyprus&quot;}<br><br>#valid<br>{&quot;prompt&quot;: &quot;Who is Patroclos Lemoniatis?&quot;, &quot;completion&quot;: &quot;A software developer from Cyprus&quot;}</pre><h4>Download LLM from huggingface</h4><pre>&gt;&gt; huggingface-cli download TinyLlama/TinyLlama-1.1B-Chat-v1.0</pre><pre>&gt;&gt; huggingface-cli scan-cache<br><br>REPO ID                                REPO TYPE SIZE ON DISK NB FILES LAST_ACCESSED  LAST_MODIFIED REFS LOCAL PATH                                                                              <br>-------------------------------------- --------- ------------ -------- -------------- ------------- ---- --------------------------------------------------------------------------------------- <br>TinyLlama/TinyLlama-1.1B-Chat-v1.0     model             2.2G       10 1 minute ago   1 minute ago  main /Users/xxxxxxxx/.cache/huggingface/hub/models--TinyLlama--TinyLlama-1.1B-Chat-v1.0     <br>bert-base-uncased                      model           466.1K        1 2 weeks ago    2 weeks ago   main /Users/xxxxxxxx/.cache/huggingface/hub/models--bert-base-uncased                       </pre><p>Fine Tune LLM</p><pre>python -m mlx_lm.lora \<br>  --model TinyLlama/TinyLlama-1.1B-Chat-v1.0 \<br>  --data dataOutput \<br>  --train \<br>  --batch-size 1\<br>  --lora-layers 16\<br>  --iters 50</pre><p>Test LLM</p><pre>python -m mlx_lm.lora \<br>  --model TinyLlama/TinyLlama-1.1B-Chat-v1.0 \<br>  --adapter-path adapters \<br>  --data dataOutput \<br>  --test</pre><p>Before fine tuning ….</p><p>A totally wrong answer, a<strong><em> </em></strong><a href="https://www.digitalocean.com/resources/articles/ai-hallucination"><strong><em>hallucination</em></strong></a> response</p><pre>python -m mlx_lm.generate \<br>     --model TinyLlama/TinyLlama-1.1B-Chat-v1.0 \<br>     --max-tokens 500 \<br>     --prompt &quot;Who is Patroclos Lemoniatis?&quot;<br>Fetching 8 files: 100%|██████████████████████████████████████████████████████████████████████| 8/8 [00:00&lt;00:00, 28460.08it/s]<br>==========<br>Prompt: &lt;|user|&gt;<br>Who is Patroclos Lemoniatis?&lt;/s&gt;<br>&lt;|assistant|&gt;<br><br>Patroclos Lemoniatis was a Greek philosopher and mathematician <br>who lived in the 5th century BCE in the city-state of Athens. <br>He is best known for his work on the theory of numbers and his contributions <br>to the field of geometry. Lemoniatis was a student of the renowned <br>mathematician Thales of Miletus and was one of the founding members of <br>the Athenian Academy.<br>==========<br>Prompt: 26 tokens, 380.505 tokens-per-sec<br>Generation: 92 tokens, 73.367 tokens-per-sec<br>Peak memory: 2.057 GB</pre><p>After fine tuning …</p><p>We have the correct response, as it was given in the training files</p><pre>python -m mlx_lm.generate \<br>     --model TinyLlama/TinyLlama-1.1B-Chat-v1.0 \<br>     --max-tokens 500 \<br>     --adapter-path adapters \<br>     --prompt &quot;Who is Patroclos Lemoniatis?&quot;<br>Fetching 8 files: 100%|██████████████████████████████████████████████████████████████████████| 8/8 [00:00&lt;00:00, 15842.51it/s]<br>==========<br>Prompt: &lt;|user|&gt;<br>Who is Patroclos Lemoniatis?&lt;/s&gt;<br>&lt;|assistant|&gt;<br><br>A software developer from Cyprus<br>==========<br>Prompt: 26 tokens, 292.529 tokens-per-sec<br>Generation: 8 tokens, 64.410 tokens-per-sec<br>Peak memory: 2.060 GB</pre><p>Building new model using Fusion adapters</p><pre>python -m mlx_lm.fuse \<br>    --model TinyLlama/TinyLlama-1.1B-Chat-v1.0 \<br>    --adapter-path adapters \<br>    --save-path models/finetune-model \<br>    --de-quantize</pre><p>We can ask the newly fine tuned model directly …</p><pre>python -m mlx_lm.fuse \    <br>    --model TinyLlama/TinyLlama-1.1B-Chat-v1.0 \<br>    --adapter-path adapters \<br>    --save-path models/finetune-model \   <br>    --de-quantize<br>Loading pretrained model<br>Fetching 8 files: 100%|██████████████████████████████████████████████████████████████████████| 8/8 [00:00&lt;00:00, 12614.45it/s]<br>De-quantizing model<br><br>python -m mlx_lm.generate \<br>  --model models/finetune-model \        <br>  --max-tokens 500 \         <br>  --prompt &quot;Whos is Patroclos Lemoniatis?&quot;<br>==========<br>Prompt: &lt;|user|&gt;<br>Whos is Patroclos Lemoniatis?&lt;/s&gt;<br>&lt;|assistant|&gt;<br><br>A software developer from Cyprus<br>==========<br>Prompt: 27 tokens, 393.215 tokens-per-sec<br>Generation: 8 tokens, 72.815 tokens-per-sec<br>Peak memory: 2.057 GB</pre><h4>Convert to gguf format</h4><pre>git clone https://github.com/ggerganov/llama.cpp<br>cd llama.cpp<br>make <br><br><br>python convert_hf_to_gguf.py ../models/finetune-model \ <br>     --outfile ../models/finetuned-model.gguf \<br>     --outtype q8_0</pre><h3>Which one to choose?</h3><p>To improve Large Language Model (LLM) performance on domain specific applications, ML developers often leverage Retrieval Augmented Generation (RAG) and LLM Fine-Tuning. <strong>RAG</strong> extends the capabilities of LLMs to specific domains or an organization’s internal knowledge base, without the need to retrain the model. On the other hand, <strong>Fine-Tuning</strong> approach updates LLM weights with domain-specific data to improve performance on specific tasks.⁶</p><p><a href="https://github.com/patroklos83/llm-training">GitHub - patroklos83/llm-training: LLM finetuning and RAG samples</a></p><ol><li>Quinn, Joanne (2020). <a href="https://d2l.ai/chapter_computer-vision/fine-tuning.html#steps"><em>Dive into deep learning: tools for engagement</em></a>. Thousand Oaks, California. p. 551.</li><li><a href="https://cs231n.github.io/transfer-learning/">“CS231n Convolutional Neural Networks for Visual Recognition”</a>. <em>cs231n.github.io</em>. Retrieved 9 March 2023.</li><li>Yu, Yue; Zuo, Simiao; Jiang, Haoming; Ren, Wendi; Zhao, Tuo; Zhang, Chao (2020). “Fine-Tuning Pre-trained Language Model with Weak Supervision: A Contrastive-Regularized Self-Training Approach”. <em>Association for Computational Linguistics</em>. <a href="https://en.wikipedia.org/wiki/ArXiv_(identifier)">arXiv</a>:<a href="https://arxiv.org/abs/2010.07835">2010.07835</a>.</li><li><a href="https://en.wikipedia.org/wiki/Retrieval-augmented_generation">https://en.wikipedia.org/wiki/Retrieval-augmented_generation</a>, “Retrieval-augmented generation”.</li><li>Gao, Yunfan; Xiong, Yun; Gao, Xinyu; Jia, Kangxiang; Pan, Jinliu; Bi, Yuxi; Dai, Yi; Sun, Jiawei; Wang, Meng; Wang, Haofen (2023). “Retrieval-Augmented Generation for Large Language Models: A Survey”. <a href="https://en.wikipedia.org/wiki/ArXiv_(identifier)">arXiv</a>:<a href="https://arxiv.org/abs/2312.10997">2312.10997</a> [<a href="https://arxiv.org/archive/cs.CL">cs.CL</a>].</li><li>José Cassio dos Santos Junior, Rachel Hu, Richard Song, and Yunfei Bai. 2024. Domain-Driven LLM Development: Insights into RAG and Fine-Tuning Practices. In Proceedings of the 30th ACM SIGKDD Conference on Knowledge Discovery and Data Mining (KDD ‘24). Association for Computing Machinery, New York, NY, USA, 6416–6417. <a href="https://doi.org/10.1145/3637528.3671445">https://doi.org/10.1145/3637528.3671445</a></li><li><a href="https://medium.com/rahasak/fine-tuning-llms-on-macos-using-mlx-and-run-with-ollama-182a20f1fd2c">https://medium.com/rahasak/fine-tuning-llms-on-macos-using-mlx-and-run-with-ollama-182a20f1fd2c</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=809553d73bcc" width="1" height="1" alt=""><hr><p><a href="https://blog.devops.dev/llm-artificial-intelligence-rag-or-fine-tuning-809553d73bcc">LLM Artificial Intelligence: RAG or Fine-tuning</a> was originally published in <a href="https://blog.devops.dev/">DevOps.dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java-Powered Intelligence: Exploring AI Integration in Java Applications]]></title>
            <link>https://medium.com/codex/java-powered-intelligence-exploring-ai-integration-in-java-applications-fa4439a56f7f?source=rss-ba0dd9b6831f------2</link>
            <guid isPermaLink="false">https://medium.com/p/fa4439a56f7f</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Patroclos Lemoniatis]]></dc:creator>
            <pubDate>Tue, 28 May 2024 10:34:46 GMT</pubDate>
            <atom:updated>2025-09-29T10:45:51.304Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lUakU11S6TuX48G-xoRh4g.jpeg" /><figcaption>Image by <a href="https://pixabay.com/users/grumpybeere-22072131/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=8779057">GrumpyBeere</a> from <a href="https://pixabay.com//?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=8779057">Pixabay</a></figcaption></figure><h4>Spring Boot</h4><p>Spring Boot is an open-source Java framework used for programming standalone, production-grade Spring-based applications with minimal effort. Spring Boot is a convention-over-configuration extension for the Spring Java platform intended to help minimize configuration concerns while creating Spring-based applications.¹</p><h4><strong>Artificial Intelligence³</strong></h4><p>AI, short for Artificial Intelligence, refers to the simulation of human intelligence processes by machines, particularly computer systems. These processes include learning, reasoning, and self-correction.</p><p>AI encompasses a wide range of techniques and approaches, including:</p><p>1. <strong>Machine Learning</strong>: A subset of AI that enables machines to learn from data without being explicitly programmed. Machine learning algorithms iteratively learn from data, identify patterns, and make decisions or predictions.</p><p>2. <strong>Deep Learning</strong>: A type of machine learning that uses artificial neural networks with many layers (deep neural networks) to model and process complex patterns in large amounts of data. Deep learning has been particularly successful in areas such as image and speech recognition.</p><p>3. <strong>Natural Language Processing (NLP)</strong>: The ability of computers to understand, interpret, and generate human language. NLP enables applications such as virtual assistants, language translation, and sentiment analysis.</p><p>4. <strong>Computer Vision</strong>: The field of AI focused on enabling computers to interpret and understand visual information from the real world, such as images and videos. Computer vision is used in applications ranging from facial recognition to autonomous vehicles.</p><p>5. <strong>Robotics</strong>: The integration of AI techniques into robotic systems to enable them to perceive their environment, make decisions, and perform tasks autonomously. Robotics has applications in manufacturing, healthcare, agriculture, and many other fields.</p><p>AI technologies have a wide range of applications across various industries, including:</p><ul><li>healthcare</li><li>finance</li><li>transportation</li><li>education</li><li>entertainment</li></ul><h4>Some common applications of AI include³</h4><ul><li>Personalized recommendations in e-commerce and content streaming platforms.</li><li>Fraud detection and risk assessment in banking and finance.</li><li>Autonomous vehicles and drones for transportation and delivery.</li><li>Medical image analysis for disease diagnosis and treatment planning.</li><li>Chatbots and virtual assistants for customer service and support.</li></ul><h3>How do machines translate real world information into data they understand?</h3><h4>Vector embeddings³</h4><p>also known as word embeddings or simply embeddings, are numerical representations of words or phrases in a continuous vector space. These representations are designed to capture semantic and syntactic similarities between words, making them useful for various natural language processing (NLP) tasks. Overall, vector embeddings provide a powerful way to represent and process natural language text in machine learning models, enabling them to understand and generate human-like language behavior.</p><h4>Vector databases³</h4><p>also known as vectorized databases or vector stores, are specialized databases designed to efficiently store, index, and query high-dimensional vector data. Unlike traditional relational databases that primarily deal with structured data like numbers and strings, vector databases are optimized for handling vectors, which are numerical representations of objects or entities in a multi-dimensional space.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/920/1*Eh9l_g4SMua5eV-CiJEC9A.png" /></figure><h3>Why are vector databases important?</h3><p>One of the primary values a database brings to application development is the ability to organize and categorize data efficiently for us by those applications. As stated above, vector databases are at the foundation of building generative AI applications because they enable vector search capabilities. When machine learning was in its infancy the data used by LLMs was typically small and finite, but as generative AI has become mainstream, the amount of data used to train and augment learning has grown exponentially. This is why vector databases are so important, they simplify fundamental operations for generative AI apps by storing large volumes of data in the structure that generative AI applications need for optimized operations.²</p><p><em>“[…] once you understand this ML multitool (embedding), you’ll be able to build everything from search engines to recommendation systems to chatbots and a whole lot more. You don’t have to be a data scientist with ML expertise to use them, nor do you need a huge labeled dataset.” — </em><a href="https://cloud.google.com/blog/topics/developers-practitioners/meet-ais-multitool-vector-embeddings"><em>Dale Markowitz, Google Cloud</em></a><em>.</em></p><h3>LLM — Large Language Models</h3><p>These are sophisticated AI models, like GPT-3, that are trained on vast amounts of text data to understand and generate human-like language. Large Language Models have various applications, including text generation, language translation, question answering, and more.</p><p>We can run and play with open source models using Ollama tool</p><p><a href="https://ollama.com/">Ollama · Run AI models locally and in the cloud</a></p><h4>Llama2 LLM</h4><p>Llama 2 is released by Meta Platforms, Inc. This model is trained on 2 trillion tokens, and by default supports a context length of 4096. Llama 2 Chat models are fine-tuned on over 1 million human annotations, and are made for chat.</p><h3>Let’s explore a java sample implementation …</h3><p>Using the springboot framework we will create the app’s configuration , controller and service to handle user chat questions and converting text to embeddings …</p><pre>package com.patroclos.ai.config;<br><br>import java.util.Map;<br><br>import javax.sql.DataSource;<br><br>import org.springframework.ai.document.MetadataMode;<br>import org.springframework.ai.postgresml.PostgresMlEmbeddingClient;<br>import org.springframework.ai.postgresml.PostgresMlEmbeddingClient.VectorType;<br>import org.springframework.ai.postgresml.PostgresMlEmbeddingOptions;<br>import org.springframework.beans.factory.annotation.Autowired;<br>import org.springframework.context.annotation.Bean;<br>import org.springframework.context.annotation.Configuration;<br>import org.springframework.core.task.AsyncTaskExecutor;<br>import org.springframework.jdbc.core.JdbcTemplate;<br>import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;<br><br>@Configuration<br>public class AppConfiguration {<br><br> @Autowired<br> private DataSource dataSource;<br><br> @Bean(&quot;embeddingClient&quot;)<br> PostgresMlEmbeddingClient embeddingClient() {<br>  PostgresMlEmbeddingClient embeddingClient = new PostgresMlEmbeddingClient(<br>    new JdbcTemplate(dataSource),<br>    PostgresMlEmbeddingOptions.builder()<br>    .withTransformer(&quot;distilbert-base-uncased&quot;) // huggingface transformer model name.<br>    .withVectorType(VectorType.PG_VECTOR) //vector type in PostgreSQL.<br>    .withKwargs(Map.of(&quot;device&quot;, &quot;cpu&quot;)) // optional arguments.<br>    .withMetadataMode(MetadataMode.EMBED) // Document metadata mode.<br>    .build());<br><br>  return embeddingClient;<br> }<br><br>}</pre><p><a href="https://docs.spring.io/spring-ai/reference/api/clients/ollama-chat.html">Ollama Chat</a></p><pre>package com.patroclos.ai.controller;<br><br>import java.io.IOException;<br>import java.util.List;<br><br>import org.slf4j.Logger;<br>import org.springframework.ai.chat.messages.Media;<br>import org.springframework.core.io.ClassPathResource;<br>import org.springframework.http.HttpStatus;<br>import org.springframework.http.ResponseEntity;<br>import org.springframework.util.MimeTypeUtils;<br>import org.springframework.web.bind.annotation.GetMapping;<br>import org.springframework.web.bind.annotation.PathVariable;<br>import org.springframework.web.bind.annotation.PostMapping;<br>import org.springframework.web.bind.annotation.RequestMapping;<br>import org.springframework.web.bind.annotation.RequestParam;<br>import org.springframework.web.bind.annotation.RestController;<br><br>import com.patroclos.ai.ollama.LlamaAiService;<br>import com.patroclos.ai.ollama.LlamaResponse;<br><br>@RestController<br>@RequestMapping(&quot;api/v1/ai/&quot;)<br>public class LlamaRestController {<br> <br> private final Logger log = org.slf4j.LoggerFactory.getLogger(LlamaRestController.class);<br><br> private final LlamaAiService llamaAiService;<br><br> public LlamaRestController(LlamaAiService llamaAiService) {<br>  this.llamaAiService = llamaAiService;<br> }<br> <br> @PostMapping(&quot;chat&quot;)<br> public ResponseEntity&lt;LlamaResponse&gt; chat(<br>   @RequestParam(value = &quot;text&quot;, defaultValue = &quot;&quot;) String text) throws IOException { <br>  if (text.isBlank()) {<br>   return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();<br>  }<br>  log.info(&quot;generating response for text ... {}&quot;, text);<br>  final LlamaResponse aiResponse = llamaAiService.generateMessage(text);<br>  log.info(&quot;got response for text {}&quot;, aiResponse.getMessage().toString());<br>  return ResponseEntity.status(HttpStatus.OK).body(aiResponse);<br> }<br> <br> @PostMapping(&quot;summarize&quot;)<br> public ResponseEntity&lt;LlamaResponse&gt; summarize(<br>   @RequestParam(value = &quot;text&quot;, defaultValue = &quot;&quot;) String text) throws IOException { <br>  if (text.isBlank()) {<br>   return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();<br>  }<br>  text = String.format(&quot;please summarize this text: %s&quot;, text);<br>  log.info(&quot;generating response for text ... {}&quot;, text);<br>  final LlamaResponse aiResponse = llamaAiService.generateMessage(text);<br>  log.info(&quot;got response for text {}&quot;, aiResponse.getMessage().toString());<br>  return ResponseEntity.status(HttpStatus.OK).body(aiResponse);<br> }<br><br> @PostMapping(&quot;generate&quot;)<br> public ResponseEntity&lt;LlamaResponse&gt; generate(<br>   @RequestParam(value = &quot;promptMessage&quot;) String promptMessage,<br>   @RequestParam(value = &quot;filename&quot;, defaultValue = &quot;&quot;) String filename) throws IOException {<br>  <br>  if (promptMessage.isBlank()) {<br>   return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();<br>  }<br>  <br>  List&lt;Media&gt; media = null;<br>  LlamaResponse aiResponse = null;<br>  <br>  if (filename != null &amp;&amp; filename.length() &gt; 0) {<br>   if (!filename.toLowerCase().endsWith(&quot;.png&quot;)) {<br>    aiResponse = new LlamaResponse();<br>    aiResponse.setMessage(&quot;only .png files allowed&quot;);  <br>    return ResponseEntity.badRequest().body(aiResponse);<br>   }<br>   <br>   filename = filename.startsWith(&quot;=&quot;) ? filename.substring(1, filename.length()) : filename;<br>   byte[] fileData = new ClassPathResource(&quot;/static/files/&quot; + filename).getContentAsByteArray();<br>   media = List.of(new Media(MimeTypeUtils.IMAGE_PNG, fileData));<br>   <br>   log.info(&quot;generating response for text [{}] and file [{}] ...&quot;, promptMessage, filename);<br>   aiResponse = llamaAiService.generateMessage(promptMessage, media);<br>  }<br>  else<br>  {<br>   log.info(&quot;generating response for text ... {}&quot;, promptMessage);<br>   aiResponse = llamaAiService.generateMessage(promptMessage);<br>  }<br>  log.info(&quot;got response for text {}&quot;, aiResponse.getMessage().toString());<br>   <br>  return ResponseEntity.status(HttpStatus.OK).body(aiResponse);<br> }<br><br>}</pre><pre>package com.patroclos.ai.ollama;<br><br>import java.io.IOException;<br>import java.util.List;<br><br>import org.springframework.ai.chat.ChatResponse;<br>import org.springframework.ai.chat.messages.Media;<br>import org.springframework.ai.chat.messages.UserMessage;<br>import org.springframework.ai.chat.prompt.Prompt;<br>import org.springframework.ai.ollama.OllamaChatClient;<br>import org.springframework.ai.ollama.api.OllamaOptions;<br>import org.springframework.stereotype.Service;<br><br>@Service<br>public class LlamaAiService {<br><br> private final OllamaChatClient chatClient;<br><br> public LlamaAiService(OllamaChatClient chatClient) {<br>  this.chatClient = chatClient;<br> }<br><br> public LlamaResponse generateMessage(String promptMessage) throws IOException {<br>  return generateMessage(promptMessage, null);<br> }<br><br> public LlamaResponse generateMessage(String promptMessage, List&lt;Media&gt; media) throws IOException {<br>  String llamaMessage = null;<br>  <br>  if (media == null) {<br>      llamaMessage = chatClient.call(promptMessage);<br>  }<br>  else {<br>   var userMessage = new UserMessage(promptMessage, media);<br>   ChatResponse response = chatClient.call(new Prompt(List.of(userMessage), OllamaOptions.create().withModel(&quot;mistral&quot;)));<br>   llamaMessage = response.getResult().getOutput().getContent();<br>  }<br><br><br>  LlamaResponse resp = new LlamaResponse();<br>  resp.setMessage(llamaMessage);<br>  return resp;<br> }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7NgZmsDq85Ue9IqW" /><figcaption>interaction with llama2 LLM</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WIHhUHtIpM42GEv3vBEoNQ.png" /><figcaption>interaction with vector database PostgresML</figcaption></figure><p>Fell free to dowload a copy of the code…</p><p><a href="https://github.com/patroklos83/spring-ai-public">GitHub - patroklos83/spring-ai-public: Sample spring boot AI module integration</a></p><p>[1]: <em>Spring</em> <em>Boot</em>, <a href="https://en.wikipedia.org/wiki/Spring_Boot">https://en.wikipedia.org/wiki/Spring_Boot</a></p><p>[2]: <em>What is a Vector Database?: A Comprehensive Guide,</em> <a href="https://www.datastax.com/guides/what-is-a-vector-database#why-are-vector-databases-important">https://www.datastax.com/guides/what-is-a-vector-database#why-are-vector-databases-important</a></p><p>[3] Information provided by OpenAI’s GPT model, accessed on May 28, 2024. <a href="https://chatgpt.com/">https://chatgpt.com/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fa4439a56f7f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/java-powered-intelligence-exploring-ai-integration-in-java-applications-fa4439a56f7f">Java-Powered Intelligence: Exploring AI Integration in Java Applications</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CQRS Pattern using Spring Boot version 3 and Axon Framework/Server]]></title>
            <link>https://medium.com/codex/cqrs-pattern-using-spring-boot-version-3-and-axon-framework-server-369dc13d41a6?source=rss-ba0dd9b6831f------2</link>
            <guid isPermaLink="false">https://medium.com/p/369dc13d41a6</guid>
            <category><![CDATA[axon-framework]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[cqrs]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Patroclos Lemoniatis]]></dc:creator>
            <pubDate>Fri, 09 Feb 2024 19:06:24 GMT</pubDate>
            <atom:updated>2025-11-11T07:32:20.196Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*g4HdFgaWdz1KwciCVkjTdA.png" /></figure><h3>What is CQRS?</h3><p><strong>CQRS</strong> stands for <strong><em>Command and Query Responsibility Segregation</em></strong>, a pattern that separates read and update operations for a data store. CQRS was introduced by Greg Young in 2010.</p><p>It Seggregates the responsibilities of the commands and queries in a system. Which means we are splitting the model into read and write. On top of that, command and read handling is seperated as well.</p><p>Write model is made up from the commands, and should be as close as possible to the business processes.</p><p>A query returns the result but does not change the state. As queries do not change the state of the objects, they do not need to involve the Domain Model.</p><p>A common misconception is that <strong><em>Command</em></strong> and <strong><em>Queries</em></strong> should run on seperate databases. This is not true since only the responsibilities should be seperated.</p><p><strong>CQRS is applicable to the behaviour of the system and not where the data is stored</strong></p><p>Often goes hand-in-hand with Event Sourcing.</p><h3><strong>Benefits of CQRS</strong></h3><ul><li><strong>Performance</strong></li></ul><p>By seperating read and write models, you can optimize each model accoringly for large scale systems.</p><ul><li><strong>Scalability</strong></li></ul><p>Read and Write model can be scaled independently according to the system workload.</p><ul><li><strong>Flexibility</strong></li></ul><p>Possible to choose seperate write and read databases, as to accomodate the needs for each aspect of the system.</p><ul><li><strong>Event Sourcing</strong></li></ul><p>Audit log, versioning and time travel capabilities</p><h3>Event Sourcing</h3><p>Is a pattern for storing data as events in an append-only event store. An event represents a true event that took place in a business. Every change to the business state, is being appended to the event store.</p><p>Event sourcing is great for keeping audit logs, as it also keeps the context of the object changed. Which answers the ‘what’ changed question, in an audit log.</p><p>Some advantages of event sourcing are</p><ul><li><strong>Audit log</strong>: Keeping detailed audit logs</li><li><strong>Time travel</strong>: Resetting the business model to a previous state</li><li><strong>Root cause analysis</strong>: Possible to investigate the root of an issue occured, by repeating an entire workflow from beginning to the end.</li><li><strong>Event Driven Architecture</strong>: Enabling the advantages of aynchronous architecture and subscribing to events for producing notifications, activating workflows based on the business events etc …</li></ul><h3>Lets start with the Event Store</h3><p>For storing events we can use <a href="https://developer.axoniq.io/en/axon-server/overview">Axon Server</a> and <a href="https://developer.axoniq.io/axon-framework/overview">Framework</a> which provides the whole setup for storing events.</p><p><strong>What is Axon Framework?</strong></p><p>Is an open source framework for building event-driven microservices and domain-driven design systems.</p><blockquote>Based on architectural principles, such as Domain-Driven Design (DDD) and Command-Query Responsibility Segregation (CQRS), the Axon Framework provides the building blocks that CQRS requires and helps create scalable and extensible applications while maintaining application consistency in distributed systems¹</blockquote><p><strong>What is Axon Server?</strong></p><p>Is a ready to use <strong>message router</strong> and an <strong>event store</strong>. It serves two purposes</p><ul><li>It routes messages (commands, queries, and events) between distributed components (microservices).</li><li>It stores events allowing distributed (often event sourced) applications to have a single source of a state repository.</li></ul><h3>Use case scenario</h3><p>A warehouse software system is handling inventory items.</p><p>A user is able to run multiple processes on the items. 2 of these processes are <strong>Create Inventory Items </strong>and <strong>Stock Adjustment (Increase / Decrease)</strong>.</p><p>Important to note, this system is being accessed, by thousand of users, since it is connected to an online store, that displays the availability of the products.</p><p>Inventory items stock counter is being updated frequently. In addition, queries are being executed for stock retrieval in parallel to the updates.</p><p>On top of that, for every stock update, system needs to keep a detailed <a href="https://medium.com/@patroclosdev/why-audit-logs-hibernate-envers-1ac92e52e918"><strong><em>Audit Log</em></strong></a> of what changed, when and by who.</p><p><strong>Problem</strong>,</p><p>is that system is experiencing a lot of database WRITE operations back-pressure. Plus, a huge amount of READ operations, are retrieving reduntant data from the inventory item tables. We need to to adjust the READ queries to minimize the time needed to fetch these information from the database.</p><p>Consequently, a <strong>solution</strong>, is to use <strong>CQRS with Event Sourcing</strong></p><p>Data reads must be fine-tuned separately from performance of data writes.</p><p>We need to seperate the model into 2 parts, the <strong><em>WRITE</em></strong> and <strong><em>READ</em></strong> model. This will allow the developers to refactor and fine-tune the WRTIE commands, which in turn will be added to a message queue. By introducing a message queue we are controlling the flow of the transactions to be executed by the database.</p><p>While this will significally reduce the performance bottleneck of the database on WRITE operatios, at the same time we are exchanging <strong>performance</strong> with <strong>cosistency</strong> of data. Validity of data is affected since there is a chance, a stock update to be delayed, a few minutes or more, until is reflected on the READ database.</p><p>There is no need for the Available stock on the online store item’s page, to be 100% accurate, since it is an estimate value. On the Checkout page though, the available stock has to be retrieved from the Event-Store, in order to replay all the events and calculate the items latest state and available stock.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*39R-Uy7SwccKJ97q-3tSjw.png" /><figcaption>A high-level diagram of the Inventory Service with CQRS Event Sourcing pattern</figcaption></figure><p>You can find a working example in the below link</p><p><a href="https://github.com/patroklos83/cqrs-springboot-axon">GitHub - patroklos83/cqrs-springboot-axon: Sample CQRS pattern with SpringBoot 3 and AXON Server/Framework</a></p><ol><li><a href="https://developer.axoniq.io/axon-framework/overview">https://developer.axoniq.io/axon-framework/overview</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=369dc13d41a6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/cqrs-pattern-using-spring-boot-version-3-and-axon-framework-server-369dc13d41a6">CQRS Pattern using Spring Boot version 3 and Axon Framework/Server</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Software Architecture and Designing Large scale systems]]></title>
            <link>https://medium.com/codex/software-architecture-and-designing-large-scale-systems-ccd9d970fb0f?source=rss-ba0dd9b6831f------2</link>
            <guid isPermaLink="false">https://medium.com/p/ccd9d970fb0f</guid>
            <category><![CDATA[net-core]]></category>
            <category><![CDATA[software-design]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Patroclos Lemoniatis]]></dc:creator>
            <pubDate>Sun, 10 Dec 2023 19:19:16 GMT</pubDate>
            <atom:updated>2025-11-11T07:32:11.232Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H-NpFHLc-O12uFR-6pkT8Q.png" /></figure><h3>What is Software Architecture?</h3><p>Is a high-level description of a system’s structure, that also defines the interconnection and behavior of the sub-components that make up the system, in order to fulfill it’s functional requirements. Moreover, it abstracts the behind complex implementation details.</p><p><strong><em>Are programming languages part of the Software Architecture Design?</em></strong></p><p>No, programming languages are part of the implementation.</p><h3>Advantages of desinging and implementing Software Architecture</h3><ul><li>Handle, process and store large amount of data</li><li>Thousands of users can be served every day</li></ul><h3>Examples</h3><ul><li>Social media</li><li>Video-on-demand</li><li>Online video games</li><li>Banking systems</li></ul><h3>First step to designing a Software Architecture, is to gather the <strong>Requirements</strong></h3><p><strong>Features of the system</strong></p><ul><li>Functional Requirements :<em> “Describe what the system must do”. These requirements do not determine the system architecture</em></li></ul><p><strong>Quality Attributes</strong></p><ul><li>Non-Functional Requirements : <em>Scalability, High-Availability, Reliability, Security, Performance. These properties </em><strong><em>dictate the system architecture</em></strong></li></ul><p><strong>System Constraints</strong></p><ul><li>Limitation and boundaries: <em>Strict deadlines, Financial limitations (Limited budget)</em></li></ul><h3><strong>Examples of Requirements</strong></h3><ul><li>Functional Requirements</li></ul><p><em>“When a user clicks on a button, a modal will be loaded displaying all the available products”</em></p><ul><li>Quality Attributes</li></ul><p><em>“When a user clicks on a button, a modal will be loaded displaying all the available products within at most 100 milliseconds”</em></p><p><strong>Important!</strong></p><p><em>No single architecture can provide all the quality attributes. Some attributes contradict each other, therefore there always will be trade-offs.</em></p><p><em>Take for example, a login page which handles username/password. If the quality attribute is to login in less than 1 second the issue here is, login pages always should use SSL/TLS encryption, which will make login page slower. So, we trade-off </em><strong><em>performance </em></strong><em>with </em><strong><em>security</em></strong><em>.</em></p><p><strong>Unrealistic Quality Attributes</strong></p><ul><li>Extremely low-latency in areas where bandwidth is low</li><li>100% Availability, System can never fail</li><li>Full protection against hackers</li></ul><h3>System Constraints</h3><p>Are essentially, decisions that were made fully or partially for us, restricting our degree of freedom.</p><ul><li>These are considered pillars of software design</li><li>Providing a starting point, system is designed around them</li></ul><p>Types of System Constraints</p><ul><li><strong>Technical Constraints</strong></li></ul><p>Example: Being locked to a particular hardware vendor</p><ul><li><strong>Business Constraints</strong></li></ul><p>Example: Strict deadlines or limited budget</p><ul><li><strong>Regulatory Constraints</strong></li></ul><p>Example: GDPR (General Data Protection Rule) rules on collecting, storing and sharing users data</p><p>Constraints should be taken lightly. Specifically internal constraints should be negotiated. External constraints, like legal obligations and rules are not negotiable.</p><p>Example: If limited to a particular database vendor, we should make sure our design is not tightly coupled to that technology. Usage of different technology in the future should need minimal changes.</p><p><strong><em>In general</em></strong>, different components of the system should be loosely coupled so they can be <strong><em>replaced easily</em></strong> in the future.</p><h3>Most Important Quality Attributes</h3><h3><strong>Performance</strong></h3><p><em>Time between a client’s request and receiving a response</em></p><p><em>Response Time = Processing Time + Waiting Time</em></p><h3><strong>Scalability</strong></h3><p>Vertical Scalability: Replacing existing hardware/server with a newer better one, or upgrading existing hardware’s CPU, RAM etc …</p><p>Pros:</p><ul><li>No code changes needed</li><li>All applications can benefit from it</li><li>Migration to different machines is easy</li></ul><p>Cons</p><ul><li>We are locked to a centralized system, which cannot provide <strong>Fault tolerance</strong> and <strong>High Availability</strong></li></ul><p>Horizontal Scalability: Adding more hardware/servers to process client requests</p><p>Pros</p><p>No limitations on scalability, to the number of nodes added</p><ul><li>Easy to add, remove machines</li><li>Fault tolerance and High Availability</li></ul><p>Cons</p><ul><li>Code changes may be required</li><li>Increased complexity</li></ul><h3><strong>Availability</strong></h3><p>The fraction of time/probability a system is operationally functional and accessible to the user.</p><p>Uptime = The time the system is operational and accesible by the user</p><p>Donwtime = The time the system is unavailable to the user</p><p>Availability = Uptime / (Uptime + Downtime)</p><h3>Large scale systems architectural blocks</h3><p><strong>Load Balancing</strong></p><p>Distributing a set of requests over a set of resources. Usually, A load balancer sits between the user and the server group.</p><p><strong>Message Brokers</strong></p><p>Used for event sourcing, asynchronous requests and promote loose coupling between services. Eliminates backpressure, coming to a service.</p><p><strong>API Gateway</strong></p><p>Follows an architecture pattern called API composition. Abstracts the API implementation from the consumer application.</p><p>Advantages of using an API Gateway</p><ul><li>Seamless internal modifications</li><li>Consolidate security, authentication and authorization all in one place</li></ul><p><strong>Content Delivery Network (CDN)</strong></p><p>Network of interconnected servers that caches content close to the user. Allows quick transfer for content like javascript files, HTML pages etc …*</p><h3>Case Scenario</h3><p>Lets design a social media platform where users can post messages, comment and react to other users posts. This system needs to scale up to server millions of users everyday.</p><p><strong>Functional Requirements</strong></p><ul><li>Users must have an account to post or view other posts</li><li>Posts, can contain text, images, links or videos</li><li>Users can comment on other users posts, delete or update the comment</li><li>Users can add a reaction on other users comments, delete or update the reaction</li><li>Posts and Comments are ordered chronologically by datetime</li><li>Posts and Comments could be also ordered by number of reactions and popularity</li></ul><p><strong>What are the Non-Functional Requirements of this system?</strong></p><ul><li>Scalability — millions of users</li><li>Performance — &lt; 400ms response time</li><li>Fault Tolerance/Availability — 99.9%</li><li>Availability / Partition Tolerance — Availability over Consistency</li></ul><p><strong>Lets Design the REST APIs</strong></p><ul><li><strong>Users</strong></li></ul><p><strong>GET</strong> /users</p><p><strong>GET</strong> /users/userid</p><p><strong>POST</strong> /users/signup</p><p><strong>POST</strong> /users/login</p><ul><li><strong>Posts</strong></li></ul><p><strong>GET</strong> /posts?limit=20&amp;offset=0 <strong>[<em>use API pagination]</em></strong></p><p><strong>GET</strong> /posts/{postid}</p><p><strong>POST</strong> /posts/create</p><p><strong>PUT</strong> /posts/{postid}/update</p><p><strong>DELETE</strong> /posts/{postid}</p><ul><li><strong>Comments</strong></li></ul><p><strong>GET</strong> posts/{postid}/comments/?limit=20&amp;offset=0 <strong><em>[use API Pagination]</em></strong></p><p><strong>GET</strong> /posts/{postid}/comments/{commentid}</p><p><strong>POST</strong> /posts/{postid}/comments/create</p><p><strong>DELETE</strong> /posts/{postid}/comments/{commentid}</p><ul><li><strong>Reactions</strong></li></ul><p><strong>GET</strong> /posts/{postid}/reactions</p><p><strong>GET</strong> /posts/{postid}/comments/{commentid}/reactions/</p><p><strong>POST</strong> /posts/{postid}/reaction/create</p><p><strong>POST</strong> /posts/{postid}/comments/{commentid}/reaction/create</p><p><strong>PUT</strong> /posts/{postid}/reactions/{reactionid}</p><p><strong>PUT</strong> /posts/{postid}/comments/{commentid}/reactions/{reactionid}</p><p><strong>DELETE</strong> /posts/{postid}/reactions/{reactionid}</p><p><strong>DELETE</strong> /posts/{postid}/comments/{commentid}/reactions/{reactionid}</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H-NpFHLc-O12uFR-6pkT8Q.png" /></figure><ol><li><strong>API gateway</strong> delegates the API calls to the appropriate micro-service . In addition, to eliminate duplicate request processing, we introduce an API cache to store responses and serve them when needed.</li><li><strong>Backend services </strong>splitted to multiple <strong>Micro-Services</strong>. Each micro-service is replicated. Micro-services are making use of L<strong>oad balancing</strong> to handle multiple requests and to be fault-tolerant.</li><li>Each <strong>micro-service </strong>is connected to its own database. <strong>Users</strong> service is communicating with an <strong>SQL relational Database</strong>, the rest of the micro-services are assinged a <strong>NoSql document database </strong>to store massive amounts of data and of course to process large amount of data in the minimum amount of time.</li><li><strong>Posts</strong> service Database is being <strong>sharded</strong>, in order to handle massive amount of posts from millions of users simultaneously. <strong>Sharding</strong> means to split the database based on the primary key, from a specific range to a specific range. For example, Shard 1 consists of records from 0–10000, shard 2 10001–20000 and shard 3 20001–30000.</li><li>A meesage broker is assinged between the <strong>API gateway </strong>and <strong>Reactions</strong> service, in order to remove backpressure and buffer millions of reactions from millions of users.</li><li><strong>Ranking</strong> service is used to extract analytics from <strong>Reactions</strong> and <strong>Posts</strong> service, making use of <strong>Batch Processing</strong> for <strong>Big Data</strong>.</li><li>A distributed <strong>CDN cloud storage</strong>, is also used to store static content.</li><li><strong>Web App</strong> service is used to store the images uploaded in conjuction with users posts and comments.</li></ol><h3><strong>Summary</strong></h3><p><strong><em>Did we satisfy the Non Functional Requirements?</em></strong></p><p><strong><em>Lets summarize the points added to the Architecture Diagram</em></strong></p><ul><li><strong>Scalability — millions of users</strong></li></ul><p>Load Balancing</p><p>Database sharding</p><p>API gateway</p><p>Micro-services replication</p><ul><li><strong>Performance — &lt; 400ms response time</strong></li></ul><p>CDN cloud storage</p><p>API gateway Cache</p><p>Message broker</p><p>Micro-services replication</p><ul><li><strong>Fault Tolerance/Availability — 99.9%</strong></li><li><strong>Availability / Partition Tolerance — Availability over Consistency</strong></li></ul><p>Micro-services replication and Database replication</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ccd9d970fb0f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/software-architecture-and-designing-large-scale-systems-ccd9d970fb0f">Software Architecture and Designing Large scale systems</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Software Security, User Management, the basic stuff…]]></title>
            <link>https://medium.com/codex/user-management-the-basic-stuff-fb9b728ddf86?source=rss-ba0dd9b6831f------2</link>
            <guid isPermaLink="false">https://medium.com/p/fb9b728ddf86</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-security]]></category>
            <category><![CDATA[spring-framework]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Patroclos Lemoniatis]]></dc:creator>
            <pubDate>Mon, 14 Aug 2023 18:37:01 GMT</pubDate>
            <atom:updated>2025-09-29T10:45:48.630Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*C65Hgh6rgFNrn032.jpeg" /></figure><p>Managing user access can most times become a headache if the current security setup is failing to accommodate the access requirements of an enterprise application system.</p><p>But what is User Management and why it is so important?</p><h3>First things first!</h3><p>Authentication, Authorization and Audit Logging, are the three principles to implement and enforce <a href="https://medium.com/@patroclosdev/why-audit-logs-hibernate-envers-1ac92e52e918"><strong><em>C-I-A Confidentiality/Integrity/Availability</em></strong></a><strong>.</strong></p><ul><li><strong>Authentication </strong>for logging persons using credentials</li><li><strong>Authorization </strong>for restricting access to specific processes and <a href="https://medium.com/@patroclosdev/using-domain-driven-software-design-86de3671358c"><strong><em>Entities</em></strong></a></li><li><a href="https://medium.com/@patroclosdev/why-audit-logs-hibernate-envers-1ac92e52e918"><strong>Audit Logging</strong></a> for recording user actions</li></ul><h4>How the user management will be implemented and configured?</h4><h4>Authentication</h4><ul><li>Password expiration policy?</li><li>Locking user account when login attempts fail after certain tries?</li><li>Maximum sessions per user account allowed?</li><li>Set 2 Factor Authentication?</li></ul><h4>Authorization</h4><ul><li>How to properly and efficiently implement an [RBAC] <em>Role-Based-Access-Control,</em> by setting permissions and privileges to enable access to authorized users?</li><li>Implement [EBAC] <em>Entity-Based-Access-Control </em>?</li><li>Group user Accounts?</li><li>Protect data by filtering datasets retrieved from database based on the user group?</li></ul><h4>Audit Log</h4><ul><li>Set a retention policy?</li><li>Store Audit log history of changes and at what level of detail?</li></ul><h4>All that and more should be taken into consideration when applying security controls across an enterprise application.</h4><h4>But lets give it a try and design a basic Role Based Access Control and apply Entity Access permissions …</h4><p>What is RBAC?</p><p><strong><em>Rule-Based-Access-Control</em></strong> creates access permissions based on a predetermined set of rules that allow or deny users access within the application system regardless of their role or position in the organization.</p><p>What is EBAC?</p><p><strong><em>Entity-Based-Access-Control</em></strong> introduces Entities as a primary concept which are assigned permissions for operations like READ/CREATE/UPDATE/DELETE</p><p><strong>Let’s begin …</strong></p><p>Administrator is assigning System Roles to a group of users</p><ul><li><em>User A</em> is assigned <em>ROLE_MANAGER</em></li><li><em>User B</em> is assigned <em>ROLE_SUPERVISOR</em></li><li><em>User C</em> is assigned <em>ROLE_USER</em></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/755/1*D6fUx10VoALuCXfvTyswZw.png" /></figure><p>All these users are grouped together to form the <em>IT Department</em></p><p>Each System <em>ROLE </em>has access to System Processes</p><p><em>User C</em> has the lowest, in hierarchy, role, consequently has access to <em>Process C</em>, but has no access to execute <em>Process A</em> nor <em>Process B</em>.</p><p><em>User B</em>, has access to both Process B and Process C</p><p><em>User A</em>, as <em>MANAGER</em>, has access to execute all 3 processes</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/817/1*WdJaivRigI-c2hP6hz1IaQ.png" /></figure><p>Defining Entity Access Policies as per above, should enforce <em>User C </em>to HAVE <em>Read </em>and <em>Create </em>PERMISSION on <em>Entity X.</em></p><p><em>User B</em>, as SUPERVISOR, should have PERMISSION to <em>READ</em>, <em>CREATE </em>and UPDATE <em>Entity X</em>.</p><p><em>User A</em> as MANAGER, has PERMISSION to <em>READ, CREATE, UPDATE</em> and <em>DELETE Entity X</em>.</p><p><strong><em>What has been achieved here is securing System Processes and data from unauthorized access and manipulation. Avoid information leaks or improper modification by potentially malicious users.</em></strong></p><h3>A Sample Implementation</h3><p>Let’s see an example of user management implemented with Java Spring MVC Framework.</p><p>There are 3 users with 2 Roles, ROLE_ADMIN and ROLE_USER</p><p>user Admin is assigned ROLE_ADMIN</p><p>user A and user B are assigned ROLE_USER</p><p>Admin user assigns specific permissions to user’s A Role</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5861OR2zjO2_9x3e8a3Osw.png" /><figcaption>Administrator edits ROLE User to grant access</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vklF0T3jzsuKxxDy_O8qLQ.png" /><figcaption>Administrator gives access for READ/CREATE on Entity [Article], on ROLE_USER</figcaption></figure><h3>Scenario A</h3><p>user A creates a new Article record</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Knhj56IRqzrWPPOejJ52GQ.png" /><figcaption>userA with ROLE User logs in</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DFXqorRjuFe6-8bXFk3W6g.png" /><figcaption>userA creates a new Article</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8JLlgHYpiZrD4-T-OLRTfw.png" /><figcaption>userA tries to edit the Article</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K_8MiI5zLASXrRJyf5WVDA.png" /><figcaption>userA is denied updating the Article, as the ROLE_USER has no permission to update entity [Article]</figcaption></figure><h3>Scenario B</h3><p>Admin retrieves the Audit Log and reviews the changes …</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/977/1*ekiBJ0MVBKk74KEfs-xXSw.png" /><figcaption>Admin user logs in</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KylezlePc3i9Z7BUWWCDcg.png" /><figcaption>Audit Log as per the creation of the new entity [Article]</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B1w7gNwwurEH5ii2uk51kQ.png" /><figcaption>Audit Log attribute details as per the creation of the new entity [Article]</figcaption></figure><h3>Scenario C</h3><p>User B logs in and searches Articles to view the new Article, created by user A. But user A and user B belong to different groups.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q2mpJjd5WnoZHTWL6Lqytw.png" /><figcaption>user A belongs to group AUTHORS</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rZYGGkStdNmUokFMCY7CBA.png" /><figcaption>user B belongs to group DESIGNER</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d9p6ZaeG03rFnDNGu1S8eQ.png" /><figcaption>user B has no permission to retrieve Article created by user B, since they belong to 2 different groups</figcaption></figure><p>Code can be found in the below github repository …</p><p><a href="https://github.com/patroklos83/SpringMVC">GitHub - patroklos83/SpringMVC: sample template SpringMVC webapp</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fb9b728ddf86" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/user-management-the-basic-stuff-fb9b728ddf86">Software Security, User Management, the basic stuff…</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Audit Logs? (Hibernate Envers)]]></title>
            <link>https://patroclosdev.medium.com/why-audit-logs-hibernate-envers-1ac92e52e918?source=rss-ba0dd9b6831f------2</link>
            <guid isPermaLink="false">https://medium.com/p/1ac92e52e918</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[software-security]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[software-architecture]]></category>
            <dc:creator><![CDATA[Patroclos Lemoniatis]]></dc:creator>
            <pubDate>Sun, 02 Jul 2023 10:27:20 GMT</pubDate>
            <atom:updated>2023-07-02T10:27:20.268Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*321XUDLjpul1ofdV.jpeg" /><figcaption>image by freephotocc on pixabay.com</figcaption></figure><h3><strong>Lets start with the basics. </strong>What are Audit Logs?</h3><p>Audit logging is the process of capturing user activity across an application system. Specifically event name, event date and time, user who executed the event and what was impacted from the event.</p><p>Each application has processes that are being executed by users to save and update data. Every time a change is applied on a data entity, a record is created or updated in the database.</p><p>These activities produce event/audit logs, that are required by the system administrators in order to have an overall picture of the application’s activity.</p><p>Consider, the scenario where sensitive data have been deleted or updated resulting in a “damaging” event. If no trace is left by these “invalid” events, no investigation is possible and probably no data fix can be applied to revert to the correct data.</p><p>Another, scenario, is where an unauthorized user is deleting or updating the data. Audit logs effectively can pinpoint the culprit, giving the exact date, time, and what data has the user changed.</p><h3>C-I-A Confidentiality, Integrity, and Availability</h3><p>The basis for securing an application system</p><ul><li><strong>Confidentiality</strong>: Access to data has to be controlled to prevent unauthorized sharing of data. Enable access control policies, encrypt data, and use multi-factor authentication.</li><li><strong>Integrity</strong>: Data should be trustworthy and free of tampering. Usage of hashing, encryption, digital certificates, or digital signatures.</li><li><strong>Availability</strong>: Data should be available to users at all times. Organizations can use redundant networks, servers, and applications. These can be programmed to become available when the primary system has been disrupted or broken, as to serve the data needs of the users.</li></ul><p>To achieve the C-I-A triad we have to enforce the below principles. <em>Lets focus on Auditing…</em></p><p><em>Loren Kohnfelder, 2021, Designing Secure Software: A Guide for Developers</em></p><blockquote><strong>Authentication</strong>: High-assurance determination of the identity of a principal</blockquote><blockquote><strong>Authorization</strong>: Reliably only allowing an action by an authenticated principal</blockquote><blockquote><strong>Auditing</strong>: Maintaining a reliable record of actions by principals for inspection</blockquote><blockquote>Auditing</blockquote><blockquote>In order for an organization to audit system activity, the system must produce a reliable log of all events that are critical to maintaining security. These include authentication and authorization events, system startup and shutdown, software updates, administrative accesses, and so forth. Audit logs must also be tamper-resistant, and ideally even difficult for administrators to meddle with, to be considered fully reliable records. Auditing is a critical leg of the Gold Standard, because incidents do happen, and authentication and authorization policies can be flawed. Auditing can also serve as mitigation for inside jobs in which trusted principals cause harm, providing necessary oversight.³</blockquote><h3>Why use Audit Logs?</h3><h3><strong>* System Troubleshooting</strong></h3><p>Audit logs provide vital information of system processes which in turn could provide assistance to the performance enhancement or bug fixing of an application system.</p><h3>* Accountability</h3><p>Audit logs help an organization capture security and authentication as well as privileged activity information. This promotes user accountability for their actions across an application system. To do this effectively, audit logs have to be captured and stored regularly to show actions before and after an event has occurred.</p><h3>* Reconstruction of events</h3><p>Audit logs may also be used to “replay” events to help understand how a damaging event has occurred. Logs are configured to capture detailed data changes, therefore data at a certain point of time, can sometimes be reconstructed from logs.</p><h3>* Providing Legal Validity</h3><p>Audit logs can provide proof of a user actions.</p><h3>What do Audit Logs capture?</h3><p>Audit logs capture the following type of information</p><ul><li>Event Name</li><li>Brief description of the event</li><li>Execution Date and Time</li><li>User who executed the event</li><li>Application/IP/Device/Entity that was impacted</li><li>Application/IP/Device from where the execution of event occurred</li><li>Custom tags like Severity of the event</li></ul><h3>Lets go though a real application example</h3><p>User logs into the application …</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CzoeqDJT_NkC08FukkYktw.png" /><figcaption>Here is the audit log of the user log-in</figcaption></figure><p>User creates a new Article</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/901/1*dZnL1NbKEAnhcT1yCibXEw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/896/1*RxzW7vtlXMuMbPQ4c_4dMA.png" /><figcaption>Here is the audit log of the new Article which was created</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rLwhKjF7-vVkcTRrzs1h9A.png" /><figcaption>Detailed info of the properties changed in relation to the event for the specific entity affected</figcaption></figure><p>User updates the Article. Edits the <strong><em>author </em></strong>and adds a new <strong><em>Comment </em></strong>…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/692/1*8EQQojXc_Yk26fCEDe33eA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*5c3CLK0YKKufIRBqNkFVfA.png" /><figcaption>Here is the Audit log of the update event and the affected entities</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HViE4BrbGRzp0c6fQsn8YA.png" /><figcaption>Detailed info of the properties affected in relation to the update event for the specific entity affected</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*J5Gyw-f-ypGKpYf6D6kvPQ.png" /><figcaption>Here is the new <strong>ManyToOne (ArticleComment) </strong>child entity created from the update of the parent entity Article</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Hd9z0_dzijLSxddBfTdqaw.png" /><figcaption>Newly created <strong>ManyToOne (ArticleComment</strong>) child entity event detailed info</figcaption></figure><h3>Changes as recorded in the database level</h3><p><em>Here are the AUDIT Tables</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/901/1*fM4HRuayYAJARfaSjYQ23g.png" /><figcaption>Articles_AUD table</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Tb-0fEMrgsMsDlW6OvyIyA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pCALKjlauqZB2NF5xwd-nQ.png" /><figcaption>ArticleComments_AUD table</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Eq9HHj1WqR2ccsKFapT9Ig.png" /></figure><p>So each time an entity is created/modified or deleted, a record is created in the corresponding audit table, which has a unique revision number [similar to Subversion/Git versioning]. This makes it possible to <strong><em>reconstruct/checkout</em></strong> an entity as it was at a specific point in time.</p><h4>Few words in regards to the above example</h4><p><em>Above example is built with Java </em><a href="https://spring.io/"><strong><em>Spring Framework</em></strong></a><em> application [Spring MVC v6, java 17], uses </em><a href="https://hibernate.org/orm/"><strong><em>Hibernate ORM</em></strong></a><em> v6.1.6 and </em><a href="https://hibernate.org/orm/envers/"><strong><em>Hibernate Envers</em></strong></a><em> v6.1.6 for Activity logging.</em></p><h3>Hibernate Envers¹</h3><p>It is a module that works in conjunction with Hibernate ORM library to help implement core audit logging functionality, to maintain detailed revision logs of creation and update events on model entities.</p><p>As per the example above, this is the code used by the model Entities to handle Audit changes. Please note for every entity table there is a corresponding *_AUD (audit table) to hold the history revisions.</p><pre>CREATE TABLE ARTICLES (<br>  id bigint NOT NULL AUTO_INCREMENT,<br>  title varchar(200) NOT NULL,<br>  category varchar(100) NULL,<br>  summary varchar(200) NULL,<br>  author varchar(100) NULL,<br>  createdBy bigint,<br>  createdDate timestamp NOT NULL,<br>  lastModifiedBy bigint,<br>  lastModifiedDate timestamp NOT NULL,<br>  lastUpdatedByprocessId varchar(200) NULL,<br>  isdeleted bigint NOT NULL default 0,<br>  version bigint NOT NULL,<br>  PRIMARY KEY (Id)<br>);<br><br>CREATE TABLE ARTICLES_AUD (<br>  id bigint NOT NULL,<br>  title varchar(200),<br>  title_mod boolean,<br>  category varchar(100),<br>  category_mod boolean,<br>  summary varchar(200),<br>  summary_mod boolean,<br>  author varchar(100),<br>  author_mod boolean,<br>  createdBy bigint,<br>  createdBy_mod boolean,<br>  createdDate timestamp,<br>  createdDate_mod boolean,<br>  lastModifiedBy bigint,<br>  lastModifiedBy_mod boolean,<br>  lastModifiedDate timestamp,<br>  lastModifiedDate_mod boolean,<br>  version bigint,<br>  version_mod boolean,<br>  lastUpdatedByprocessId varchar(200),<br>  lastUpdatedByprocessId_mod boolean,<br>  isdeleted bigint,<br>  isdeleted_mod boolean,<br>  REV INTEGER NOT NULL,<br>  REVTYPE INTEGER NOT NULL,<br>  PRIMARY KEY (Id, REV)<br>);<br><br>CREATE TABLE ARTICLECOMMENTS (<br>  id bigint NOT NULL AUTO_INCREMENT,<br>  comment varchar(max) NOT NULL,<br>  article_id bigint NULL,<br>  createdBy bigint,<br>  createdDate timestamp NOT NULL,<br>  lastModifiedBy bigint,<br>  lastModifiedDate timestamp NOT NULL,<br>  lastUpdatedByprocessId varchar(200) NULL,<br>  isdeleted bigint NOT NULL default 0,<br>  version bigint NOT NULL,<br>  PRIMARY KEY (Id)<br>);<br><br>CREATE TABLE ARTICLECOMMENTS_AUD (<br>  id bigint NOT NULL,<br>  comment varchar(max) NULL,<br>  comment_mod boolean,<br>  article_id bigint NULL,<br>  article_id_mod boolean,<br>  createdBy bigint,<br>  createdBy_mod boolean,<br>  createdDate timestamp,<br>  createdDate_mod boolean,<br>  lastModifiedBy bigint,<br>  lastModifiedBy_mod boolean,<br>  lastModifiedDate timestamp,<br>  lastModifiedDate_mod boolean,<br>  version bigint,<br>  version_mod boolean,<br>  lastUpdatedByprocessId varchar(200),<br>  lastUpdatedByprocessId_mod boolean,<br>  isdeleted bigint,<br>  isdeleted_mod boolean,<br>  REV INTEGER NOT NULL,<br>  REVTYPE INTEGER NOT NULL,<br>  PRIMARY KEY (Id, REV)<br>);<br><br>CREATE TABLE CITATIONS (<br>  id bigint NOT NULL AUTO_INCREMENT,<br>  title varchar(200) NOT NULL,<br>  link varchar(100) NULL,<br>  citationtype varchar(200) NULL,<br>  createdBy bigint,<br>  createdDate timestamp NOT NULL,<br>  lastModifiedBy bigint,<br>  lastModifiedDate timestamp NOT NULL,<br>  lastUpdatedByprocessId varchar(200) NULL,<br>  isdeleted bigint NOT NULL default 0,<br>  version bigint NOT NULL,<br>  PRIMARY KEY (Id)<br>);<br><br>CREATE TABLE CITATIONS_AUD (<br>  id bigint NOT NULL,<br>  title varchar(200),<br>  title_mod boolean,<br>  link varchar(100) NULL,<br>  link_mod boolean,<br>  citationtype varchar(200) NULL,<br>  citationtype_mod boolean,  <br>  createdBy bigint,<br>  createdBy_mod boolean,<br>  createdDate timestamp,<br>  createdDate_mod boolean,<br>  lastModifiedBy bigint,<br>  lastModifiedBy_mod boolean,<br>  lastModifiedDate timestamp,<br>  lastModifiedDate_mod boolean,<br>  version bigint,<br>  version_mod boolean,<br>  lastUpdatedByprocessId varchar(200),<br>  lastUpdatedByprocessId_mod boolean,<br>  isdeleted bigint,<br>  isdeleted_mod boolean,<br>  REV INTEGER NOT NULL,<br>  REVTYPE INTEGER NOT NULL,<br>  PRIMARY KEY (Id, REV)<br>);<br><br>CREATE TABLE ARTICLE_CITATION (<br>  article_id bigint not null, <br>  citation_id bigint not null,<br>  constraint fk_article_citation_article foreign key(article_id) references articles(id),<br>  constraint fk_article_citation_citation foreign key(citation_id) references citations(id)<br>);<br><br>CREATE TABLE ARTICLE_CITATION_AUD (<br>  article_id bigint not null, <br>  citation_id bigint not null,<br>  REV INTEGER NOT NULL,<br>  REVTYPE INTEGER NOT NULL,<br>  constraint fk_article_citation_article2 foreign key(article_id) references articles(id),<br>  constraint fk_article_citation_citation2 foreign key(citation_id) references citations(id)<br>);<br><br>CREATE TABLE REVINFO (<br>    REV INTEGER GENERATED BY DEFAULT AS IDENTITY,<br>    REVTSTMP BIGINT,<br>    PRIMARY KEY (REV)<br>);</pre><pre>@Audited<br>@Entity<br>@Table(name=&quot;articles&quot;)<br>public class Article extends BaseO  { <br><br> private static final long serialVersionUID = 1L;<br><br> @Id<br> @NotAudited<br> @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = &quot;articles_sequence&quot;)<br> @SequenceGenerator(name = &quot;articles_sequence&quot;, sequenceName = &quot;articles_sequence&quot;, allocationSize = 1)<br> @Column(name=&quot;id&quot;, updatable = false)<br> private long id;  <br><br> @Audited(withModifiedFlag = true)<br> @Column(name=&quot;title&quot;) <br> private String title;<br><br> @Audited(withModifiedFlag = true)<br> @Column(name=&quot;category&quot;) <br> private String category;<br><br> @Audited(withModifiedFlag = true)<br> @Column(name=&quot;summary&quot;) <br> private String summary;<br><br> @Audited(withModifiedFlag = true)<br> @Column(name=&quot;author&quot;) <br> private String author;<br><br> @Audited<br> @AuditJoinTable(name = &quot;article_citation_aud&quot;)<br> @ManyToMany(cascade=CascadeType.MERGE, fetch=FetchType.EAGER)<br> @JoinTable(<br>   name=&quot;article_citation&quot;,<br>   joinColumns={@JoinColumn(name=&quot;article_id&quot;)},<br>   inverseJoinColumns={@JoinColumn(name=&quot;citation_id&quot;)})<br> private List&lt;Citation&gt; citations;<br><br> @Audited<br> @AuditJoinTable(name = &quot;articlecomments_aud&quot;)<br> @OneToMany(mappedBy=&quot;article&quot;, fetch=FetchType.EAGER)<br> private List&lt;ArticleComment&gt; comments;<br><br>}  </pre><pre><br>@Audited<br>@Entity<br>@Table(name=&quot;articlecomments&quot;)<br>public class ArticleComment extends BaseO { <br><br> private static final long serialVersionUID = 1L;<br> <br> @Id<br> @NotAudited<br> @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = &quot;articlecomments_sequence&quot;)<br> @SequenceGenerator(name = &quot;articlecomments_sequence&quot;, sequenceName = &quot;articlecomments_sequence&quot;, allocationSize = 1)<br> @Column(name=&quot;id&quot;, updatable = false)<br> private long id;  <br><br> @Audited(withModifiedFlag = true)<br> @Column(name=&quot;comment&quot;) <br> private String comment;<br><br> @Audited(withModifiedFlag = true, modifiedColumnName = &quot;article_id_mod&quot;)<br> @ManyToOne<br> @JoinColumn(name=&quot;article_id&quot;)<br> private Article article;<br><br>}  </pre><pre>public class AuditEnversRepository {<br><br>@jakarta.persistence.PersistenceContext <br> protected EntityManager em;<br><br> public List&lt;Object[]&gt; getEntityRevisionsByProcessId(Class&lt;? extends BaseO&gt; o, Long id, String processId) {<br>  AuditReader auditReader = AuditReaderFactory.get(em);<br>  List&lt;Object[]&gt; revResults  = auditReader.createQuery()<br>  .forRevisionsOfEntityWithChanges(o, false) <br>  .add(AuditEntity.property(&quot;lastUpdatedByprocessId&quot;).eq(processId))<br>  .add(AuditEntity.property(&quot;id&quot;).eq(id))<br>  .getResultList();  <br>  return revResults;<br> }<br><br>}</pre><p><strong><em>Hibernate Envers</em></strong> provides a convenient <a href="https://docs.jboss.org/hibernate/orm/current/quickstart/html_single/#tutorial_envers">AuditReader² </a>API class to retrieve entity changes.</p><p>[1] <a href="https://hibernate.org/orm/envers/">https://hibernate.org/orm/envers/</a></p><p>[2]<a href="https://docs.jboss.org/hibernate/orm/current/quickstart/html_single/#tutorial_envers">Hibernate Envers Tutorial</a></p><p>[3] Loren Kohnfelder, 2021, <em>Designing Secure Software: A Guide for Developers</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1ac92e52e918" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Easily create a friendly News Agency UI, using .Net Core MVC]]></title>
            <link>https://patroclosdev.medium.com/easily-create-a-friendly-news-agency-ui-using-net-core-mvc-f002062aba92?source=rss-ba0dd9b6831f------2</link>
            <guid isPermaLink="false">https://medium.com/p/f002062aba92</guid>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[dotnet]]></category>
            <dc:creator><![CDATA[Patroclos Lemoniatis]]></dc:creator>
            <pubDate>Tue, 18 Apr 2023 19:27:43 GMT</pubDate>
            <atom:updated>2023-04-18T19:27:43.844Z</atom:updated>
            <content:encoded><![CDATA[<h3>Easily create a friendly News Agency UI, using .Net Core MVC</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QKFPm5REExp_Fp0ueiZIbA.jpeg" /><figcaption>image from pixabay by TheAngryTeddy</figcaption></figure><p>In this blog,</p><p>we will cover how easy it is to create a sample web application User interface using .NET MVC, using NHibernate, SQLite, Model AutoMapper and Razor pages.</p><h3>What is MVC?</h3><p>MVC, which stands for Model-View-Controller, is a software development architecture pattern used to structure and organize code in web applications. It separates an application’s concerns into three components: the model, view, and controller.</p><h3>Why use .Net Core?</h3><p>There are several reasons why you might consider using .NET Core</p><ol><li>Cross-platform support: .NET Core runs on multiple operating systems, including Windows, Linux, and macOS</li><li>Open-source and community-driven</li><li>Integration with other Microsoft technologies: .NET Core integrates well with other Microsoft technologies such as Azure, Visual Studio, and SQL Server, making it easy to build, deploy, and manage applications within the Microsoft ecosystem.</li></ol><h3>Razor Pages</h3><p>Razor Pages allows developers to build server-side web pages using the Razor syntax, which is a combination of HTML markup and server-side code. Each web page is represented by a -page model- class that contains the code needed to generate the HTML markup. The page model class is defined in a C# code file and is associated with a Razor view file that contains the HTML markup and Razor syntax for the page.</p><h3>NHibernate</h3><p>NHibernate is an open-source object-relational mapping (ORM) framework for the .NET platform. It provides a bridge between the object-oriented programming paradigm of .NET and the relational database world.</p><p>It provides a wide range of features to help developers manage the persistence of data, including support for lazy loading, caching, and transaction management.</p><p>Some advantages of using NHibernate are:</p><ol><li>Abstraction of database details: NHibernate provides a high-level, object-oriented interface for working with database data.</li><li>Increased productivity: NHibernate reduces the amount of boilerplate code required to manage database data, which can speed up development time.</li><li>Improved maintainability: NHibernate provides a clear separation between the data access layer and the business logic layer of an application, which makes it easier to maintain and update the codebase over time.</li><li>Support for multiple database platforms: NHibernate supports a wide range of database platforms, including Microsoft SQL Server, Oracle, MySQL, and PostgreSQL.</li></ol><h3>SQLite database</h3><p>It is a lightweight and self-contained database engine that can be embedded into applications to store data in a local file. SQLite is open source and free to use, and it supports SQL (Structured Query Language) syntax for creating, querying, and managing data stored in the database.</p><p>SQLite is widely used in various types of software applications, such as desktop and mobile applications, web browsers, and operating systems. SQLite is also known for its reliability, stability, and scalability, which makes it an ideal choice for many software developers.</p><h3>What is AutoMapper?</h3><p>AutoMapper is a library that allows automatic mapping from one object to another, eliminating extra code to be written every time a mapper is required to map an entity to a DTO and vice-versa.</p><h3><strong>Lets see the UI example</strong></h3><p>Suppose a News Agency, needs to store, retrieve and edit new and existing articles.</p><p>The solution, therefore, is to create a Web Application with an Articles summary and detail page.</p><p>Summary Page: Display all the non deleted articles in a table format</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ekLLxgEwfWGj5uWtPp2lhw.png" /></figure><p>Detail Page: Open a new page to edit a specific article or create a new article</p><p><em>This is the Read Mode where with the use of Razor syntax, the components are shown as Labels instead of TextBoxes.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K7-oLpQYVU7ODcsnxlOFwA.png" /></figure><p><em>When the Edit link is clicked, the Label components are replaced with TextBoxes.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QX92_RSMxT2M2YHwXflhKg.png" /></figure><p>Fell free to grab a copy of the source code and play !</p><p><a href="https://github.com/patroklos83/DotNet-Core-MVC-app">GitHub - patroklos83/DotNet-Core-MVC-app: Sample ASP.NET core Web application using Model - View - Controller design</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f002062aba92" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>