<?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 Angelo Ferreira on Medium]]></title>
        <description><![CDATA[Stories by Angelo Ferreira on Medium]]></description>
        <link>https://medium.com/@angelozero?source=rss-f3da207c5d78------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*H0K1JTVhNl-1xPmUqxolJw.jpeg</url>
            <title>Stories by Angelo Ferreira on Medium</title>
            <link>https://medium.com/@angelozero?source=rss-f3da207c5d78------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 03:37:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@angelozero/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[Evaluating AI Agents with MLflow 3.0 and LLM Judges]]></title>
            <link>https://towardsdev.com/evaluating-ai-agents-with-mlflow-3-0-and-llm-judges-288df718d4d8?source=rss-f3da207c5d78------2</link>
            <guid isPermaLink="false">https://medium.com/p/288df718d4d8</guid>
            <category><![CDATA[llm-judge]]></category>
            <category><![CDATA[ollama]]></category>
            <category><![CDATA[mlflow]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[langgraph]]></category>
            <dc:creator><![CDATA[Angelo Ferreira]]></dc:creator>
            <pubDate>Mon, 11 May 2026 02:08:37 GMT</pubDate>
            <atom:updated>2026-05-12T12:03:53.859Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ie3AK3qCfQXJVDY7Nze4WA.png" /></figure><p><em>This article documents the journey of building an audit system for AI agents, using </em><strong><em>LangGraph</em></strong><em> for orchestration and </em><strong><em>MLflow</em></strong><em> for governance and metrics.</em></p><h3>1. Why Evaluate?</h3><p>In traditional systems, 2 + 2 is always 4. In generative AI, the answer can vary. How do you ensure that a Billing Agent doesn&#39;t give an undue discount or invent a due date?</p><p>The solution is not to look at logs one by one, but to build an <strong>Automated Evaluation Pipeline</strong>.</p><h3>2. LangGraph</h3><p>Before evaluating, we need something to run. In the main.py file, we use <strong>LangGraph</strong> to create a flow where a &quot;Supervisor&quot; decides who solves the problem.</p><h4>The Smart Router</h4><p>The Graph works like a telephone exchange. It receives the question and routes it to the right specialist.</p><pre># Enable automatic tracing for LangChain/LangGraph (MLflow 3.0)<br>mlflow.langchain.autolog()<br><br># Excerpt from main.py: Defining the routing logic<br>def supervisor(state: AgentState) -&gt; Literal[&quot;billing&quot;, &quot;tech&quot;]:<br>    last_message = state[&quot;messages&quot;][-1].content.lower()<br><br>    if any(word in last_message for word in [&quot;bill&quot;, &quot;payment&quot;, &quot;invoice&quot;]):<br>        return &quot;billing&quot; # Routes to the RAG specialist<br>    return &quot;tech&quot;    # Routes to tech support</pre><p><strong><em>What we learn here:</em></strong><em> At this stage, MLflow performs </em><strong><em>Observability</em></strong><em> through </em><em>autolog(). It records the path (Trace) and response time, but does not yet say whether the answer is correct.</em></p><h3>3. Ground Truth (eval_data.py)</h3><p>To judge, we need a “truth”. In the eval_data.py file, we define what we expect from the model.</p><pre>eval_dataset = [<br>    {<br>        &quot;inputs&quot;: {&quot;query&quot;: &quot;What is Angelo&#39;s invoice amount?&quot;},<br>        &quot;outputs&quot;: &quot;The amount is R$ 350.00...&quot;, # Response generated by the model<br>        &quot;expectations&quot;: {<br>            &quot;expected_facts&quot;: [<br>                &quot;Amount of R$ 350.00&quot;,<br>                &quot;Customer name: Angelo&quot;<br>            ]<br>        }<br>    }<br>]</pre><p><strong>Common question:</strong> <em>“Do I need to look at the database (Pinecone) here?”</em></p><p><strong>Answer:</strong> Not necessarily. At this stage, expected_facts is your <strong><em>Business Contract</em></strong><em>.</em> <br>If the data is not there, the judge will say it is wrong, regardless of what the database delivered.</p><h3>4. The Judges: LLM-as-a-Judge</h3><p>This is where the sophistication comes in. We use one LLM to read the response of another. In the project, we use two profiles: <strong>Qwen</strong> (Generalist) and <strong>Llama</strong> (Strict Auditor).</p><h4>Judge 1: Qwen (The Essay Teacher)</h4><p>It uses MLflow’s default prompt to understand whether, semantically, the response makes sense.</p><h4>Judge 2: Llama (The Tax Auditor)</h4><p>Here we implement custom logic. It analyzes fact by fact and only approves if <strong>all</strong> are present.</p><pre>@scorer<br>def judge_llama(inputs, outputs, expectations):<br>    # ... prompt capture logic ...<br>    <br>    # Normalization: Llama evaluates fact by fact (e.g.: yes|no|yes)<br>    verdicts = [v.strip() for v in raw_result.split(&quot;|&quot;)]<br>    <br>    # &quot;All or Nothing&quot; logic: Only &quot;yes&quot; if EVERYTHING is &quot;yes&quot;<br>    final_value = &quot;yes&quot; if all(v == &quot;yes&quot; for v in verdicts) else &quot;no&quot;<br>    <br>    return Feedback(value=final_value, rationale=rationale, ...)</pre><h3>5. Comparison and Visualization (Dashboard)</h3><p>With MLflow running in Docker, we access the dashboard to compare the judges.</p><h4>Tone vs. Precision</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B882lC_huiSn-In6XvHd9g.png" /></figure><ul><li><strong>If Qwen gives “Score 5” and Llama gives “No”:</strong> The response is well-written and polite, but is missing an essential technical piece of data (precision error).</li><li><strong>If Llama gives “Yes” and Qwen gives “Score 2”:</strong> The data is correct, but the response is poorly formatted or confusing (tone error).</li></ul><h4>The Role of Temperature 0.0</h4><p>For all judges, we set temperature=0.0.</p><p><strong><em>Why? … </em></strong><em>We want determinism. A judge cannot “wake up in a good mood” and give different scores for the same text. It must be a consistent validator.</em></p><h3>6. Solving Local Issues (Monkey-Patching)</h3><p>Since we run local models via <a href="https://ollama.com/"><strong>Ollama</strong></a>, processing time can exceed the default 60-second timeout of the libraries. To prevent the system from failing, we apply a technical “patch”:</p><pre># Increasing the timeout to 5 minutes (300s) to support local Ollama<br>def _patched_send_request(endpoint, headers, payload):<br>    response = _requests.post(..., timeout=300)<br>    return response.json()<br><br>_model_utils._send_request = _patched_send_request</pre><h3>Conclusion: The development cycle</h3><ol><li><strong>Develop</strong> the Graph in LangGraph.</li><li><strong>Monitor</strong> execution with automatic Traces.</li><li><strong>Evaluate</strong> the final result against the Ground Truth.</li><li><strong>Audit</strong> the database (RAG) if the judges point out failures.</li></ol><h3>Info</h3><ul><li><a href="https://ollama.com/">Ollama</a></li><li><a href="https://www.pinecone.io/">Pinecone</a></li><li><a href="https://mlflow.org/docs/latest/genai/eval-monitor/quickstart/">MLflow: AI Engineering Platform for LLMs and Agents</a></li><li><a href="https://www.youtube.com/watch?v=PZBUaVxdY0U">Creating LLM judges to Measure Domain-Specific Agent Quality — By Databricks</a></li><li><a href="https://www.udemy.com/course/mlflow-course/?srsltid=AfmBOooYmaQNFUc-iLtj27X1bps3-6Ohnxp6Y2zVHRo9zmVnNDrZ544Y">MLflow in Action — Master the art of MLOps using MLflow tool — By J Garg — Real Time Learning</a></li><li><a href="https://www.youtube.com/watch?v=8LBL28JqXfw&amp;t=7s">LangChain e LangGraph: O Guia Definitivo Para IA Com Python — By Otávio Miranda</a></li></ul><h3>Github Project</h3><ul><li><a href="https://github.com/angelozero/ml-flow">AngeloZero — MLflow</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=288df718d4d8" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/evaluating-ai-agents-with-mlflow-3-0-and-llm-judges-288df718d4d8">Evaluating AI Agents with MLflow 3.0 and LLM Judges</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Microsoft Presidio, LangChain and LangGraph]]></title>
            <link>https://medium.com/@angelozero/microsoft-presidio-langchain-and-langgraph-01779b4f2b45?source=rss-f3da207c5d78------2</link>
            <guid isPermaLink="false">https://medium.com/p/01779b4f2b45</guid>
            <category><![CDATA[langgraph]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[microsoft-presidio]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[langchain]]></category>
            <dc:creator><![CDATA[Angelo Ferreira]]></dc:creator>
            <pubDate>Mon, 06 Apr 2026 01:42:39 GMT</pubDate>
            <atom:updated>2026-04-06T01:42:39.529Z</atom:updated>
            <content:encoded><![CDATA[<p>A simple project showing how to mask <strong>PII</strong> data for <strong>LLMs</strong> and orchestrate <strong>RAG </strong>with<strong> LangGraph.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MSGkLtDST9iC722ObIMrMw.png" /></figure><p>This project features a <strong>Credit Audit System</strong> built on <strong>Privacy-by-Design</strong> principles. The solution leverages a <strong>RAG (Retrieval-Augmented Generation)</strong> architecture to classify financial risks by cross-referencing requests with internal banking policies. The technical core is the <strong>data governance layer</strong>: by integrating <strong>LiteLLM and Microsoft Presidio</strong>, PII masking (such as CPFs) is handled natively at the infrastructure level. This ensures that sensitive data never reaches the LLM, achieving robust privacy without a single line of custom sanitization logic in the Python application code.</p><p>In this article, I will demonstrate how this architecture functions, covering everything from agent orchestration to human-in-the-loop validation.</p><p><strong><em>Note</em></strong>: <strong>CPF</strong><em> </em>it&#39;s a unique tax identification number required for almost all financial and legal transactions in Brazil</p><h3>Flow Orchestration</h3><pre>User sends CPF + amount<br>        │<br>        ▼<br>FastAPI receives the request<br>        │<br>        ▼<br>RAG retrieves credit policy excerpts from ChromaDB<br>        │<br>        ▼<br>LLM (Llama 3.2) analyzes and classifies the client<br>        │<br>        ▼<br>LangGraph decides: automatic approval or pause for the manager<br>        │<br>        ▼<br>JSON response with report + masked CPF (XXX.***.***-XX)</pre><p>The CPF 123.456.789-00 never reaches the AI model. It is intercepted and replaced with XXX.***.***-XX at the infrastructure layer.</p><h3>RAG — The AI Responds Based on Real Documents</h3><p>RAG (Retrieval-Augmented Generation) is the technique that prevents the AI from making up answers. Instead of relying on the model’s generic knowledge, the application retrieves real excerpts from the credit policy and provides them as context.</p><pre>def execute(cpf, amount):<br>    # 1. Build the query<br>    query = (<br>        f&quot;Perform the credit audit for the amount of R$ {amount} &quot;<br>        f&quot;and CPF {cpf}. Check the score range classification, &quot;<br>        &quot;possible impediment factors from Item 3 and &#39;Geographic Override&#39; rules from Item 7. &quot;<br>        &quot;Return the client pattern and the report according to the Item 10 protocol.&quot;<br>    )<br><br>    # 2. Retrieve the 3 most relevant excerpts from the policy in ChromaDB<br>    results = get_results_by_relevance_score(query)<br><br>    # 3. Combine the excerpts into a context string<br>    context = get_context_by_results(results)<br>    <br>    # 4. Send context + query to the LLM → receive risk analysis<br>    analysis_risk_description = get_client_analysis_risk_descritpion(context, query)<br>    <br>    # 5. Build the final audit prompt<br>    prompt = get_risk_analysis_prompt(cpf, amount, analysis_risk_description)<br>    <br>    # 6. Configure the LLM with tool + structured response<br>    llm = get_llm_with_tools(validate_credit_policy)<br>    <br>    # 7. Send and receive the final response<br>    response = llm.invoke(prompt[&quot;messages&quot;])<br>    <br>    return {&quot;data&quot;: response}</pre><h3>How the Search Works Under the Hood</h3><p>The credit policy document (PDF) was previously split into <strong>chunks</strong> of 2000 characters with an overlap of 500. Each chunk was transformed into a numerical vector (embedding) and stored in <strong>ChromaDB</strong>.</p><p>When a query arrives, it is also converted into a vector. ChromaDB compares the vectors and returns the most semantically similar chunks — not by keywords, but by meaning.</p><pre># src/service/generate_chunks_service.py — how chunks are created<br>spliter = RecursiveCharacterTextSplitter(<br>    chunk_size=2000, chunk_overlap=500, length_function=len, add_start_index=True<br>)</pre><p>The 500-character overlap ensures that sentences at the boundary between two chunks are not lost.</p><h3>Tool and Structured Response</h3><p>The LLM doesn’t just generate text — it can call a Python tool during the analysis:</p><pre># src/tools/validate_credit_policy_tool.py<br>@tool<br>def validate_credit_policy(score: float, regional_risk: bool, has_impediment: bool) -&gt; str:<br>    if has_impediment:<br>        return &quot;BLOCKED: Direct impediment identified in Item 3.&quot;<br>    if regional_risk and score &lt; 800:<br>        return &quot;RISK: Insufficient score for the region (Geographic Override).&quot;<br>    return &quot;CONSERVATIVE: Client meets all security requirements.&quot;</pre><p>And the response is forced to follow a Pydantic schema — if the AI returns something outside the schema, it is rejected:</p><pre># src/agent/agent_langgraph_model.py<br>class LangGraphAgentResponse(BaseModel):<br>    answer: str<br>    client_cpf: str<br>    requested_amount: float<br>    sources: List[LangGraphSource]</pre><h3>LangGraph — The Flow Is Not Linear, It’s a Graph</h3><p>Instead of a script that does A → B → C, the flow is modeled as a <strong>state graph</strong> where each step is a node and transitions can be conditional. This allows the flow to <strong>pause for human approval</strong> and be <strong>resumed later</strong>.</p><pre>class CreditState(TypedDict):<br>    messages: Annotated[list[str], add_messages]<br>    cpf_original: str<br>    cpf_masked: str<br>    amount: float<br>    is_approved: bool<br>    analysis_report: str<br>    client_pattern: Literal[&quot;CONSERVADOR&quot;, &quot;RISCO&quot;, &quot;EXCECAO&quot;, &quot;BLOQUEIO&quot;]</pre><p>This is the shared state. All nodes read from and write to it.</p><h3>The Nodes</h3><pre>START → [guardrails] → [analysis] → (condition) → [auto_approve] → END<br>                                         │<br>                                         └──────→ [manager_approval] ⏸ → END</pre><ul><li><strong>guardrails</strong> — prepares the input data</li><li><strong>analysis</strong> — calls the full RAG pipeline and obtains the AI report</li><li><strong>auto_approve</strong> — marks as automatically approved</li><li><strong>manager_approval</strong> — pauses for the manager to decide</li></ul><h3>Conditional Routing</h3><p>After the analysis, the graph decides the path:</p><pre>def route_request(state: CreditState) -&gt; Literal[&quot;to_manager&quot;, &quot;to_auto_check&quot;]:<br>    pattern = state.get(&quot;client_pattern&quot;)<br>    if pattern == &quot;RISCO&quot; or state[&quot;amount&quot;] &gt; 5000:<br>        return &quot;to_manager&quot;<br>    return &quot;to_auto_check&quot;</pre><p>Amount above R$ 5,000 or RISK classification → pause for the manager. All other cases → automatic approval.</p><h3>Checkpoint and Human-in-the-Loop</h3><p>The graph uses MemorySaver to save the state at each node and interrupt_before to pause before the manager node:</p><pre>memory = MemorySaver()<br>graph = builder.compile(checkpointer=memory, interrupt_before=[&quot;manager_approval&quot;])</pre><p>When the flow pauses, the manager can access the state, read the report, decide, and resume:</p><pre># The flow pauses automatically<br>response = graph.invoke(input_data, config)<br><br># The manager reads the report<br>snapshot = graph.get_state(config)<br>print(snapshot.values.get(&quot;analysis_report&quot;))<br><br># The manager decides<br>graph.update_state(config, {&quot;is_approved&quot;: True})<br><br># The manager resumes<br>graph.invoke(None, config)</pre><p>The None indicates that this is not a new flow — it&#39;s the resumption of the one that was paused.</p><h3>CPF Masking with LiteLLM</h3><p>The CPF is masked at the <strong>infrastructure</strong> level, not in the code. Every call to the LLM goes through the LiteLLM proxy, which uses Microsoft Presidio to detect and replace the CPF automatically.</p><pre>Python App → LiteLLM (proxy) → Presidio detects CPF → Anonymizer replaces → LLM receives XXX.***.***-XX</pre><h3>How to Configure</h3><p><strong>1. Custom Recognizer</strong> — teaches Presidio to detect Brazilian CPF:</p><pre>[<br>  {<br>    &quot;name&quot;: &quot;BrazilCpfRecognizer&quot;,<br>    &quot;supported_language&quot;: &quot;en&quot;,<br>    &quot;patterns&quot;: [<br>      { &quot;name&quot;: &quot;cpf_with_dots&quot;, &quot;regex&quot;: &quot;\\d{3}\\.\\d{3}\\.\\d{3}-\\d{2}&quot;, &quot;score&quot;: 1.0 },<br>      { &quot;name&quot;: &quot;cpf_digits_only&quot;, &quot;regex&quot;: &quot;\\b\\d{11}\\b&quot;, &quot;score&quot;: 0.6 }<br>    ],<br>    &quot;supported_entity&quot;: &quot;BRAZIL_CPF&quot;<br>  }<br>]</pre><p><strong>2. Guardrail in LiteLLM</strong> — activates Presidio as an interceptor:</p><pre>guardrails:<br>  - guardrail_name: &quot;pii-masking&quot;<br>    litellm_params:<br>      guardrail: presidio<br>      mode: &quot;pre_call&quot;          # intercepts BEFORE sending to the LLM<br>      default_on: true          # always active<br>      presidio_ad_hoc_recognizers: &quot;/app/presidio_ad_hoc_recognizers.json&quot;</pre><p><strong>3. Anonymizer Proxy</strong> — applies the custom mask XXX.***.***-XX:</p><pre># anonymizer_proxy/app.py<br>CUSTOM_OPERATORS = {<br>    &quot;BRAZIL_CPF&quot;: OperatorConfig(&quot;replace&quot;, {&quot;new_value&quot;: &quot;XXX.***.***-XX&quot;}),<br>}<br><br>engine = AnonymizerEngine()<br><br>result = engine.anonymize(text=text, analyzer_results=results, operators=CUSTOM_OPERATORS)</pre><p>The proxy exists because the Presidio Anonymizer REST API ignores custom operators — only the Python API supports them.</p><p><strong>4. Docker Compose</strong> — brings everything up with a single command:</p><pre>docker compose up -d --build</pre><p>There are 4 containers: LiteLLM (proxy), Presidio Analyzer (detects), Anonymizer Proxy (masks), and Anonymizer Upstream (fallback).</p><p>The result: the Python code sends the real CPF without worrying about it. The infrastructure intercepts and protects it. The LLM never sees 123.456.789-00 — only XXX.***.***-XX.</p><h3>Final Result</h3><pre>{<br>  &quot;data&quot;: {<br>    &quot;answer&quot;: &quot;REPORT: The client identifier is XXX.***.***-XX ...&quot;,<br>    &quot;client_cpf&quot;: &quot;XXX.***.***-XX&quot;,<br>    &quot;requested_amount&quot;: 10000.0,<br>    &quot;sources&quot;: [<br>      {<br>        &quot;url&quot;: &quot;https://www.bankestudo.com.br/creditos&quot;,<br>        &quot;title&quot;: &quot;Credit Policy of BANCO ESTUDO S.A.&quot;,<br>        &quot;relevance_score&quot;: 0.8<br>      }<br>    ]<br>  }<br>}</pre><p>A credit request comes in with a real CPF <br>→ RAG retrieves the bank’s policy <br>→ the AI analyzes and classifies → LangGraph decides whether to pause for the manager or approve automatically <br>→ Presidio ensures the CPF never reached the model <br>→ the response comes out structured, validated, and with protected data.</p><h3>Info</h3><p>The repository for this project:<br><a href="https://github.com/angelozero/bank-score">Github AngeloZero</a></p><p>LangChain: <br><a href="https://www.udemy.com/course/langchain/">Udemy: LangChain- Agentic AI Engineering with LangChain &amp; LangGraph</a></p><p>LangGraph:<br><a href="https://www.youtube.com/watch?v=5xS_u8u5NQw&amp;list=PLbIBj8vQhvm09IqqLYIwLF5dGrcbJzFZc&amp;index=5">Youtube: LangGraph: Entenda Graphs, Nodes, Edges e State com Python</a></p><p>Microsoft Presidio:<br><a href="https://microsoft.github.io/presidio/learn_presidio/">Oficial Documentation</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=01779b4f2b45" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python, LangChain and LLM]]></title>
            <link>https://towardsdev.com/python-langchain-and-llm-e9da2c7ac399?source=rss-f3da207c5d78------2</link>
            <guid isPermaLink="false">https://medium.com/p/e9da2c7ac399</guid>
            <category><![CDATA[ollama]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Angelo Ferreira]]></dc:creator>
            <pubDate>Wed, 25 Mar 2026 21:48:20 GMT</pubDate>
            <atom:updated>2026-03-27T15:03:41.016Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Building a RAG System</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fKJ8dvbdpecDNUu7pFqIng.png" /></figure><h3>What is RAG and why use it?</h3><p>Language models (LLMs) like Llama or GPT are trained on public data from the internet. They have no knowledge of your company’s internal documents, specific manuals, or any private information.</p><p><strong>RAG (Retrieval-Augmented Generation)</strong> solves this in three steps:</p><ol><li><strong>Retrieval</strong> — fetches the most relevant excerpts from your documents based on the question asked</li><li><strong>Augmentation</strong> — combines those excerpts with the original question into a single prompt</li><li><strong>Generation</strong> — sends that prompt to the LLM, which generates a response based solely on the provided content</li></ol><p>The result is an assistant that answers accurately about any document you provide, without making up information.</p><h3><strong>1. Indexing</strong></h3><ul><li><em>PDFs → Text Extraction → Splitting into chunks → Vectorization → ChromaDB</em></li></ul><h4>Loading the PDFs</h4><pre>from langchain_community.document_loaders import PyPDFDirectoryLoader<br><br>BASE_FOLDER = &quot;base&quot;<br><br>def load_source_data():<br>    loader = PyPDFDirectoryLoader(BASE_FOLDER)<br>    return loader.load()</pre><p>PyPDFDirectoryLoader reads all .pdf files from the base/ folder and returns a list of Document objects, each containing the extracted text and metadata such as the file name and page number.</p><h4>Splitting into chunks</h4><p>LLMs have a token limit per request. Additionally, sending entire documents increases cost and reduces search precision. The solution is to split the text into smaller blocks:</p><pre>from langchain_text_splitters import RecursiveCharacterTextSplitter<br><br>def split_text_into_chunks(documents):<br>    splitter = RecursiveCharacterTextSplitter(<br>        chunk_size=2000,    # maximum size of each block in characters<br>        chunk_overlap=500,  # overlap between consecutive blocks<br>        length_function=len,<br>        add_start_index=True<br>    )<br>    <br>    return splitter.split_documents(documents)</pre><p>The chunk_overlap ensures that context is not lost at the split boundary — the last 500 characters of one chunk are repeated at the beginning of the next.</p><h4>Vectorizing and saving to ChromaDB</h4><p>Embeddings are numerical representations of text. Semantically similar texts generate vectors that are close together in mathematical space, which enables similarity-based search.</p><pre>from langchain_ollama import OllamaEmbeddings<br>from langchain_chroma.vectorstores import Chroma<br><br>def create_vector_index(chunks):<br>    embeddings = OllamaEmbeddings(model=&quot;llama3.2&quot;)<br>    db = Chroma.from_documents(<br>        chunks,<br>        embeddings,<br>        persist_directory=&quot;chunks_db&quot;<br>    )<br>    print(&quot;Vector database created successfully.&quot;)</pre><p>ChromaDB persists the vectors on disk in the chunks_db/ folder. On the next run, the database will already be available without needing to reprocess the documents.</p><h4>Full indexing flow</h4><pre>def create_db():<br>    raw_documents = load_source_data()<br>    chunks = split_text_into_chunks(raw_documents)<br>    create_vector_index(chunks)<br><br>create_db()</pre><h3>2. Query</h3><ul><li><em>Question → Vectorization → Search in ChromaDB → Prompt with context → LLM → Response</em></li></ul><h4>Opening the database and searching for relevant chunks</h4><pre>from langchain_chroma.vectorstores import Chroma<br>from langchain_ollama import OllamaEmbeddings<br><br>CHROMA_PATH = &quot;chunks_db&quot;<br>MODEL = &quot;llama3.2&quot;<br><br>embeddings = OllamaEmbeddings(model=MODEL)<br>db = Chroma(persist_directory=CHROMA_PATH, embedding_function=embeddings)<br>query = input(&quot;Enter your question: &quot;)<br># Returns the 3 chunks most similar to the question, with a relevance score<br>results = db.similarity_search_with_relevance_scores(query, k=3)<br>if not results or results[0][1] &lt; 0.3:<br>    print(&quot;No relevant results found.&quot;)<br>    exit()</pre><p>The relevance score ranges from 0 to 1. The threshold 0.3 filters out results with low semantic similarity, preventing the LLM from answering based on irrelevant context.</p><h4>Building the prompt with context</h4><pre>from langchain_core.prompts import ChatPromptTemplate<br><br>PROMPT_TEMPLATE = &quot;&quot;&quot;<br>Answer the question based only on the following context:<br>{context}<br>---<br>Answer the question based on the above context: {question}<br>&quot;&quot;&quot;<br>context_text = &quot;\n\n---\n\n&quot;.join([doc.page_content for doc, _score in results])<br>prompt_template = ChatPromptTemplate.from_template(PROMPT_TEMPLATE)<br>prompt = prompt_template.format(context=context_text, question=query)</pre><p>The instruction <em>“based only on the following context”</em> is important: it restricts the LLM to answer only based on the provided chunks, preventing it from using external knowledge and generating inaccurate responses.</p><h4>Calling the LLM and displaying the response</h4><pre>from langchain_ollama import ChatOllama<br><br>llm = ChatOllama(model=MODEL)<br>response = llm.invoke(prompt)<br>sources = [doc.metadata.get(&quot;source&quot;, &quot;unknown&quot;) for doc, _score in results]<br>print(f&quot;\nResponse:\n{response.content}&quot;)<br>print(f&quot;\nSources: {sources}&quot;)</pre><p>ChatOllama connects to the local Ollama server (http://localhost:11434) and sends the prompt to the model. The response includes the sources — the names of the files from which the chunks were extracted — which allows tracing the origin of each piece of information.</p><h3>Final Thoughts</h3><p>This project demonstrates that it is possible to build a functional RAG system using 100% open source tools at no operational cost. Running the LLM locally via Ollama eliminates the dependency on paid APIs and keeps data private on your own machine.</p><p>For production environments, the main areas for improvement would be:</p><ul><li>Replace ChromaDB with a managed vector database (Pinecone, Weaviate, pgvector)</li><li>Add chunk reranking to improve search precision</li><li>Implement conversation memory to support follow-up questions</li><li>Expose the system via a REST API with FastAPI</li></ul><h3>References</h3><ul><li><a href="https://docs.langchain.com/">LangChain Documentation</a></li><li><a href="https://ollama.com/">Ollama</a></li><li><a href="https://www.trychroma.com/">ChromaDB</a></li><li><a href="https://www.youtube.com/watch?v=0M8iO5ykY-E">Youtube — Complete AI Agent with Python — RAG Project with Langchain</a></li></ul><h3><strong>Code</strong></h3><ul><li><a href="https://github.com/angelozero/python-rag-project">Github AngeloZero</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e9da2c7ac399" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/python-langchain-and-llm-e9da2c7ac399">Python, LangChain and LLM</a> was originally published in <a href="https://towardsdev.com/">Towards 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 Record Builder]]></title>
            <link>https://medium.com/@angelozero/java-record-builder-93ad892708e6?source=rss-f3da207c5d78------2</link>
            <guid isPermaLink="false">https://medium.com/p/93ad892708e6</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[dto]]></category>
            <category><![CDATA[record]]></category>
            <category><![CDATA[lombok]]></category>
            <dc:creator><![CDATA[Angelo Ferreira]]></dc:creator>
            <pubDate>Mon, 09 Feb 2026 11:58:28 GMT</pubDate>
            <atom:updated>2026-02-09T11:58:28.436Z</atom:updated>
            <content:encoded><![CDATA[<p>An efficient approach to building Java Records</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/1*8WPxd7keHZetvnc-rBPGgA.jpeg" /></figure><h3>What is a Record?</h3><p>Record is a special class wich acts as a transporter of immutable data. If you need a class only to hold values ( like a DTO or a coordinator pair ), the Record does this in a compact way, automatically generating methods equals(), hashCode(), toString() and the getters. Was officially introduced as a stable functionality in Java 16. Came through <a href="https://openjdk.org/jeps/395">JEP 395</a>.</p><p><strong>Heritage</strong></p><ul><li>A Record can implement an interface but it can’t extend other classes.</li></ul><p><strong>Modifiers</strong></p><ul><li>A Record can be declared as final but it can’t be extended by another class because are implicitly final.</li></ul><p><strong>Attributes</strong></p><ul><li>A Record has static fields.</li></ul><p><strong>Constructors</strong></p><ul><li>A Record creates compacts constructors for the purpose of validation but it is not possible to change the field state because they are final.</li></ul><p><strong>Methods</strong></p><ul><li>A Record can add instance or static methods but is not a good idea to declare access methods with different names (ex: getName() instead of name()).</li></ul><p><strong>Immutability</strong></p><ul><li>All the fields from a Record are private final by default.</li></ul><p><strong>Reduced Boilerplate</strong></p><ul><li>You can define the body of the class in a single line: public Record Person(Integer id, String name) {}.</li></ul><h3>Too verbose don’t you think?</h3><p>In the old days to write/create a simple class with only two fields, you had to write something about 40 or 50 lines of code. It was necessary to declare the fields, constructor, getters, setters and manually equals(), hashCode() and toString().</p><pre>public class Person {<br><br>    private Integer id;<br>    private String name;<br><br>    public Person() {<br>    }<br><br>    public Person(Integer id, String name) {<br>        this.id = id;<br>        this.name = name;<br>    }<br><br>    // Getters, Setters, equals, hashCode and toString... (more than 30 lines!)<br>}</pre><h3>The Lombok Era</h3><p><a href="https://projectlombok.org/features/">Lombok</a> has come to “hide” this all “unnecessary info”. With a few annotations, the Lombok lib generates the code at compile time. Visualy, it was a really good solution but is necessary to add an external dependency into the project.</p><pre>import lombok.*;<br><br>@Data<br>@Builder<br>@AllArgsConstructor<br>@NoArgsConstructor<br>public class Person {<br>    private Integer id;<br>    private String name;<br>    <br>}</pre><h3>The Records Era</h3><p>Java, with Record, came to natively understand that purpose is just carry data. The code is reduced to a single line. The intention is clear, the fields are immutable by default and you don’t need external libs or even generate code in your editor.</p><pre>public record PersonRecord(Integer id, String name) { }</pre><h3>How about Record Builder?</h3><p>In this <a href="https://github.com/Randgalt/record-builder">record-builder project from Randgalt</a> you will find a new feature showing <em>how to create a record from with a builder pattern</em>. Features in this project:</p><ul><li>a companion builder class for Java records</li><li>an interface that adds “with” copy methods</li><li>an annotation that generates a Java record from an Interface template</li></ul><p><strong>POM dependecy</strong></p><pre>&lt;!-- currently using the version 51 --&gt;<br>&lt;dependencies&gt;<br>    &lt;dependency&gt;<br>        &lt;groupId&gt;io.soabase.record-builder&lt;/groupId&gt;<br>        &lt;artifactId&gt;record-builder-core&lt;/artifactId&gt;<br>        &lt;version&gt;${record.builder.version}&lt;/version&gt;<br>        &lt;scope&gt;provided&lt;/scope&gt;<br>    &lt;/dependency&gt;<br>&lt;/dependencies&gt;<br><br>&lt;build&gt;<br>    &lt;plugins&gt;<br>        &lt;plugin&gt;<br>            &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;<br>            &lt;artifactId&gt;maven-compiler-plugin&lt;/artifactId&gt;<br>            &lt;configuration&gt;<br>                &lt;annotationProcessorPaths&gt;<br>                    &lt;path&gt;<br>                        &lt;groupId&gt;io.soabase.record-builder&lt;/groupId&gt;<br>                        &lt;artifactId&gt;record-builder-processor&lt;/artifactId&gt;<br>                        &lt;version&gt;${record.builder.version}&lt;/version&gt;<br>                    &lt;/path&gt;<br>                &lt;/annotationProcessorPaths&gt;<br>            &lt;/configuration&gt;<br>        &lt;/plugin&gt;<br>    &lt;/plugins&gt;<br>&lt;/build&gt;</pre><p><strong>RecordBuilder Example</strong></p><pre>@RecordBuilder<br>public record PersonRecord(Integer id, String name) { }</pre><pre>public static void foo() {<br>    var angelo = PersonRecordBuilder.builder().id(1).name(&quot;Angelo&quot;).build();<br>    var angeloWithNewId = PersonRecordBuilder.builder(angelo).id(2).build();<br><br>    System.out.println(&quot;Name: &quot; + angelo.name());<br>    System.out.println(&quot;Old id: &quot; + angelo.id());<br>    System.out.println(&quot;New id: &quot; + angeloWithNewId.id());<br>}</pre><p><strong><em>Wihter</em> Example</strong></p><pre>@RecordBuilder<br>public record NewPersonRecord(Integer id, String name) implements NewPersonRecordBuilder.With { }</pre><pre>public static void bar() {<br>        var p1 = new NewPersonRecord(1, &quot;Angelo&quot;);<br>        var p2 = p1.withName(&quot;Zero&quot;);<br>        var p3 = p2.withId(2);<br>        var p4 = p3.with().id(3).name(&quot;Jake&quot;).build();<br>        var p5 = p4.with(person -&gt; person.id(4).name(&quot;Java&quot;));<br>        var p6 = p5.with(person -&gt; {<br>            if (person.name().equals(&quot;Java&quot;)){<br>                person.name(person.name() + &quot; is cool!&quot;) ;<br>            }<br>        });<br>        var p7 = NewPersonRecordBuilder.from(p6).withId(25);<br>  <br>        // System.out.println(&quot;P1 - name: &quot; + p1.name() + &quot; id: &quot; + p1.id());<br>    }</pre><ul><li>The output will be</li></ul><pre>P1 - name: Angelo id: 1<br>P2 - name: Zero id: 1<br>P3 - name: Zero id: 2<br>P4 - name: Jake id: 3<br>P5 - name: Java id: 4<br>P6 - name: Java is cool! id: 4<br>P7 - name: Java is cool! id: 25</pre><h3>Info</h3><p><strong>Thanks for</strong></p><ul><li><a href="https://medium.com/@sskmal/java-records-6736f45a6aa7">Java Records and Builder pattern For Record — by sunimal malkakulage</a></li><li><a href="https://www.youtube.com/watch?v=wAW2OpBKpvw">Spring Tips: Useful Annotation Processors — by SpringDeveloper</a></li><li><a href="https://github.com/Randgalt/record-builder">Github Randgalt — record-builder</a></li></ul><p><strong>You can find all the code from this article here</strong></p><ul><li><a href="https://github.com/angelozero/java-record-builder">Github AngeloZero — java-record-builder</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=93ad892708e6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LangChain4j Java integration for LLMs]]></title>
            <link>https://towardsdev.com/langchain4j-java-integration-for-llms-4c13d68810a3?source=rss-f3da207c5d78------2</link>
            <guid isPermaLink="false">https://medium.com/p/4c13d68810a3</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[langchain4j]]></category>
            <dc:creator><![CDATA[Angelo Ferreira]]></dc:creator>
            <pubDate>Mon, 05 Jan 2026 06:38:35 GMT</pubDate>
            <atom:updated>2026-01-26T06:53:19.458Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4AyYmQm6AKV-5kqxd_sZxQ.png" /></figure><p>Artificial Intelligence integration into the Java ecosystem was not such a simple thing. While LLM (Large Language Models) development previously looked like something restricted to the Python ecosystem, <strong>LangChain4J</strong> came to be a <em>game changer</em>.</p><p>In this article I’ll show you how to build a simple assistant specialized in Brazilian soccer capable to executing searches about scores, teams and a few other things in real time using the <strong>Gemini</strong> model from Google.</p><h3>How it works ?</h3><p>Unlike from a common chatbot, an Assistant with ‘Tools’ goes through a cyclic and intelligent flow.</p><ol><li><strong>The Client</strong> asks a question (<em>ex.: ‘Who’s the championship leader?’</em>).</li><li><strong>Ai Service</strong> sends the question and the context (system instructions) to <strong>Gemini</strong>.</li><li><strong>Gemini</strong> doesn’t have the data in real time and asks to use a <strong>Tool</strong>.</li><li><strong>Java</strong> executes the AssistantTools service, gets the data and sends it back to the AI.</li><li><strong>The AI</strong> processes the data and gives a ‘natural’ answer to the user.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w5KektY6ZdcEW0GdBzFccQ.png" /></figure><h3>1. Setup and Dependency</h3><p>For this project I’m using <strong>Spring Boot 4</strong> and the latest version of <strong>LangChain4J</strong>. It’s really important has an API Key from <a href="https://aistudio.google.com/">Google AI Studio</a></p><p><strong>pom.xml</strong></p><pre>&lt;!-- currently 1.10.0-beta18 --&gt;<br>&lt;dependency&gt;<br>    &lt;groupId&gt;dev.langchain4j&lt;/groupId&gt;<br>    &lt;artifactId&gt;langchain4j-spring-boot-starter&lt;/artifactId&gt;<br>    &lt;version&gt;${langchain.version}&lt;/version&gt;<br>&lt;/dependency&gt;<br><br>&lt;!-- currently 1.10.0 --&gt;<br>&lt;dependency&gt;<br>    &lt;groupId&gt;dev.langchain4j&lt;/groupId&gt;<br>    &lt;artifactId&gt;langchain4j-google-ai-gemini&lt;/artifactId&gt;<br>    &lt;version&gt;${langchain.gemini.version}&lt;/version&gt;<br>&lt;/dependency&gt;</pre><p><strong>application.properties</strong></p><pre>spring.application.name=langchain4j<br>langchain4j.google.ai.gemini.api-key=YOUR_GOOGLE_AI_STUDIO_API_KEY<br>langchain4j.google.ai.gemini.model-name=gemini-2.5-flash</pre><p><strong>AssistantConfig.java</strong></p><pre>public class AssistantConfig {<br>    <br>    @Value(&quot;${langchain4j.google.ai.gemini.api-key}&quot;)<br>    private String geminiApiKey;<br>    <br>    @Value(&quot;${langchain4j.google.ai.gemini.model-name}&quot;)<br>    private String geminiModel;<br>    <br>    @Bean<br>    public GoogleAiGeminiChatModel googleAiGeminiChatModel() {<br>        return GoogleAiGeminiChatModel.builder()<br>                .apiKey(geminiApiKey)<br>                .modelName(geminiModel)<br>                .build();<br>    }<br><br>    @Bean<br>    public AssistantAiService assistant(GoogleAiGeminiChatModel model, AssistantTools assistantTools) {<br>        return AiServices.builder(AssistantAiService.class)<br>                .chatModel(model)<br>                .tools(assistantTools)<br>                .build();<br>    }<br>}</pre><h3>2. System Messages and Ai Service</h3><p>An Assistant without instructions ends up becoming unpredictable. Through the assistant-instructions.txt file, we defined that our AI is an expert in Brazilian soccer.</p><p><strong>assistant-instructions.txt (</strong><em>Obs.: You can access the entire file </em><a href="https://github.com/angelozero/langchain4j/blob/main/src/main/resources/prompts/assistant-instructions.txt"><em>here</em></a><em> )</em></p><pre>You are an expert assistant in BRAZILIAN FOOTBALL. Respond ONLY about competitions, clubs, statistics, and history of national football ...</pre><p><strong>Prompt Engineering</strong></p><ul><li>The AI’s focus here is on about Brazilian Soccer and nothing else. When using @SystemMessage(fromResource = &quot;...&quot;), <strong>LangChain4J</strong> injects all those rules into your interactions, ensuring the AI processes the information correctly</li></ul><p><strong>Ai Service</strong></p><ul><li>The AssistantAiService interface, with the @AiService annotation, is the entry point for all the AI logic. Spring handles all the implementation at runtime, connecting the <strong>Gemini</strong> model, <strong>Tools</strong> and the <strong>instructions</strong>.</li></ul><pre>@AiService<br>public interface AssistantAiService {<br><br>    @SystemMessage(fromResource = &quot;prompts/assistant-instructions.txt&quot;)<br>    Result&lt;String&gt; handleRequest(@UserMessage String userMessage);<br><br>}</pre><h3>3. Tools</h3><p>The <strong>LangChain4J</strong> magic is in the annotation @Tool. It provides Java methods to <strong>Gemini</strong> that can be invoked. When the user asks *&#39;Who&#39;s the leader?&#39; <strong>Gemini</strong> doesn&#39;t give a random response, it identifies the description from the tool and makes a request to <strong>LangChain4J</strong> to execute the method getChampionshipLeaders().</p><pre>@Component<br>public class AssistantTools {<br><br>    @Tool(&quot;Returns the list of the top 3 teams currently leading the championship.&quot;)<br>    public String getChampionshipLeaders() {<br>        Map&lt;String, String&gt; currentTable = ChampionshipService.generateRandomTable();<br>        String leaders = currentTable.entrySet().stream()<br>                //... some code here<br>                .collect(Collectors.joining(&quot;, &quot;));<br>        return &quot;The current leaders are: &quot; + leaders;<br>    }<br><br>}</pre><h3>Conclusion</h3><p><strong>LangChain4J</strong> integrated with <strong>Gemini</strong> abstracts the LLM’s consumption in the Java ecosystem, allowing for the implementation of smart agents.</p><p><strong>Natural Language Proccess (NLP): </strong><em>High precision in intent and entity extraction.</em></p><p><strong>Context Orquestration: </strong><em>Behaviour control by system instructions.</em></p><p><strong>Function Calling: </strong><em>Execution logic services and queries at runtime to retrieve data using </em><strong><em>Tools</em></strong><em>.</em></p><h3>Info</h3><ul><li><a href="https://www.youtube.com/watch?v=A5i7D7RAPA4">Aprenda IA com Java LangChain4j | Arquitetura Spring Boot + Gemini na prática by Michelli Brito</a></li><li><a href="https://docs.langchain4j.dev/intro">LangChain4J — Offical Documentation</a></li><li><a href="https://github.com/langchain4j/langchain4j-spring">Github LangChain4J</a></li></ul><p><strong>The project used in this article</strong></p><ul><li><a href="https://github.com/angelozero/langchain4j">Github AngeloZero</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4c13d68810a3" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/langchain4j-java-integration-for-llms-4c13d68810a3">LangChain4j Java integration for LLMs</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Modern Java is pretty cool and I can prove it]]></title>
            <link>https://medium.com/@angelozero/modern-java-is-pretty-cool-and-i-can-prove-it-7501cd6f6efb?source=rss-f3da207c5d78------2</link>
            <guid isPermaLink="false">https://medium.com/p/7501cd6f6efb</guid>
            <category><![CDATA[java-quarkus]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[graalvm]]></category>
            <category><![CDATA[quarkus]]></category>
            <dc:creator><![CDATA[Angelo Ferreira]]></dc:creator>
            <pubDate>Wed, 12 Nov 2025 03:22:02 GMT</pubDate>
            <atom:updated>2025-11-12T03:22:02.900Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VxHCZHFLCyJPBR9eUw3GbQ.png" /></figure><p>For a long while, Java had this bad reputation of being a bloated, verbose and sometimes a little bit confusing for someone who is starting with the language, but these days this couldn’t be further from the truth.</p><p>Modern Java is actually leaner, faster, and far more elegant than most developers give it credit for.</p><p>More importantly, however, there are few other languages that offer as many job opportunities or as much long-term stability as Java.</p><p>So let’s see some misconceptions and review what the modern Java ecosystem has to offer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*DnvoZCRoADfdL8pT" /></figure><h4><strong><em>Boilerplates</em></strong></h4><ul><li>First is that in recent years Java managed to remove a lot of the boilerplate it was famous for. This is why Java code such as this one can be greatly improved thanks to some modern new features.</li><li>The first code is that we used to code with a verbose structure</li></ul><p><strong><em>The old way</em></strong></p><pre>public class Main {<br>    public static void main(String[] args) {<br>        List&lt;Car&gt; cars = new ArrayList&lt;Car&gt;();<br>        cars.add(new Car(1L, &quot;ferrari&quot;));<br>        cars.add(new Car(1L, &quot;bmw&quot;));<br>        cars.add(new Car(1L, &quot;nissan&quot;));<br><br>        for (Car car : cars) {<br>            System.out.println(car.model());<br>        }<br>    }<br>}</pre><p><strong><em>The modern way</em></strong></p><ul><li><em>Font: </em><a href="https://openjdk.org/jeps/512"><em>JEP 512: Compact Source Files and Instance Main Methods</em></a></li></ul><pre>public class Main {<br>    void main() {<br>        var cars = List.of(<br>                new Car(1L, &quot;ferrari&quot;),<br>                new Car(1L, &quot;bmw&quot;),<br>                new Car(1L, &quot;nissan&quot;));<br><br>        cars.stream()<br>                .map(car -&gt; &quot;The car model is: &quot; + car.model())<br>                .forEach(System.out::println);<br>    }<br>}</pre><ul><li>The second code now use records, which are essentially immutable data classes with built-in constructors, accessors and special methods. They let us define plain data objects in a single line instead of a full-blown class with boilerplate.</li></ul><pre>public record Car(Long id, String model) { }</pre><ul><li>Another big improvement is Java type inference and the var keyword. As you might know, Java is famous for being a really strict strongly typed object oriented language, and for a long while, it was mocked for forcing you to declare the same type over and over again even when it was obvious.</li><li>The first thing they did was to introduce the diamond operator to reduce redundant type declarations when creating generic objects then, in java10, type inference took that even further with the introduction of the var keyword. Of course, the compiler still enforces strict typing, but the resulting code is finally starting to look like a language in this century.</li></ul><pre>var cars = List.of(...);</pre><h4><strong><em>Concurrency and Asynchronous Programming</em></strong></h4><ul><li>Another area where Java made massive progress is in how it handles concurrency and asynchronous programming. For years, working with threads in Java felt like operating heavy machinery.</li><li>This all changes in recent versions thanks to <a href="https://wiki.openjdk.org/display/loom/Main">Project Loom</a>. In short this project completely rethinks how concurrency works in Java. Instead of forcing developers to juggle complext thread pools, futures, and reactive abstractions, Loom introduces virtual threads, which are lightweight and managed by the JVM instead of the operating system.</li><li>Traditional threads in Java were expensive, with each one consuming megabytes of stack space and being limited by how many the OS could handle. Virtual threads, on the other hand, are cheap to create, cheap to park, and designed to scale effortlessly.</li><li>This alone changes how you architect systems. You can write code that reads like it’s blocking while performing like it’s asynchronous.</li><li><a href="https://quarkus.io/get-started/">Quarkus</a> is a framework that is already integrating with Loom to take advantege of this new model, allowing servers to handle tens or even hundreds of thousands of concurrent connections without any of the XML nightmare configuration Java was famous for.</li></ul><p><strong><em>Before Loom</em></strong></p><pre>// <br>var executor = Executors.newFixedThreadPool(10);<br>for (int i = 0; i &lt; 1000; i++) {<br>    executor.submit(() -&gt;<br>        System.out.println(&quot;Catching Pokémon &quot; + Thread.currentThread())<br>    );<br>}<br>executor.shutdown();</pre><p><strong><em>After Loom</em></strong></p><pre>try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {<br>    for (int i = 0; i &lt; 1000; i++) {<br>        executor.submit(() -&gt;<br>            System.out.println(&quot;Catching Pokémon &quot; + Thread.currentThread())<br>        );<br>    }<br>}</pre><h4><em>Memory and Performance</em></h4><ul><li>Java handles memory management and overall performance. For years Java’s garbage collector was treated as both its biggest strength and its biggest weakness. The old stereotype of Java being a slow language that eats RAM came from those early JVM days when the garbage collector had to basically stop time to clean up memory. However, this is no longer the case. Over the past decade, the JVM team completely re-engineered the garbage collector subsystem, introducing new collectors with a total philosophical shift.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/0*FVvrAsoVLpOaj3-c.png" /></figure><ul><li>Memory efficiency also improved drastically. Features like compact object headers, escape analysis, and string deduplication have reduced memory overhead to the point where modern Java applications can run in containers with far smaller footprints than ever before.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*o7vSIHdHqsZY7pTU.png" /></figure><ul><li>Spring was for a very long time the default choice for serious Java development. It powered everything from banking systems to enterprise-grade backends, but it also carried a lot of baggage. Everyone involved in any type of enterprise development probably still has nightmares about XML configurations, complex dependency management, or heavyweight startup times. But the good news is that there is a new wave of frameworks that completely rethink how Java applications are built.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*j8KRfkVl9vs3enSz.png" /></figure><ul><li>These frameworks are designed for speed, simplicity, and developer experience, without sacrificing the robustness that made Java popular in the first place.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Kp9nA3ShA2uRiwHR.png" /></figure><p><a href="https://quarkus.io/get-started/">Quarkus</a> is at the forefront of this new generation. It is built with cloud-native environments in mind, and it trims down the traditional enterprise overhead and embraces modern JVM features like GraalVM and ahead-of-time compilation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/655/0*C43JngpCkpqrHz6w.png" /></figure><p><a href="https://www.graalvm.org/latest/getting-started/">Graal VM</a> is a high-performance runtime developed by Oracle Labs that extends the traditional Java Virtual Machine into a universal virtual machine capable of running multiple languages efficiently. It’s built on two main ideas.</p><ul><li>1º — We get a new Just-In-Time compiler, which replaces the old HotSpot JIT and generates faster, more optimized machine code. It uses aggressive profiling and speculative optimization to squeeze out extra performance from Java and other JVM languages.</li><li>2º — It enables ahead-of-time compilation by its native image technology. So instead of distributing bytecode that runs on a JVM, you can compile your entire application into a single native binary. That binary start almost instantly, uses less memory, and doesn’t require a separete JVM installation.</li></ul><p><strong><em>Now… Show me the code!</em></strong></p><ul><li>One of the thins you’ll notice is how familiar the code feels. Quarkus doesn’t try to reinvent the language or force a new paradigm so you’ll still write plain Java, with annotations and dependency injection. This is similar to Spring, but there is no reflection overhead or runtime magic. Everything is processed at compile time, making it both faster and more predictable.</li><li>Once we define a basic endpoint, we can plug in an ORM and add a data layer to the mix</li><li>Quarkus supports both Hibernate ORM and <a href="https://pt.quarkus.io/guides/hibernate-orm-panache">Panache</a>, which is Quarku’s take on simplifying JPA.</li><li>Note that entity class doesn’t have a primary key field. That’s because the base entity is already providing an autoincremented id, and also basic CRUD opertations.</li><li>The repository is annotated with @ApplicationScoped, so it&#39;s managed by Quarkus dependency injection system, and automatically wired wherever you need it.</li></ul><p><em>Controller</em></p><pre>@Path(&quot;/api/car&quot;)<br>public class CarController {<br><br>    @Inject<br>    private GetCarUseCase getCarUseCase;<br><br>    @GET<br>    public List&lt;CarRest&gt; getCar() {<br>        return getCarUseCase.execute().stream()<br>                .map(car -&gt; new CarRest(car.id(), car.model()))<br>                .toList();<br>    }<br>}</pre><p><em>Service</em></p><pre>@ApplicationScoped<br>public class GetCarUseCase {<br><br>    @Inject<br>    private CarRepository carRepository;<br><br>    public List&lt;Car&gt; execute() {<br>        try {<br>            return carRepository.list(Page.ofSize(10), Sort.empty())<br>                    .stream().map(carEntity -&gt; new Car(carEntity.id, carEntity.getModel()))<br>                    .toList();<br>        <br>        } catch (Exception ex) {<br>            throw new RuntimeException(&quot;Fail to get a list of cars: &quot; + ex.getMessage());<br>        }<br>    }<br>}</pre><p><em>Repository</em></p><pre>@ApplicationScoped<br>public interface CarRepository extends PanacheEntityResource&lt;CarEntity, Long&gt; {}</pre><p><em>Entity</em></p><pre>@Entity(name = &quot;CAR&quot;)<br>public class CarEntity extends PanacheEntity {<br>    private String model;<br><br>    public String getModel() {<br>        return model;<br>    }<br><br>    public void setModel(String model) {<br>        this.model = model;<br>    }<br>}</pre><ul><li><a href="https://quarkus.io/get-started/"><em>To execute the project follow the steps 1 and 3</em></a></li><li><a href="https://github.com/angelozero/hello-world-quarkus"><em>Github: AngeloZero: hello-world-quarkus</em></a></li><li><a href="https://www.youtube.com/watch?v=lvHR2Xc9LMU"><em>Youtube: Modern Java is pretty cool and you can’t avoid it anymore… — By Awesome</em></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7501cd6f6efb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Keycloak - Custom SPI ProtocolMapper]]></title>
            <link>https://medium.com/@angelozero/keycloak-custom-spi-protocolmapper-1693decff037?source=rss-f3da207c5d78------2</link>
            <guid isPermaLink="false">https://medium.com/p/1693decff037</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[spi]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[keycloak]]></category>
            <dc:creator><![CDATA[Angelo Ferreira]]></dc:creator>
            <pubDate>Sun, 27 Apr 2025 02:09:23 GMT</pubDate>
            <atom:updated>2025-04-27T02:09:23.400Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/934/1*ICtupsGDh6ErwQlSmOZImQ.jpeg" /></figure><p><em>Authentication using Keycloak, Spring Boot with JWT, PostgreSQL, and Docker</em></p><ul><li>This article explains how to create a <strong>custom SPI</strong> to intercept <strong>authentication</strong>. By intercepting this process, we can save the user’s record in a <strong>PostgreSQL database</strong> and return their interests in the authenticated token’s data. Shortly after, we will call a <strong>REST API</strong> to retrieve this interests via the token.</li><li>The AuthenticatorFactory interface is fundamental for customizing and extending authentication mechanisms in Keycloak, allowing us to integrate new authentication methods flexibly and configurable.</li></ul><pre>import org.keycloak.authentication.AuthenticationFlowContext;<br>import org.keycloak.authentication.Authenticator;<br>import org.keycloak.models.KeycloakSession;<br>import org.keycloak.models.RealmModel;<br>import org.keycloak.models.UserModel;<br>import org.slf4j.Logger;<br>import org.slf4j.LoggerFactory;<br><br>public class CustomAuthenticationFactory implements AuthenticatorFactory {<br>  // some implemented methods here...<br>}</pre><ul><li>The Authenticator interface is responsible for managing the user authentication process.</li></ul><pre>import org.keycloak.authentication.AuthenticationFlowContext;<br>import org.keycloak.authentication.Authenticator;<br>import org.keycloak.models.KeycloakSession;<br>import org.keycloak.models.RealmModel;<br>import org.keycloak.models.UserModel;<br>import org.slf4j.Logger;<br>import org.slf4j.LoggerFactory;<br><br>public class CustomAuthenticator implements Authenticator {<br>    // some implemented methods here...<br>}</pre><ul><li>CustomAccessTokenMapper class extends AbstractOIDCProtocolMapper and implements several interfaces, including OIDCAccessTokenMapper, allowing mapping of custom attributes to the access token. With them you add attributes on final token.</li></ul><pre>import org.keycloak.models.ClientSessionContext;<br>import org.keycloak.models.KeycloakSession;<br>import org.keycloak.models.ProtocolMapperModel;<br>import org.keycloak.models.UserSessionModel;<br>import org.keycloak.protocol.oidc.mappers.*;<br>import org.keycloak.provider.ProviderConfigProperty;<br>import org.keycloak.representations.IDToken;<br>import org.slf4j.Logger;<br>import org.slf4j.LoggerFactory;<br><br>public class CustomAccessTokenMapper extends AbstractOIDCProtocolMapper implements OIDCAccessTokenMapper, OIDCIDTokenMapper, UserInfoTokenMapper {<br>    // some methods here...<br>    <br>    @Override<br>    protected void setClaim(IDToken token, ProtocolMapperModel mappingModel, UserSessionModel userSession, KeycloakSession keycloakSession, ClientSessionContext clientSessionCtx) {<br>      //some logic here...<br>    }<br><br>    @Override<br>    public AccessToken transformAccessToken(AccessToken token, ProtocolMapperModel mappingModel, KeycloakSession session, UserSessionModel userSession, ClientSessionContext clientSessionCtx) {<br>      //some logic here...<br>    }<br>}</pre><ul><li>setClaim() — the setClaim method cannot return a list directly in the token, regardless of the type of that list. To work around this situation, we can add the list inside an object and thus return the object.</li></ul><pre>public record UserDataInterests(List&lt;UserInterests&gt; userInterestsList) {<br>}<br><br>/* * */<br><br>@Override<br>protected void setClaim(/*...*/) {<br>    var userDataInterests = findUserDataInterests(email);<br>    OIDCAttributeMapperHelper.mapClaim(token, mappingModel, userDataInterests);    <br>}</pre><ul><li>transformAccessToken() — In the transformAccessToken method, we can add any parameter and any type of object, including a list of any type.</li></ul><pre>public record User(//... some attributes<br>                   List&lt;String&gt; interests) {<br>}<br><br>/* * */<br><br>@Override<br>public AccessToken transformAccessToken(/***/) {<br>    var user = findUser(email);<br>    token.getOtherClaims().put(&quot;interests_string_list&quot;, user.interests());<br>    setClaim(token, mappingModel, userSession, session, clientSessionCtx);    <br>    return token;<br>}</pre><h3>META-INF folder and its files</h3><ul><li>To register the custom authenticator in Keycloak, you need to create:</li></ul><h4>META-INF/services</h4><p>This folders are necessary to store your module’s metadata. It is a convention in Java applications that allows Keycloak to recognize and configure your custom authenticator.</p><h4><strong>AuthenticatorFactory and </strong><strong>ProtocolMapper</strong>:</h4><p>These files are crucial as they inform Keycloak about the interfaces being implemented.</p><pre>my-custom-authenticator-project/<br>│<br>├── META-INF/<br>│   └── services/<br>│       └── org.keycloak.authentication.AuthenticatorFactory<br>│       └── org.keycloak.protocol.ProtocolMapper<br>│<br>└── CustomAccessTokenMapper.java<br>└── CustomAuthenticationFactory.java<br>└── CustomAuthenticator.java</pre><h3>Keycloak Configs</h3><ul><li>In Authentication &gt; (your_flow_auth) &gt; Add a new step / your spi &gt; edit configs</li><li>set <em>&quot;ACTIVE&quot;</em> <strong>Object String List Token Attribute</strong> field</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/445/1*wHC_2FQhNCrkJZg4HR6jLg.png" /></figure><ul><li>In Client Scopes &gt; (your_client_scope) &gt; Mappers &gt; configs</li><li>set <em>&quot;interests_object_list&quot; in </em><strong>Token Claim Name</strong> field</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bRioGISlv1-JuXPPbJZ1eA.png" /></figure><p>Don&#39;t forget it to add the <a href="https://www.forumsys.com/2022/05/10/online-ldap-test-server/">LDAP Free Data Base</a> to import some users</p><p>The log in the end must be something like this</p><pre>[CustomAuthenticator] - Custom Authenticator SPI<br>[CustomAuthenticator] - User request data info:<br>[CustomAuthenticator] - USERNAME ---------------&gt; gauss<br>[CustomAuthenticator] - PASSWORD ---------------&gt; password<br>[CustomAuthenticator] - CONFIG VALUE -----------&gt; ACTIVE<br>[CustomAuthenticator] - CONFIG ENABLE ----------&gt; true<br><br>[UserPostgresRepository] - Find user by email: gauss@ldap.forumsys.com<br>[UserPostgresRepository] - Getting connection into PostgresSQl database<br>[UserPostgresRepository] - User found with success<br>[UserPostgresRepository] - ID -------------- 1<br>[UserPostgresRepository] - FIRST NAME ------ Carl Friedrich Gauss<br>[UserPostgresRepository] - EMAIL ----------- gauss@ldap.forumsys.com<br>[UserPostgresRepository] - INTERESTS ------- [Tech, Sports, Music]<br><br>[CustomAuthenticator] - User &quot;gauss&quot; authenticated with success<br><br>[CustomAccessTokenMapper] - Custom Transform Access Token<br>[CustomAccessTokenMapper] - Is enable ? --------&gt; {CUSTOM_AUTH_CLIENT_CONFIG_ENABLE=true, CUSTOM_AUTH_CLIENT_CONFIG_VALUE=ACTIVE}<br><br>[UserPostgresRepository] - Find user by email: gauss@ldap.forumsys.com<br>[UserPostgresRepository] - Getting connection into PostgresSQl database<br>[UserPostgresRepository] - User found with success<br>[UserPostgresRepository] - ID -------------- 1<br>[UserPostgresRepository] - FIRST NAME ------ Carl Friedrich Gauss<br>[UserPostgresRepository] - EMAIL ----------- gauss@ldap.forumsys.com<br>[UserPostgresRepository] - INTERESTS ------- [Tech, Sports, Music]<br><br>[CustomAccessTokenMapper] - Custom Access Token Mapper SPI<br>[CustomAccessTokenMapper] - Config value -------&gt; {CUSTOM_AUTH_CLIENT_CONFIG_ENABLE=true, CUSTOM_AUTH_CLIENT_CONFIG_VALUE=ACTIVE}<br><br>[UserPostgresRepository] - Find user by email: gauss@ldap.forumsys.com<br>[UserPostgresRepository] - Getting connection into PostgresSQl database<br>[UserPostgresRepository] - User found with success<br>[UserPostgresRepository] - ID -------------- 1<br>[UserPostgresRepository] - FIRST NAME ------ Carl Friedrich Gauss<br>[UserPostgresRepository] - EMAIL ----------- gauss@ldap.forumsys.com<br>[UserPostgresRepository] - INTERESTS ------- [Tech, Sports, Music]<br><br>[CustomAccessTokenMapper] - Token updated with success<br>[CustomAccessTokenMapper] - Token updated value to interests_string_list with success</pre><p>And the final token like this</p><pre>eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICJkam84ZmpnZGtIT29ZVHVNSGkwOXozV2s3aVY2cFd5V0lKSFl6a1hGbTEwIn0.eyJleHAiOjE3NDU3MTY4MDEsImlhdCI6MTc0NTcxNjc0MSwiYXV0aF90aW1lIjoxNzQ1NzE2NzQxLCJqdGkiOiJjNmU4M2M0Mi1iM2JlLTRiMzctOWMwZC04YzY3YjE0ZmY5YjEiLCJpc3MiOiJodHRwOi8vbG9jYWxob3N0OjgwODAvcmVhbG1zL21hc3RlciIsImF1ZCI6ImFjY291bnQiLCJzdWIiOiI0ZDVmODBiZS1mMGU0LTRkY2ItODA1MS1mYzJmZTQ5NjEwM2YiLCJ0eXAiOiJCZWFyZXIiLCJhenAiOiJ6ZXJvIiwic2lkIjoiODgxZmIyYjAtZGQ2My00Y2IwLTk3OTItMjk3NzAxOWFkOGZiIiwiYWNyIjoiMSIsImFsbG93ZWQtb3JpZ2lucyI6WyIqIl0sInJlYWxtX2FjY2VzcyI6eyJyb2xlcyI6WyJkZWZhdWx0LXJvbGVzLW1hc3RlciIsIm9mZmxpbmVfYWNjZXNzIiwidW1hX2F1dGhvcml6YXRpb24iXX0sInJlc291cmNlX2FjY2VzcyI6eyJhY2NvdW50Ijp7InJvbGVzIjpbIm1hbmFnZS1hY2NvdW50IiwibWFuYWdlLWFjY291bnQtbGlua3MiLCJ2aWV3LXByb2ZpbGUiXX19LCJzY29wZSI6ImVtYWlsIHByb2ZpbGUiLCJlbWFpbF92ZXJpZmllZCI6ZmFsc2UsImludGVyZXN0c19vYmplY3RfbGlzdCI6eyJ1c2VySW50ZXJlc3RzTGlzdCI6W3siaW50ZXJlc3RzIjoiVGVjaCJ9LHsiaW50ZXJlc3RzIjoiU3BvcnRzIn0seyJpbnRlcmVzdHMiOiJNdXNpYyJ9XX0sIm5hbWUiOiJDYXJsIEZyaWVkcmljaCBHYXVzcyBHYXVzcyIsInByZWZlcnJlZF91c2VybmFtZSI6ImdhdXNzIiwiZ2l2ZW5fbmFtZSI6IkNhcmwgRnJpZWRyaWNoIEdhdXNzIiwiZmFtaWx5X25hbWUiOiJHYXVzcyIsImVtYWlsIjoiZ2F1c3NAbGRhcC5mb3J1bXN5cy5jb20iLCJpbnRlcmVzdHNfc3RyaW5nX2xpc3QiOlsiVGVjaCIsIlNwb3J0cyIsIk11c2ljIl19.ykPA0fZiEsroES8loBZxaaoNnjURfMXIciKGuWReJDpS95WovzVb_eHw9j5a9sDeVA9NG1dqZF9BVcIOo3vGrMJwZiupG1BDIbInITOvzSpOJywK6X6LG_Kp3aW-BlQOdW23EnT86xpIz3cRdG32VNHIS_HWWjdHYnLytRIMrXNad7g1aGiGAB4yxzl92cIAvxgR2jStXvywugZsJhquMJpu_h6I_elb3XbF1-NbvS0MB9m4LwS6UHjh1NsUI3gE3i1gzFF_uLWKde83tZav9033mZ2YbEKTomPEFMJVLIG-CXrjBRRdq0ehG8jn-xVHhl6YZcE-YRxqwYPL4S1aZQ</pre><pre>{<br>    // some values here...<br>    &quot;scope&quot;: &quot;email profile&quot;,<br>    &quot;email_verified&quot;: false,<br>    &quot;interests_object_list&quot;: {<br>        &quot;userInterestsList&quot;: [<br>            {<br>                &quot;interests&quot;: &quot;Tech&quot;<br>            },<br>            {<br>                &quot;interests&quot;: &quot;Sports&quot;<br>            },<br>            {<br>                &quot;interests&quot;: &quot;Music&quot;<br>            }<br>        ]<br>    },<br>    &quot;name&quot;: &quot;Carl Friedrich Gauss Gauss&quot;,<br>    &quot;preferred_username&quot;: &quot;gauss&quot;,<br>    &quot;given_name&quot;: &quot;Carl Friedrich Gauss&quot;,<br>    &quot;family_name&quot;: &quot;Gauss&quot;,<br>    &quot;email&quot;: &quot;gauss@ldap.forumsys.com&quot;,<br>    &quot;interests_string_list&quot;: [<br>        &quot;Tech&quot;,<br>        &quot;Sports&quot;,<br>        &quot;Music&quot;<br>    ]<br>}</pre><p>The complete project can be found at <a href="https://github.com/angelozero/keycloak">AngeloZero — Github</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1693decff037" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SpringBoot with Resilience4j]]></title>
            <link>https://towardsdev.com/springboot-with-resilience4j-f8dc6c29f5bf?source=rss-f3da207c5d78------2</link>
            <guid isPermaLink="false">https://medium.com/p/f8dc6c29f5bf</guid>
            <category><![CDATA[resilience4j]]></category>
            <category><![CDATA[circuit-breaker]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Angelo Ferreira]]></dc:creator>
            <pubDate>Wed, 05 Mar 2025 14:33:00 GMT</pubDate>
            <atom:updated>2025-12-30T12:26:57.080Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xPSdYbLQoytL64Uzv0tTEw.jpeg" /></figure><h3>What is Resilience4j?</h3><p><a href="https://resilience4j.readme.io/docs/getting-started">Resilience4j</a> is a lightweight library for Java that provides resilience patterns such as Circuit Breaker, Retry, Rate Limiter, Bulkhead, and Timeout. These features help protect the application against failures of external services, ensuring that the application continues to operate even when a service fails.</p><h3>Circuit Breaker and Retry</h3><ul><li>The Circuit Breaker pattern prevents the application from making calls to a service that has already failed multiple times in a row, allowing the service time to recover.</li><li>The Retry pattern allows the application to attempt a failed operation multiple times before giving up.</li></ul><pre>import io.github.resilience4j.circuitbreaker.annotation.CircuitBreaker;<br><br>@Service<br>@AllArgsConstructor<br>public class GetStarWarCharacterByIdService {<br><br>    private final StarWartRestApiFeignClient starWartRestApiFeignClient;<br>    private final FallBackService fallBackService;<br><br><br>    @CircuitBreaker(name = &quot;GetStarWarCharacterByIdService&quot;, fallbackMethod = &quot;fallBackGetStarWarCharacterById&quot;)<br>    //@Retry(name = &quot;GetStarWarCharacterByIdService&quot;, fallbackMethod = &quot;fallBackGetStarWarCharacterById&quot;)<br>    public StarWarsCharacter execute(Integer id) {<br>        if (new Random().nextBoolean()) {<br>            return starWartRestApiFeignClient.getStarWarsCharacterById(id);<br>        }<br>        throw new RuntimeException(&quot;The Darth Sith&quot;);<br>    }<br><br>    public StarWarsCharacter fallBackGetStarWarCharacterById(Integer id, Exception ex) {<br>        return fallBackService.execute(id, ex);<br>    }<br>}</pre><h3>Fallback</h3><ul><li>The fallback method is called when the original operation fails. It provides an alternative response, allowing the application to continue functioning.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YPahqtlOJK_ywWO6_ulVYA.jpeg" /></figure><pre>@Service<br>public class FallbackService {<br><br>    public StarWarsCharacter fallbackGetStarWarCharacterByIdService(Integer id, Exception ex) {<br>        return new StarWarsCharacter(&quot;Angelo Zero - &quot; + ex.getMessage(), null);<br>    }<br>}</pre><h3>Configuration</h3><ul><li>Make sure the following dependencies are included in your pom.xml:</li></ul><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;<br>    &lt;artifactId&gt;spring-cloud-starter-circuitbreaker-resilience4j&lt;/artifactId&gt;<br>&lt;/dependency&gt;<br>&lt;dependency&gt;<br>    &lt;groupId&gt;org.aspectj&lt;/groupId&gt;<br>    &lt;artifactId&gt;aspectjweaver&lt;/artifactId&gt;<br>    &lt;version&gt;1.9.7&lt;/version&gt;<br>&lt;/dependency&gt;</pre><ul><li>Finally, ensure that the main class is annotated with @EnableAspectJAutoProxy:</li></ul><pre>@EnableAspectJAutoProxy<br>@EnableFeignClients<br>@SpringBootApplication<br>public class Resilience4jApplication {<br><br>    public static void main(String[] args) {<br>        SpringApplication.run(Resilience4jApplication.class, args);<br>    }<br><br>}</pre><ul><li>The application will be available at http://localhost:8080/api/{id}, where {id} is the ID of the Star Wars character you wish to query.</li><li>In the application.properties file, the following configurations should be set:</li></ul><pre># Circuit Breaker Config<br># Size of the window used to calculate the failure rate<br>resilience4j.circuitbreaker.instances.GetStarWarCharacterByIdService.slidingWindowSize=3<br><br># Minimum number of calls required before calculating the failure rate<br>resilience4j.circuitbreaker.instances.GetStarWarCharacterByIdService.minimumNumberOfCalls=6<br><br># Timeout duration for the service call (2 seconds)<br>resilience4j.timelimiter.instances.GetStarWarCharacterByIdService.timeoutDuration=2s<br><br># Allows cancellation of calls that are in progress<br>resilience4j.timelimiter.instances.GetStarWarCharacterByIdService.cancelRunningFuture=true<br><br># Failure rate threshold that triggers the opening of the Circuit Breaker (in %)<br>resilience4j.circuitbreaker.instances.GetStarWarCharacterByIdService.failureRateThreshold=50<br><br># Time in milliseconds that the Circuit Breaker stays open before attempting to switch to HALF_OPEN (1 second)<br>resilience4j.circuitbreaker.instances.GetStarWarCharacterByIdService.waitDurationInOpenState=1000<br><br># Number of calls allowed in HALF_OPEN state to test if the service is available again<br>resilience4j.circuitbreaker.instances.GetStarWarCharacterByIdService.permittedNumberOfCallsInHalfOpenState=3</pre><ul><li>You can create a configuration class (@Bean) to visualize the logs/state transitions of the circuit.</li><li><strong>CLOSED → OPEN → HALF-OPEN</strong></li></ul><pre>@Configuration<br>public class CircuitBreakerLogConfig {<br><br>    @Bean<br>    public RegistryEventConsumer&lt;CircuitBreaker&gt; circuitBreakerRegistryEventConsumerConfig() {<br>        return new RegistryEventConsumer&lt;CircuitBreaker&gt;() {<br>            @Override<br>            public void onEntryAddedEvent(EntryAddedEvent&lt;CircuitBreaker&gt; entryAddedEvent) {<br>                System.out.println(entryAddedEvent.getAddedEntry().getEventPublisher()<br>                        .onStateTransition(event -&gt; System.out.println(&quot;\n\n&quot; + event)));<br>            }<br><br>            @Override<br>            public void onEntryRemovedEvent(EntryRemovedEvent&lt;CircuitBreaker&gt; entryRemoveEvent) {<br><br>            }<br><br>            @Override<br>            public void onEntryReplacedEvent(EntryReplacedEvent&lt;CircuitBreaker&gt; entryReplacedEvent) {<br><br>            }<br>        };<br>    }<br>}</pre><p>To see more details, access the complete project on my <a href="https://github.com/angelozero/java-resilience4j">GitHub AngeloZero</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f8dc6c29f5bf" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/springboot-with-resilience4j-f8dc6c29f5bf">SpringBoot with Resilience4j</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring AI and Ollama]]></title>
            <link>https://medium.com/@angelozero/spring-ai-and-olllama-1a5193027e1a?source=rss-f3da207c5d78------2</link>
            <guid isPermaLink="false">https://medium.com/p/1a5193027e1a</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[spring-ai]]></category>
            <category><![CDATA[ollama]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Angelo Ferreira]]></dc:creator>
            <pubDate>Thu, 13 Feb 2025 02:14:55 GMT</pubDate>
            <atom:updated>2025-02-13T11:34:14.656Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Integration with DeepSeek</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/541/1*cTtUxFuTePgc0RoKYNZVHA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*tYCsT543DtXgh8XyHcB7mQ.png" /></figure><h3>What is Ollama Chat</h3><ul><li><strong>Ollama</strong>: Allows users to run language models locally and integrates with <strong>Spring AI</strong> through the <strong>OllamaChatModel</strong> API.</li><li><strong>OpenAI Compatibility</strong>: Ollama provides an endpoint compatible with the OpenAI API, allowing Spring AI to connect to an Ollama server.</li></ul><h3>Prerequisites</h3><ul><li>Access to an Ollama instance is required, which can be installed locally or run in containers (like Testcontainers) or on Kubernetes.</li><li>Models can be downloaded from the Ollama model repository or from models available on Hugging Face.</li></ul><h3>Hello World with Ollama and Spring AI</h3><h4><strong>Installing Ollama</strong></h4><ul><li>To view the complete documentation, visit <a href="https://docs.spring.io/spring-ai/reference/api/chat/ollama-chat.html">Spring AI with Ollama</a></li><li>Go to <a href="https://ollama.com/library/deepseek-r1">Ollama</a> and download the <strong>DeepSeek-R1</strong> version.</li><li>After installation, check if Ollama is running by accessing the link <a href="http://localhost:11434/">http://localhost:11434/.</a></li><li>If everything is correct, you should see the following message in your browser: Ollama is running.</li></ul><h4><strong>Creating a Java Application</strong></h4><ul><li>Create an application with <a href="https://start.spring.io/">Spring Initializr</a>.</li><li>Add the following dependencies during creation:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/547/1*nqASx6UPQtZqpfhvQyII9Q.png" /></figure><ul><li>After the project is created, import it into <a href="https://www.jetbrains.com/pt-br/idea/download/">IntelliJ</a>.</li><li>Check the pom.xml file to see if the following dependency has been added:</li></ul><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;org.springframework.ai&lt;/groupId&gt;<br>    &lt;artifactId&gt;spring-ai-ollama-spring-boot-starter&lt;/artifactId&gt;<br>&lt;/dependency&gt;</pre><ul><li>Now, in your application.properties file, add the following properties:</li></ul><pre>spring.application.name=spring-ai-deepseek<br>spring.ai.ollama.base-url=http://localhost:11434/<br>spring.ai.ollama.chat.options.model=deepseek-r1:1.5b</pre><ul><li>The value for spring.ai.ollama.chat.options.model= needs to match what was used when Ollama was installed.</li><li><em>Ex.: </em><em>ollama run deepseek-r1:1.5b</em></li><li>First, create a configuration class to provide communication with the <em>client</em>:</li></ul><pre>import org.springframework.ai.chat.client.ChatClient;<br>import org.springframework.context.annotation.Bean;<br>import org.springframework.context.annotation.Configuration;<br><br>@Configuration<br>public class ChatClientConfig {<br><br>    @Bean<br>    public ChatClient chatClient(ChatClient.Builder chatClientBuilder) {<br>        return chatClientBuilder.build();<br>    }<br>}</pre><ul><li>Create a service class that calls the methods for communication with the AI:</li></ul><pre>import lombok.AllArgsConstructor;<br>import org.springframework.ai.chat.client.ChatClient;<br>import org.springframework.stereotype.Service;<br>import reactor.core.publisher.Flux;<br><br>@Service<br>@AllArgsConstructor<br>public class ChatAIService {<br><br>    private final ChatClient chatClient;<br><br>    public String askToDeepSeekAI(String question) {<br>        return chatClient.prompt(question).call().content();<br>    }<br><br>    public Flux&lt;String&gt; askToDeepSeekAiWithStream(String question) {<br>        return chatClient.prompt(question).stream().content();<br>    }<br>}</pre><ul><li>Finally, create a <em>Controller</em> to test the calls:</li></ul><pre>@RestController<br>@RequestMapping(&quot;/ai-api&quot;)<br>@AllArgsConstructor<br>public class ChatAIController {<br><br>    private final ChatAIService service;<br><br>    @PostMapping<br>    public ResponseEntity&lt;String&gt; askToAi(@RequestBody QuestionRequest questionRequest) {<br>        return ResponseEntity.ok(service.askToDeepSeekAI(questionRequest.question()));<br>    }<br><br>    @PostMapping(&quot;/stream&quot;)<br>    public ResponseEntity&lt;Flux&lt;String&gt;&gt; askToAiWithStream(@RequestBody QuestionRequest questionRequest) {<br>        return ResponseEntity.ok(service.askToDeepSeekAiWithStream(questionRequest.question()));<br>    }<br>}</pre><ul><li>To test the API locally, access <a href="http://localhost:8080/ai-api.">http://localhost:8080/ai-api.</a></li><li>Body for request call:</li></ul><pre>{<br>    &quot;question&quot;: &quot;Short answer: why is the color of the sky blue?&quot;<br>}</pre><ul><li>Response from API:</li></ul><pre>&lt;think&gt;<br>    Okay, so I&#39;m trying to figure out why the sky is blue. I remember that when I look up at the sky outside, it&#39;s mostly clear blue. But why does that happen? I think it has something to do with how light interacts with the atmosphere.<br><br>    First off, I know that the sky is a layer of gas and plasma in our atmosphere. Light travels through this medium, which probably causes some scattering or absorption of the blue light. Maybe things like raindrops or smoke scatter the blue color out of view.<br><br>    Wait, there&#39;s something about Rayleigh scattering. Isn&#39;t that when shorter wavelength light scatters more than longer wavelengths? Blue has a shorter wavelength than red and yellow, right? So if blue light is scattered more, it leaves us with a darker sky at those parts where the blue light was absorbed or scattered back towards us.<br><br>    I also recall something about the greenhouse effect. I think gases in the atmosphere, especially things like carbon dioxide and water vapor, absorb and reradiate blue light. This causes longer wavelengths, like green and brown, to heat the Earth more than they would if there were no greenhouse gases. So we get warmer temperatures at higher latitudes because their atmospheric gases absorb and reemitting those blue lights.<br><br>    But wait, isn&#39;t blue also part of the UV? No, I think UV light is much shorter wavelength, which is why it&#39;s absorbed by things like ozone in Earth&#39;s atmosphere but doesn&#39;t contribute as much to the sky. Also, the Earth&#39;s atmosphere absorbs a lot of visible and near-infrared radiation, so we don&#39;t see all the colors. This filtering out would leave blue as the dominant color.<br><br>    I&#39;ve also heard about something called the cosmic ray effect, where high-energy particles interact with the atmosphere, causing absorption or ionization that affects the scattering of light. This might contribute to some blue hues in the sky, though I&#39;m not entirely sure how much it contributes compared to Rayleigh scattering.<br><br>    So putting this together: Rayleigh scattering causes blue light to scatter away from our line of sight, leaving us with a darker sky at those areas. The greenhouse effect adds another layer by absorbing and reradiating blue light, making the higher latitudes warmer than they would otherwise be. And both Rayleigh scattering and UV absorption contribute to the filtering that makes blue the dominant color in the sky.<br><br>    I think I&#39;ve covered most of the factors involved, but I&#39;m not 100% sure if I missed anything. Maybe other atmospheric processes like ozone layer play a role, but the primary reasons are Rayleigh scattering and the greenhouse effect.<br>&lt;/think&gt;</pre><pre>The sky appears blue due to several atmospheric effects:<br><br>1. **Rayleigh Scattering**: Blue light has a shorter wavelength than red or yellow light. According to Rayleigh&#39;s law, this causes more of the blue light to scatter away from our line of sight, leaving us with a darker sky at those areas.<br><br>2. **Greenhouse Effect**: The atmosphere absorbs and reradiates blue light, especially during the day, causing longer wavelengths (green and brown) to heat Earth more than usual, leading to higher temperatures in polar regions.<br><br>3. **UV Absorption**: The atmosphere absorbs UV radiation and some visible light, contributing to filtering that makes blue dominant.<br><br>4. **Cosmic Ray Interactions**: High-energy particles interact with the atmosphere, potentially causing absorption or ionization, adding another layer of filtering.<br><br>These factors collectively contribute to the blue color we observe in the sky.</pre><p>See the complete project on my <a href="https://github.com/angelozero/java-deepseek">GitHub AngeloZero</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1a5193027e1a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Explorando Spring Security 6.4]]></title>
            <link>https://medium.com/@angelozero/autoriza%C3%A7%C3%A3o-com-spring-security-6-4-d6569a384076?source=rss-f3da207c5d78------2</link>
            <guid isPermaLink="false">https://medium.com/p/d6569a384076</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[spring-boot-3]]></category>
            <category><![CDATA[spring-security]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Angelo Ferreira]]></dc:creator>
            <pubDate>Fri, 20 Sep 2024 02:59:34 GMT</pubDate>
            <atom:updated>2024-09-20T13:35:39.491Z</atom:updated>
            <content:encoded><![CDATA[<p>Pt. 2</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*b4FC7XFxPZgSUys4rx9cSw.png" /></figure><h3>Autenticação X Autorização</h3><h4>Autenticação</h4><p><em>Quem está tentando acessar um determinado recurso?</em></p><h4>Autorização</h4><p><em>Dado que sei quem esta tentando acessar o recurso, ele tem permissão para isso ?</em></p><p>Spring Security 6.4 traz métodos de segurança que permite você separar sua lógica de autorização da lógica de domínio. E neste artigo vou apresentar algumas das suas novas funcionalidades.</p><h4>Utilizando regras de “pós” execução de método para aplicar autorização com Spring Security</h4><p>Voltando para nossa interface BankAccountInterface, vamos fazer uma nova modificação para utilizar o <strong>Spring Security</strong> e implementar uma <em>pós</em> validação de segurança.</p><p>No método findById(), queremos que, após a sua execução, seja validado se o retorno da informação, neste caso, o proprietário da conta, que tenha o mesmo nome que o usuário logado na sessão. Para isso, usaremos a anotação @PostAuthorize() e informaremos uma palavra-chave chamada returnObject, que nos dará acesso ao objeto retornado, ou seja, <em>BankAccount</em>.</p><p>Com a informação de BankAccount e considerando que o <strong>Spring Security</strong> tem acesso aos dados de quem está <em>logado</em> através do SecurityContextHolder, podemos criar uma simples validação.</p><p>A validação será a seguinte:</p><ul><li>Verificamos se o objeto <em>BankAccount</em> retornado não é nulo e se o seu proprietário (returnObject?.owner) é igual aos dados do usuário logado (authentication?.name).</li><li>Se ambas as condições forem verdadeiras, então o acesso ao objeto retornado será autorizado.</li></ul><p>Essa implementação irá garantir que apenas o proprietário da conta possa acessar suas informações, aumentando a segurança da aplicação.</p><pre>public interface BankAccountInterface {<br>    <br>    // returnObject? -&gt; to avoid null pointer when access BankAccountData<br>    // .owner -&gt; the BankAccountData owner<br>    // authentication? -&gt; to avoid null pointer when access SecurityContextHolder<br>    // .name -- the name of the user in SecurityContextHolder<br>    @PostAuthorize(&quot;returnObject?.owner == authentication?.name&quot;)<br>    BankAccountData findById(Integer id);<br><br>    @PostAuthorize(&quot;returnObject?.owner == authentication?.name&quot;)<br>    BankAccountData getById(Integer id);<br>}</pre><p>Ainda na classe BankAccountInterface, vamos aproveitar para reutilizar uma única <em>annotation</em> que desempenhe a mesma função, removendo assim a duplicidade de regra.</p><p>Vamos criar uma nova <em>annotation</em> chamada PosReadBankAccount, na qual centralizaremos toda a lógica de verificação do nome do usuário, além de adicionar a lógica de verificação da <em>role</em> que o usuário autenticado na sessão possui.</p><p><strong>A regra ficará assim</strong>:</p><ul><li>Após fazer a consulta, verificamos se o nome do proprietário (owner) é igual ao nome do usuário da sessão (name).</li><li>Se for verdadeiro, retornamos o objeto (dados da conta).</li><li>Caso contrário, verificamos se a <em>role</em> do usuário da sessão possui nível de privilégio para acessar os dados do objeto retornado.</li><li>Se essa verificação for verdadeira, também retornamos o objeto (dados da conta).</li><li>Se for falsa, retornamos uma falha de <em>Access Denied</em>.</li></ul><pre>@Retention(RetentionPolicy.RUNTIME)<br>@PostAuthorize(&quot;returnObject?.owner == authentication?.name or hasRole(&#39;ADMIN&#39;)&quot;)<br>public @interface PosReadBankAccount {}</pre><blockquote>Para mais informações sobre as palavras chave <em>returnObject</em>, <em>authentication</em> e <em>hasRole</em> acesse a documentação da classe <a href="https://docs.spring.io/spring-security/site/docs/current/api/org/springframework/security/access/expression/SecurityExpressionRoot.html">SecurityExpressionRoot</a>.</blockquote><p>Com a <em>annotation </em>criada, as alterações finais na interface deve ficar assim:</p><pre>public interface BankAccountInterface {<br>  @PosReadBankAccount<br>  BankAccountData findById(Integer id);<br>  <br>  @PosReadBankAccount<br>  BankAccountData getById(Integer id);<br>}</pre><p>Agora, precisamos fazer uma simples alteração no nosso teste para entendermos melhor como o <em>Spring Security</em> funciona ao utilizá-lo. Na nossa classe de teste, vamos alterar para que as configurações de um usuário criado sejam feitas por uma <em>factory</em> chamada AuthorizationProxyFactory.</p><pre>AuthorizationProxyFactory factory<br>        = AuthorizationAdvisorProxyFactory.withDefaults();<br><br>private final BankAccountInterface service = (BankAccountInterface) <br>                                    factory.proxy(new BankAccountService());</pre><p>Por fim, lembra do nosso WithMockUserAdmin?? Ele será testado agora também! Quero que, se o nome do proprietário da conta não coincidir com o usuário logado, a lógica verifique o tipo de acesso que ele possui. Se o tipo de acesso for do tipo <em>ADMIN</em>, então o objeto (dados da conta) deve ser retornado.</p><pre>@Test<br>@DisplayName(&quot;Should find the bank account with success with role ADMIN&quot;)<br>@WithMockUserAdmin<br>void findByIdWithAdminGranted() {<br>  service.findById(1);<br>}</pre><p>E para garantir que a regra de <em>role</em> está sendo executada criei um novo teste para um usuário que não tem nome e nem privilégio de <em>ADMIN</em></p><p><em>Criação do usuário</em></p><pre>@Retention(RetentionPolicy.RUNTIME)<br>@WithMockUser(roles = {&quot;NOT_ADMIN&quot;})<br>public @interface WithMockUserNotAdmin {}</pre><p><em>Criação do teste</em></p><pre>@Test<br>@DisplayName(&quot;Should fail to find the bank account with not admin role&quot;)<br>@WithMockUserNotAdmin<br>void findByIdWhenDeniedWithNotAdminRole() {<br>    assertThatExceptionOfType(AuthorizationDeniedException.class)<br>            .isThrownBy(() -&gt; service.findById(1))<br>            .withMessage(&quot;Access Denied&quot;);<br>}</pre><p>Com essas novas alterações ja podemos remover a regra de validação que esta sendo feita na nossa classe de serviço BankAccountServiceProxy.</p><pre>@Service<br>@AllArgsConstructor<br>public class BankAccountServiceProxy implements BankAccountInterface {<br><br>private final BankAccountService service;<br>  @Override<br>  public BankAccountData findById(Integer id) {<br>      return service.findById(id);<br>  }<br>  @Override<br>  public BankAccountData getById(Integer id) {<br>      return service.findById(id);<br>  }<br>}</pre><h4>Inserindo regras de validação de segurança em nossas entidades de domínio</h4><p>Já sabemos que um usuário com a <em>role</em> <strong>ADMIN</strong> pode acessar a conta, mesmo não sendo o usuário logado, mas isso faz sentido este usuário ter acesso ao número da conta? Para isso vamos então retornar um valor <em>mascarado</em>, utilizando uma regra do <strong>Spring Security</strong> que irá exibir a conta com asteriscos em vez do número completo. É importante lembrar que BankAccountData não está nas informações de <em>proxy</em> que usamos para acessar os dados do usuário na sessão. Para resolver isso, vamos implementar a annotation @AuthorizeReturnObjectna nossa annotation PostReadBankAccount . Essa nova annotation permite aplicar regras de acesso específicas com base no resultado que um método retorna, facilitando a lógica de segurança.</p><blockquote>Para mais detalhes, consulte a documentação da @<a href="https://docs.spring.io/spring-security/reference/servlet/authorization/method-security.html#_using_authorizereturnobject_at_the_class_level">AuthorizeReturnObject</a> .</blockquote><p>Vamos também simplificar nossa aplicação, removendo trechos de código desnecessários, já que discutimos o funcionamento de diversos componentes. Vamos remover a implementação da interface BankAccountServiceProxy, deixando apenas a implementação e o serviço na classe BankAccountService.</p><pre>@Service<br>@AllArgsConstructor<br>public class BankAccountServiceProxy {<br><br>@Autowired<br>    private final BankAccountService service;<br>    public BankAccountData findById(Integer id) {<br>        return service.findById(id);<br>    }<br>    public BankAccountData getById(Integer id) {<br>        return service.findById(id);<br>    }<br>}</pre><p>E para que os testes continuem funcionando adiciono a annotation @EnableMethodSecurity na classe principal Security64Application</p><pre>@SpringBootApplication<br>@EnableMethodSecurity<br>public class Security64Application {<br><br>public static void main(String[] args) {<br>        SpringApplication.run(Security64Application.class, args);<br>    }<br>}</pre><p>Mas e a máscara ? Para isso vamos criar uma classe do tipo <em>handler</em> para que possa interceptar qualquer falha que houver de segurança.</p><ul><li>Se caso atender uma regra específica podemos tratar o retorno da maneira como quisermos.</li><li>A classe criada se chama MaskAuthorizationDeniedHandler que deve implementar MethodAuthorizationDeniedHandler, e nela pedimos apenas para retornar uma sequência de asteriscos.</li></ul><pre>@Component<br>public class MaskAuthorizationDeniedHandler <br>                                implements MethodAuthorizationDeniedHandler {<br><br>@Override<br>    public Object handleDeniedInvocation(MethodInvocation methodInvocation, <br>                                    AuthorizationResult authorizationResult) {<br>        return &quot;****&quot;;<br>    }<br>}</pre><p>E na nossa classe BankAccountData vamos adicionar uma nova <em>annotation</em> que se caso houver uma falha (<em>nome do usuário da sessão não corresponder ao nome do proprietário da conta</em>) ao tentar recuperar o numero da conta (getAccountNumber()), vamos informar qual o tipo de tratamento que aquela <em>exception</em> deve ter.</p><ul><li>Para isso vamos adicionar a <em>annotation</em> @HandleAuthorizationDenied informando a ela qual será sua classe <em>handler</em> que deverá tratar a falha (handlerClass = MaskAuthorizationDeniedHandler.class)</li></ul><pre>@Builder<br>@AllArgsConstructor<br>@NoArgsConstructor<br>@JsonSerialize(as = BankAccount.class)<br>public class BankAccount extends SecurityData {<br><br>    private Integer id;<br>    private String owner;<br>    private String accountNumber;<br>    private double balance;<br>    <br>    @PreAuthorize(&quot;this.owner == authentication?.name&quot;)<br>    @HandleAuthorizationDenied(handlerClass = MaskAuthorizationDeniedHandler.class)<br>    public String getAccountNumber() {<br>        return accountNumber;<br>    }<br>}</pre><p>E por fim vamos validar com os seguintes testes</p><ul><li><em>Deve ver o número da conta com sucesso</em></li></ul><pre>@Test<br>@DisplayName(&quot;Should find the bank account with success see the account number&quot;)<br>@WithMockUserAngelo<br>void findByIdWithSuccessAndSeeTheAccountNumber() {<br>    var response = service.findById(1);<br>    assertEquals(&quot;1234&quot;, response.getAccountNumber());<br>}</pre><ul><li><em>Deve ver asteriscos no lugar do numero da conta</em></li></ul><pre>@Test<br>@DisplayName(&quot;Should find the bank account with success but cannot see the account number&quot;)<br>@WithMockUserAdmin<br>void findByIdWithSuccessButCannotSeeTheAccountNumber() {<br>    var response = service.findById(1);<br>    assertEquals(&quot;****&quot;, response.getAccountNumber());<br>}</pre><p>Por fim lembre-se que podemos ainda fazer qualquer tipo de validação dentro do nosso <em>handler</em> criado pois lá temos os dados de proxy, sendo assim podendo criar nossas próprias regras customizadas.</p><h4>Utilizando lógicas de pré execução de método para aplicar autorização com Spring Security</h4><p>Voltando para nossa interface BankAccountInterface vamos fazer mais uma modificação. Quero utilizar o <strong>Spring Security</strong> para que faça agora uma <em>Pré</em> validação de segurança. Vamos criar mais um método fictício que agora deve salvar uma nova conta bancária. Para isso vamos adicionar na nossa interface o seguinte método</p><pre>void saveBankAccount(BankAccountData bankAccountDataToSave);</pre><p>Ainda no método saveBankAccount() quero que ele faça uma verificação do objeto que esta sendo persistido comparando o nome do proprietário da conta com o nome do usuário logado em sessão, e isso deve ocorrer antes dos dados serem &quot;<em>persistidos</em>&quot;</p><p>Para isso vou adicionar então uma nova <em>annotation</em> chamada @PreAuthorize() e dentro dela passar a referência do objeto para recuperar o nome do proprietário da conta e comparar com o nome do usuário logado em sessão.</p><pre>@PreAuthorize(&quot;#bankAccountDataToSave?.owner == authentication?.name&quot;)<br>void saveBankAccount(BankAccountData bankAccountDataToSave)</pre><p>E para garantir que tudo continua funcionando vamos criar mais dois testes</p><ul><li>Um aonde um usuário que esta logado esta tentando salvar uma conta da qual ele tem acesso (a dele mesmo no caso).</li></ul><pre>@Test<br>@DisplayName(&quot;Should save a bank account with success&quot;)<br>@WithMockUserAngelo<br>void shouldSaveABankAccountWithSuccess() {<br>    service.saveBankAccount(mockBankAccountAngelo());<br>}</pre><ul><li>E outro aonde o usuário logado não tem permissão para salvar a conta da qual não o pertence.</li></ul><pre>@Test<br>@DisplayName(&quot;Should not save a bank account&quot;)<br>@WithMockUserJake<br>void shouldSNotSaveABankAccount() {<br>    assertThatExceptionOfType(AuthorizationDeniedException.class)<br>            .isThrownBy(() -&gt; service.saveBankAccount(mockBankAccountAngelo()))<br>            .withMessage(&quot;Access Denied&quot;);<br>}</pre><p>Agora vou adicionar mais um método que irá atualizar os dados bancários, a regra para autorização continua sendo a mesma</p><pre>@PreAuthorize(&quot;#bankAccountDataToUpdate?.owner == authentication?.name&quot;)<br>void updateBankAccount(BankAccountData bankAccountDataToUpdate);</pre><p>E adicionei também mais dois cenários de teste que segue a mesma lógica dos dois anteriores</p><pre>@Test<br>@DisplayName(&quot;Should update a bank account with success&quot;)<br>@WithMockUserAngelo<br>void shouldUpdateABankAccountWithSuccess() {<br>    service.updateBankAccount(mockBankAccountAngelo());<br>}</pre><pre>@Test<br>@DisplayName(&quot;Should not update a bank account&quot;)<br>@WithMockUserJake<br>void shouldSNotUpdateABankAccount() {<br>    assertThatExceptionOfType(AuthorizationDeniedException.class)<br>            .isThrownBy(() -&gt; service.updateBankAccount(mockBankAccountAngelo()))<br>            .withMessage(&quot;Access Denied&quot;);<br>}</pre><p>Até aqui tudo certo, mas repare que na nossa interface estamos duplicando a <em>annotation</em> @PreAuthorize e alterando apenas o nome da referência do objeto que deve ser verificado. Como podemos então evitar essa duplicação ?</p><p>Para isso vamos criar uma nova <em>annotation</em> e utilizar um recurso muito interessante do <em>Spring Security</em> chamado <em>templates</em></p><p>Basicamente iremos informar, ao usar a nova <em>annotation</em>, qual o nome da referência do objeto, e na regra da <em>annotation</em>, independente do nome que o objeto tem, ela sempre irá conseguir buscar o valor correto.</p><p>Ao declararmos um atributo do tipo String com o nome value iremos conseguir utiliza-lo para ser a nossa referência do objeto que será passado tanto no método saveBankAccount() quanto no método updateBankAccount()</p><p>A <em>annotation</em> que vamos criar irá se chamar PreWriteBankAccount e ela fica assim:</p><pre>@Retention(RetentionPolicy.RUNTIME)<br>@PreAuthorize(&quot;{value}?.owner == authentication?.name&quot;)<br>public @interface PreWriteBankAccount {<br>    String value();<br>}</pre><p>E na interface BankAccountInterface fazemos a seguinte alteração</p><pre>@PreWriteBankAccount(&quot;#bankAccountDataToSave&quot;)<br>void saveBankAccount(BankAccountData bankAccountDataToSave);<br><br>@PreWriteBankAccount(&quot;#bankAccountDataToUpdate&quot;)<br>void updateBankAccount(BankAccountData bankAccountDataToUpdate);</pre><p>Por fim, e se caso quisermos testar a aplicação fazendo chamadas <em>rest</em>, adicionei ao projeto um simples fluxo aonde utilizo toda a estrutura aqui documentada. O mais importante e apenas para etendermos como as coisas estão funcionando, crei um <em>bean</em> aonde insiro manualmente alguns usuários em sessão e com isso tento fazer algumas validações</p><ul><li>o <em>bean</em> se chama SpringSecurity e ele esta assim:</li></ul><pre>@Configuration<br>public class SpringSecurity {<br><br>@Bean<br>    PrePostTemplateDefaults prePostTemplateDefaults() {<br>        return new PrePostTemplateDefaults();<br>    }<br>    @Bean<br>    UserDetailsService userDetailsService() {<br>        UserDetails angelo = User.builder()<br>                .username(&quot;angelo&quot;)<br>                .password(&quot;{noop}password-123&quot;)<br>                .roles(&quot;MASTER&quot;)<br>                .build();<br>        UserDetails jake = User.builder()<br>                .username(&quot;jake&quot;)<br>                .password(&quot;{noop}password-456&quot;)<br>                .roles(&quot;TOP&quot;)<br>                .build();<br>        UserDetails dumb = User.builder()<br>                .username(&quot;dumb&quot;)<br>                .password(&quot;{noop}password-789&quot;)<br>                .roles(&quot;UP&quot;)<br>                .build();<br>        return new InMemoryUserDetailsManager(angelo, jake, dumb);<br>    }<br>}</pre><p>Para terstarmos como se fosse uma chamada <em>http</em> vou deixar de exemplo 3 cenários de teste, vale resssaltar que a classe / objeto que está sendo retornado como resposta precisa ter algumas configurações pois como ela se torna uma parte do proxy a biblioteca de desserialização jackson por si só não irá conseguir converter o dado para json</p><ul><li>O retorno sem desserialização</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2j4S7cbk51WOqvzcVJMmfg.png" /></figure><p>Para que o retorno esteja correto precisamos da <em>annotation</em> @JsonSerialize() e do @Data do <em>Lombok</em></p><ul><li>A classe fica assim:</li></ul><pre>import com.fasterxml.jackson.databind.annotation.JsonSerialize;<br>// some imports here<br><br>@Data<br>@Builder<br>@AllArgsConstructor<br>@NoArgsConstructor<br>@JsonSerialize(as = BankAccount.class)<br>public class BankAccount {<br>    //... some code here</pre><p>Agora subindo a aplicação e chamando a rota GET</p><p>- /api/v1/bank-account/{id}</p><p><em>testes via </em><a href="https://www.postman.com/downloads/"><em>Postman</em></a></p><ul><li>Sucesso ao estar logado com o usuário proprietário da conta</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jI2Sb_RRVziKmfO9dAgLhw.png" /></figure><ul><li>Sucesso ao estar com um usuário que tem privilégio de ver alguns dados da conta mas não seu número</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FMMGVsiECO8Tcz1bhOxx9g.png" /></figure><ul><li>Falha ao estar logado com um usuário que não deve ter acesso a conta da qual não é sua</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vN0jFoXxF7pn800D8DdPig.png" /></figure><p>Enfim chegamos ao fim e com isso conseguimos passar por algumas <em>features</em> que o <em>Spring Security</em> tem a nos oferecer.</p><ul><li>Para o projeto de teste veja o pacote zzz nele tem todas as classes utilizadas na explicação e todo o código utilizado, os comentários foram deixados propositalmente para que você consiga acompanhar a evolução do código entendendo cada etapa.</li><li>Para a parte <em>rest</em> é só seguir os demais pacotes, simulei uma pequena aplicação separada por camadas e respeitando suas funcionalidades.</li><li>Como principal referência para este projeto, foi utilizado a apresentação <a href="https://youtu.be/9eoi1TViceM">Let’s Explore Spring Security 6.4 (SpringOne 2024)</a></li><li>Segue o repositório com o código no <a href="https://github.com/angelozero/spring-security64">GitHub — AngeloZero</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d6569a384076" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>