<?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 Lcbader on Medium]]></title>
        <description><![CDATA[Stories by Lcbader on Medium]]></description>
        <link>https://medium.com/@lcbader06?source=rss-098ee73973d0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*q7lX21jR2m1TKRjs</url>
            <title>Stories by Lcbader on Medium</title>
            <link>https://medium.com/@lcbader06?source=rss-098ee73973d0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 19:43:28 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@lcbader06/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How I built one authenticated Java 17 backend that serves four different clients while keeping…]]></title>
            <link>https://medium.com/@lcbader06/how-i-built-one-authenticated-java-17-backend-that-serves-four-different-clients-while-keeping-dce730eb7957?source=rss-098ee73973d0------2</link>
            <guid isPermaLink="false">https://medium.com/p/dce730eb7957</guid>
            <dc:creator><![CDATA[Lcbader]]></dc:creator>
            <pubDate>Sat, 14 Nov 2026 19:34:23 GMT</pubDate>
            <atom:updated>2026-11-14T19:34:23.414Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><strong><em>Building a Full-Stack Moroccan Darija Translator with Java, Gemini, Chrome, and React Native</em></strong></blockquote><p><em>How I built one authenticated Java 17 backend that serves four different clients while keeping credentials and the Gemini API key out of the wrong places.</em></p><p>Moroccan Darija is spoken every day by millions of people, but it is still underserved by many conventional translation tools. Even when a translation is technically understandable, it can sound too formal, too literal, or closer to Modern Standard Arabic than the language Moroccans actually use in conversation.</p><p>For my second Advanced Programming Paradigms project, I wanted to build something more complete than a single translation page. The result was <strong>Darija Translator</strong>: a full-stack translation platform powered by Gemini, with a Java backend and four separate clients:</p><ul><li>A Python command-line client</li><li>A PHP web client</li><li>A Chrome Manifest V3 side-panel extension</li><li>An Expo/React Native mobile application tested on a physical iPhone</li></ul><p>The goal was not only to make the translation work. I wanted the system to have a clear architecture, authentication, proper error handling, automated verification, secure secret management, and documentation that another developer could actually follow.</p><h3>The Architecture</h3><p>The system follows a client-server design. Every client sends the same JSON request to one REST endpoint:</p><pre>{<br>  &quot;text&quot;: &quot;What time does the next train leave?&quot;,<br>  &quot;sourceLanguage&quot;: &quot;English&quot;<br>}</pre><p>The backend validates the request, authenticates the caller, constructs a controlled Gemini prompt, sends the provider request, extracts the translated text, and returns a consistent JSON response.</p><p>This approach kept the clients intentionally thin. None of them communicates with Gemini directly, and none of them receives or stores the Gemini API key. Their responsibility is limited to collecting input, sending authenticated requests to the backend, and presenting the returned Darija translation.</p><p>The public health endpoint is available at GET /api/health, while translation is handled by the protected POST /api/translate endpoint.</p><p><em>[Insert the deployment diagram here.]</em></p><h3>Building the Java Backend</h3><p>The backend was built with <strong>Java 17</strong>, <strong>Maven</strong>, <strong>Jakarta REST</strong>, and <strong>Open Liberty</strong>. I used the Maven Wrapper so the project can be built without requiring a separately installed Maven version.</p><p>The main backend responsibilities are separated into focused classes:</p><ul><li>TranslatorResource exposes the REST translation endpoint, validates input, and maps success or provider failures to HTTP responses.</li><li>GeminiTranslationClient uses the JDK HttpClient to communicate with the Gemini API.</li><li>ProviderConfiguration loads the API base URL, model, timeout, and private API key from the process environment.</li><li>TranslationProviderException represents timeouts, rejected requests, unavailable providers, configuration failures, and unusable responses.</li></ul><p>The request boundary rejects missing or blank text with HTTP 400 before contacting the provider. Provider failures are converted into controlled JSON errors instead of exposing raw stack traces or sensitive information to the client.</p><p>The Gemini response is parsed from candidates[0].content.parts[].text. The backend also returns useful metadata, including the configured model, while keeping private configuration values out of the response.</p><h3>Authentication and Secret Management</h3><p>The translation endpoint is protected with HTTP Basic authentication implemented through <strong>Jakarta Authentication 3.0</strong>. Open Liberty applies the security constraint only to POST /api/translate; the health endpoint remains public.</p><p>The backend username, password, keystore password, Gemini model, and Gemini API key are supplied through environment variables. Startup validation prevents the application from silently running with missing security configuration.</p><p>One rule guided the entire security design:</p><blockquote><em>The Gemini API key belongs exclusively to the backend process.</em></blockquote><p>The Chrome extension stores the backend URL and username locally, but keeps the password only in Chrome session storage. The React Native application keeps the password in component state for the current runtime. The Python client can request the password through a masked prompt. No real credentials, keystores, generated build output, or API keys are committed to Git.</p><p>For local demonstrations, the clients communicate over the development network. A production deployment would require HTTPS so that Basic authentication credentials are protected in transit.</p><h3>Four Clients, One API</h3><h3>Python CLI</h3><p>The Python client can run interactively or receive text and source-language arguments. It prompts for the backend password without displaying it and prints the returned Darija translation.</p><p>Arabic text introduced an additional Windows terminal challenge: right-to-left output and terminal encoding can make correct Unicode text appear reversed or corrupted. For the demonstration, I preserved the actual UTF-8 translation and rendered it in a browser with lang=&quot;ar&quot; and dir=&quot;rtl&quot;, which displayed the Arabic correctly.</p><h3>PHP Web Client</h3><p>The PHP client provides a lightweight server-rendered form. It submits authenticated JSON to the Java backend and safely renders either the translated text or a controlled error. The backend URL is configurable rather than hard-coded.</p><h3>Chrome Side-Panel Extension</h3><p>The Chrome extension was the most interaction-heavy client. A user can highlight text on any normal webpage, right-click, and select <strong>Translate to Darija</strong>. The extension then opens a side panel for the originating tab, transfers the exact selection, and starts the translation when settings are available.</p><p>It also handles rapid successive selections. If a second translation begins before the first request finishes, the stale request is aborted so that an older response cannot overwrite the newest result.</p><p>One difficult bug involved Chrome repeatedly opening its native HTTP authentication dialog. Although the extension already sent an explicit Basic Authorization header, Chrome could still react to Liberty&#39;s WWW-Authenticate challenge using browser-managed credentials. Setting credentials: &quot;omit&quot; prevented that automatic behavior while preserving the explicit header. A 401 or 403 now stops cleanly, clears the session password, preserves the selected text, and waits for another deliberate save.</p><h3>React Native on iPhone</h3><p>The mobile client was built with <strong>Expo SDK 58</strong>, <strong>React Native</strong>, and <strong>React 19</strong>. It accepts the backend URL, username, runtime-only password, source language, and text.</p><p>Testing on a physical iPhone required using the Windows computer’s Wi-Fi address instead of localhost, because localhost on the phone refers to the phone itself. Once both devices were on the same network, the application could reach the Liberty backend and render the returned Arabic text from right to left.</p><p>Another challenge was Expo Go compatibility. The original client used an older SDK, while the current iOS Expo Go build required SDK 58. Upgrading the project, aligning its dependencies, and running Expo Doctor resolved the mismatch without generating permanent native iOS or Android projects.</p><p><em>[Insert the iPhone translation screenshot here.]</em></p><h3>Testing Beyond the Happy Path</h3><p>I wanted the project to demonstrate more than one successful request. The automated verification covered authentication, validation, provider behavior, and client integration.</p><p>The backend integration suite uses a local Gemini-shaped stub, which makes testing deterministic and avoids consuming real API quota. It verifies successful translation, provider rejection, empty provider responses, timeouts, HTTP 400 validation, HTTP 401 authentication, and health-endpoint behavior.</p><p>The final release-readiness checks included:</p><ul><li>9 backend integration tests</li><li>7 Python tests plus compilation</li><li>PHP syntax validation and live-browser verification</li><li>3 Chrome extension interaction tests and JavaScript syntax checks</li><li>3 React Native API tests</li><li>20/20 Expo Doctor checks</li><li>A successful 597-module iOS bundle</li><li>XML validation for all three SVG UML exports</li><li>Repository hygiene and secret scans</li></ul><p>The live demonstrations also verified a real Gemini translation through every client, including the Chrome side panel and the physical iPhone.</p><h3>Documenting the Design</h3><p>The repository includes editable PlantUML sources and matching SVG exports for three diagrams:</p><ul><li>A Java backend class diagram</li><li>A deployment diagram covering the four clients, Liberty, authentication, environment-only secrets, and Gemini</li><li>An authenticated translation sequence diagram showing success, validation failure, authentication failure, provider rejection, and timeout paths</li></ul><p>Creating the diagrams after the implementation helped ensure that the documentation represented the final code rather than an early design that had already changed.</p><p><em>[Insert the class or sequence diagram here.]</em></p><h3>What I Learned</h3><p>This project reinforced several lessons that apply far beyond translation software.</p><p>First, a shared backend makes a multi-client system easier to secure and maintain. The clients can evolve independently while relying on one consistent API contract.</p><p>Second, integration details matter. The most time-consuming issues were not basic syntax problems; they were boundaries between systems: Chrome and HTTP authentication, iOS and local-network addressing, Expo Go and SDK versions, Windows terminals and Arabic rendering, and application code and third-party provider errors.</p><p>Third, security is easier when it is designed into the architecture from the beginning. Keeping the Gemini key on the server, controlling password lifetimes, validating configuration at startup, and excluding generated or sensitive files from Git all became natural consequences of the system design.</p><p>Finally, automated tests and live verification serve different purposes. Stubs made failure paths repeatable, while the browser and physical-device tests proved that the complete user experience worked in the real environment.</p><h3>Final Result</h3><p>Darija Translator now provides one authenticated translation service across a terminal, a PHP webpage, a Chrome side panel, and an iPhone application. It accepts text in a specified source language and returns natural Moroccan Darija in readable Arabic script.</p><p>More importantly, the project became a practical demonstration of REST architecture, Jakarta security, external API integration, browser-extension development, mobile networking, testing, UML documentation, and secure configuration management.</p><h3>Project Links</h3><p><strong>GitHub repository:</strong><br><a href="https://github.com/BadrTechie/darija-translator">https://github.com/BadrTechie/darija-translator</a></p><p><strong>Five-minute demonstration:</strong><br><a href="https://drive.google.com/file/d/16VGm3-hAbxytcfgQbW_8aMHdB6F1ys_7/view?usp=sharing">https://drive.google.com/file/d/16VGm3-hAbxytcfgQbW_8aMHdB6F1ys_7/view?usp=sharing</a></p><p><em>Built as Project 2 for Advanced Programming Paradigms at Al Akhawayn University.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dce730eb7957" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Multi-Client JavaFX TCP Chat with Java 21 Virtual Threads]]></title>
            <link>https://medium.com/@lcbader06/building-a-multi-client-javafx-tcp-chat-with-java-21-virtual-threads-e04a56d76763?source=rss-098ee73973d0------2</link>
            <guid isPermaLink="false">https://medium.com/p/e04a56d76763</guid>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[university]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[paradigm]]></category>
            <dc:creator><![CDATA[Lcbader]]></dc:creator>
            <pubDate>Thu, 22 Oct 2026 20:36:37 GMT</pubDate>
            <atom:updated>2026-10-22T20:36:37.849Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A source-accurate walkthrough of a two-layer TCP chat application with explicit framing, anonymous read-only access, JavaFX thread isolation, and executable Windows JARs.</em></p><p>Repository: <a href="https://github.com/BadrTechie/java-tcp-chat">https://github.com/BadrTechie/java-tcp-chat</a></p><h3>What the application does</h3><p>This project contains two Maven application modules:</p><ul><li>tcp-server runs a JavaFX server console and a multi-client TCP server.</li><li>tcp-client runs a JavaFX chat client.</li></ul><p>The server accepts multiple simultaneous clients. Named clients can publish messages, while clients that leave the username blank receive a generated label such as Anonymous-1 (read-only) and can only read broadcasts or request the active-user list. The server adds the timestamp and sender name, then sends each accepted message once to every active connection, including the sender.</p><p>The application also handles duplicate named identities, private allUsers responses, clean command/button/window disconnection, abrupt socket loss, and server shutdown.</p><h3>One constraint shapes the structure: exactly two layers</h3><p>Each module uses only two architectural layers.</p><p>The <strong>business layer</strong> owns configuration, validation, protocol framing, sockets, connected-user state, commands, message processing, concurrency, and lifecycle. Its classes live under:</p><ul><li>io.github.badrtechie.tcpchat.server.business</li><li>io.github.badrtechie.tcpchat.client.business</li></ul><p>The <strong>presentation layer</strong> owns JavaFX controls, GridPane layout, CSS, UI event handling, status display, and the handoff to the JavaFX Application Thread:</p><ul><li>io.github.badrtechie.tcpchat.server.presentation</li><li>io.github.badrtechie.tcpchat.client.presentation</li></ul><p>There is no repository, persistence, service, controller, model, or network layer. Focused classes still have separate responsibilities, but all non-UI responsibilities remain inside business.</p><p>The default-package TCPServer and TCPClient classes are thin assignment-compatible entry points. ServerBootstrap.start launches ServerApplication, while ClientBootstrap.start passes startup arguments to ClientApplication before launching it. These adapters do not contain application behavior and are not a third layer.</p><p>The dependency direction stays simple:</p><pre>JavaFX presentation<br>        |<br>        | plain method calls and callback interfaces<br>        v<br>business logic and networking</pre><p>ServerApplication implements ServerEventListener, and ClientApplication implements ClientEventListener. Those interfaces contain ordinary Java callbacks and no JavaFX types. As a result, ChatServer and ChatClient run in headless integration tests.</p><h3>External configuration and live user input</h3><p>Deployment-specific values are not compiled into the applications.</p><p>config/server.properties contains:</p><pre>server.host=0.0.0.0<br>server.port=3000</pre><p>config/client.properties contains:</p><pre>server.host=localhost<br>server.port=3000</pre><p>ServerSettings.load reads the server defaults. ClientSettings.resolve reads the client defaults when no command-line arguments are present. Exactly two client arguments override both properties:</p><pre>java -jar .\tcp-client\target\TCPClient.jar localhost 3000</pre><p>The selected host and port prefill editable connection controls. The username always comes from the client UI and remains optional. Production code does not seed users, conversations, or connection state.</p><p>The Inputs utility in each business package validates hosts, ports, usernames, and messages at their boundaries. Usernames reject control characters and are limited to 40 characters; messages must be nonblank and no longer than 4,000 characters.</p><h3>A framed UTF-8 protocol</h3><p>TCP is a byte stream, not a message queue. One socket read is not guaranteed to correspond to one socket write, so the application defines explicit frame boundaries.</p><p>WireProtocol.write serializes every frame as:</p><ol><li>A four-byte, big-endian payload length written by DataOutputStream.writeInt.</li><li>Exactly that many UTF-8 bytes.</li></ol><p>The payload starts with a frame type followed by tab-separated fields. Each individual field is Base64-encoded UTF-8. The frame types are:</p><ul><li>HELLO and WELCOME for identity negotiation.</li><li>CHAT and MESSAGE for client input and server-formatted broadcasts.</li><li>USERS_REQUEST and USERS for the private active-user query.</li><li>ERROR for validation or protocol errors.</li><li>DISCONNECT and SHUTDOWN for lifecycle signaling.</li></ul><p>Base64 is used only to keep arbitrary field content — such as tabs, newlines, and Unicode — from colliding with the field separator. <strong>It is not encryption and provides no confidentiality or authentication.</strong> The TCP connection is unencrypted.</p><p>WireProtocol.read rejects zero, negative, incomplete, malformed, or oversized frames. The maximum encoded frame size is 1,048,576 bytes. This bounded framing also prevents a peer from requesting an unbounded allocation through the length prefix.</p><p>The client recognizes complete commands before producing a CHAT frame. Exact allUsers becomes USERS_REQUEST, while case-insensitive end, bye, or leave calls disconnect. The server never searches message substrings for commands, so ordinary message content stays intact.</p><h3>Virtual threads and protected shared state</h3><p>ChatServer.start creates and binds a ServerSocket, creates an Executors.newVirtualThreadPerTaskExecutor(), and starts the accept loop on a virtual thread. Every accepted socket is submitted as a separate virtual-thread task that runs handle(Socket).</p><p>This maps the blocking socket code directly to a client session without putting network work on the JavaFX thread. The same approach is used by the client presentation: ClientApplication starts virtual threads around ChatClient.connect, sendMessage, requestActiveUsers, and disconnect.</p><p>Virtual threads do not remove the need for synchronization. The server stores active sessions and case-normalized named identities in ConcurrentHashMap instances. putIfAbsent performs the duplicate-name claim atomically. An AtomicInteger supplies unique anonymous labels, and atomic booleans protect server/session lifecycle transitions.</p><p>Multiple virtual threads may broadcast to the same client concurrently. Each ClientSession therefore has a writeLock, and its send method serializes the complete frame write and flush. ChatClient uses the same pattern for its outgoing frames. Without per-connection serialization, bytes from two valid frames could interleave on one TCP stream.</p><p>Lifecycle operations are idempotent. ChatServer.remove uses compareAndSet before removing maps, closing the socket, and emitting callbacks. ChatClient.closeTransport clears transport references, closes the socket, and emits onDisconnected once. Both client and server bound the initial handshake with socket timeouts.</p><h3>Identity and read-only enforcement</h3><p>The first client frame must be HELLO(username). ChatServer.handle validates the field and chooses one of two paths:</p><ul><li>A nonblank name is claimed case-insensitively in namedUsers. An existing claim produces a clear ERROR frame and closes the rejected connection.</li><li>A blank name receives Anonymous-N (read-only) and a WELCOME frame whose second field is true.</li></ul><p>Read-only behavior is intentionally enforced twice. ClientApplication.onConnected disables the composer and SEND button, and ChatClient.sendMessage rejects attempts from a read-only client. The server remains authoritative: ChatServer.acceptChat checks sender.readOnly and returns an ERROR even if another client implementation bypasses the official UI and sends CHAT directly.</p><p>Anonymous clients can still call requestActiveUsers through the Active Users button because that operation does not publish a chat message.</p><h3>Authoritative broadcasts and private replies</h3><p>When a named client sends text, ChatClient.sendMessage validates it and writes CHAT(text). ChatServer.acceptChat creates:</p><pre>[HH:mm:ss] DisplayName: original message</pre><p>broadcast sends one MESSAGE frame to a snapshot of all active sessions, including the sender. The client does not display a local optimistic echo. The sender therefore sees the same single, server-authoritative copy as every other client.</p><p>An active-user request follows a different path. ChatServer.sendUsers sorts the current display names and calls requester.send(...) only. It does not call broadcast, so no other connection receives the USERS frame.</p><p>Clean disconnection can begin with end, bye, leave, the LEAVE button, or window close. The client writes DISCONNECT where possible and closes its transport. EOF and abrupt socket failures reach the same server cleanup path. When the operator stops the server, ChatServer.stop sends SHUTDOWN(&quot;Server stopped.&quot;) before closing sessions; connected clients update to Offline through onDisconnected.</p><h3>Keeping JavaFX on its own thread</h3><p>JavaFX controls must be accessed on the JavaFX Application Thread. The business layer cannot import JavaFX, so it reports events through ClientEventListener and ServerEventListener.</p><p>Network callbacks occur on virtual threads. ClientApplication and ServerApplication wrap control changes in Platform.runLater. Text histories, status labels, indicators, buttons, the server activity log, and the connected-user ListView are therefore updated at the presentation boundary.</p><p>Both interfaces build their layouts with GridPane and load external CSS resources (client.css and server.css). The server presentation assigns a color when a connected user is added and keeps that mapping until the user disconnects.</p><h3>Testing the business layer over real sockets</h3><p>The Maven test suite uses JUnit 5. ServerSettingsTest and ClientSettingsTest cover properties, CLI precedence, missing values, and invalid hosts/ports.</p><p>ChatIntegrationTest starts ChatServer on loopback with port 0, allowing the operating system to select an ephemeral port. Tests use bounded polling rather than unbounded sleeps. The suite covers:</p><ul><li>multiple simultaneous clients, including an anonymous client;</li><li>sender-inclusive delivery exactly once;</li><li>multiline message content through the framing protocol;</li><li>private active-user responses;</li><li>client-side and server-side anonymous send rejection;</li><li>case-insensitive duplicate identities;</li><li>allUsers, end, and bye;</li><li>normal and abrupt disconnect cleanup; and</li><li>server shutdown notification.</li></ul><p>The verified release command is:</p><pre>.\mvnw.cmd clean verify</pre><p>It passed 10 tests on Temurin JDK 22.0.2 while compiling with --release 21.</p><h3>Packaging and platform limits</h3><p>Each module uses Maven Shade with a thin default-package launcher as Main-Class. The build creates:</p><ul><li>tcp-server/target/TCPServer.jar</li><li>tcp-client/target/TCPClient.jar</li></ul><p>The JARs include JavaFX 21.0.2 dependencies and Windows x64 native libraries. They run with java -jar without a separate JavaFX SDK on Windows. This convenience also creates two explicit limitations:</p><ol><li>The packaged artifacts are Windows-specific; another operating system needs a rebuild with the matching OpenJFX native dependencies.</li><li>Shaded JavaFX classes run from the unnamed module and may log a non-fatal “unsupported JavaFX configuration” warning.</li></ol><p>The protocol uses plain TCP, so it does not provide TLS encryption, server authentication, user passwords, private chats, or durable history. Those are possible future features, not claims about this implementation.</p><h3>Factual implementation sequence</h3><p>The repository history records the work in bounded milestones: requirements and ambiguity decisions, the Maven foundation, the complete two-layer application with tests and packaging, then protocol/UML/demo/article documentation. This sequence kept the headless business behavior testable before relying on manual GUI checks.</p><h3>Run it</h3><p>From the repository root:</p><pre>.\mvnw.cmd clean verify<br>java -jar .\tcp-server\target\TCPServer.jar</pre><p>Click START in the server window, then launch clients:</p><pre>java -jar .\tcp-client\target\TCPClient.jar localhost 3000</pre><p>For a one-PC demonstration, run three client processes: two with different names and one with a blank username. The deployment diagram explains how the same application runs across separate machines when clients use the server’s reachable address instead of localhost.</p><h3>Closing</h3><p>The central design is deliberately direct: a framed protocol makes the TCP byte stream reliable, virtual threads keep blocking socket code readable, concurrent collections and per-socket write locks protect shared state, and plain callbacks keep JavaFX out of the business layer. The result is a functional multi-client chat whose automated tests and diagrams describe the same implementation that ships in the executable JARs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e04a56d76763" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>