<?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 Jefster on Medium]]></title>
        <description><![CDATA[Stories by Jefster on Medium]]></description>
        <link>https://medium.com/@dev.jefster?source=rss-6829b15dd270------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*ebPn-UUBrl_o31mZ</url>
            <title>Stories by Jefster on Medium</title>
            <link>https://medium.com/@dev.jefster?source=rss-6829b15dd270------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 14:30:55 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dev.jefster/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[Automating Remote Branch Cleanup in Azure DevOps Using Git and Bash]]></title>
            <link>https://medium.com/@dev.jefster/automating-remote-branch-cleanup-in-azure-devops-using-git-and-bash-ab3cfb7c0026?source=rss-6829b15dd270------2</link>
            <guid isPermaLink="false">https://medium.com/p/ab3cfb7c0026</guid>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[azure-repos]]></category>
            <category><![CDATA[bash]]></category>
            <category><![CDATA[git]]></category>
            <category><![CDATA[azure-devops]]></category>
            <dc:creator><![CDATA[Jefster]]></dc:creator>
            <pubDate>Fri, 07 Mar 2025 14:10:50 GMT</pubDate>
            <atom:updated>2025-03-07T14:10:50.845Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/835/1*dawR5LBWlxH05H03ioAbzg.png" /></figure><p><a href="https://dev.to/t/azure">#azure</a> <a href="https://dev.to/t/git">#git</a> <a href="https://dev.to/t/bash">#bash</a> <a href="https://dev.to/t/azurerepos">#azurerepos</a></p><p>Managing remote branches is crucial in keeping a Git repository clean and efficient. Over time, stale branches accumulate, making navigation harder and slowing down repository operations. In Azure DevOps, branches that haven’t been used in months can clutter your repository, potentially causing confusion and unnecessary storage costs.</p><p>This article presents a Bash script to automate the deletion of remote branches that haven’t been modified in over three months. By the end of this guide, you’ll have a simple but powerful tool to maintain a clean repository in Azure Repos.</p><p><strong>Why Delete Old Remote Branches?</strong></p><ul><li>Reduce Clutter — Old feature branches make the repository hard to navigate.</li><li>Improve Performance — Fewer branches mean faster Git operations.</li><li>Enforce Best Practices — Encourages developers to clean up after merging.</li><li>Save Storage Space — Reducing unnecessary data stored in Azure DevOps.</li></ul><p><strong>The Problem: Stale Branches in Azure DevOps</strong></p><p>If you’re working on an Azure DevOps repository, you may notice an increasing number of old branches that are no longer relevant. Manually identifying and deleting these branches is tedious, especially in large teams.</p><h3>The Solution: Automate Cleanup with Bash + Git</h3><ol><li>1. We can automate this process by writing a Bash script that:</li><li>2. Fetches all remote branches.</li><li>3. Check the last commit date for each branch.</li><li>4. Deletes branches that haven’t been modified in 3+ months.</li><li>Ask for confirmation before deleting.</li></ol><h3>The Bash Script</h3><p>Below is a fully automated script to clean up remote branches in Azure DevOps repositories:</p><pre>#!/bin/bash</pre><pre># Remote repository (default to origin)<br>REMOTE=${1:-origin}</pre><pre># Time threshold (3 months ago)<br>THRESHOLD_DATE=$(date -d &quot;3 months ago&quot; +%s)</pre><pre># Fetch latest remote branches<br>git fetch --prune $REMOTE</pre><pre>echo &quot;Checking remote branches older than 3 months...&quot;</pre><pre># Get remote branches and last commit date<br>OLD_BRANCHES=()<br>while read -r branch last_commit_date; do<br>    # Convert last commit date to Unix timestamp<br>    LAST_COMMIT_TIMESTAMP=$(date -d &quot;$last_commit_date&quot; +%s)</pre><pre>    # Compare with threshold<br>    if [[ &quot;$LAST_COMMIT_TIMESTAMP&quot; -lt &quot;$THRESHOLD_DATE&quot; ]]; then<br>        OLD_BRANCHES+=(&quot;$branch&quot;)<br>    fi<br>done &lt; &lt;(git for-each-ref --format &#39;%(refname:short) %(committerdate:iso8601)&#39; refs/remotes/$REMOTE | sed &quot;s#refs/remotes/$REMOTE/##&quot;)</pre><pre># If no old branches, exit<br>if [[ ${#OLD_BRANCHES[@]} -eq 0 ]]; then<br>    echo &quot;No branches older than 3 months found.&quot;<br>    exit 0<br>fi</pre><pre># Show branches to be deleted<br>echo &quot;The following branches are older than 3 months and will be deleted:&quot;<br>printf &#39;%s\n&#39; &quot;${OLD_BRANCHES[@]}&quot;</pre><pre># Confirm deletion<br>read -p &quot;Are you sure you want to delete these branches from Azure DevOps? (y/N): &quot; CONFIRM<br>if [[ &quot;$CONFIRM&quot; != &quot;y&quot; ]]; then<br>    echo &quot;Operation aborted.&quot;<br>    exit 0<br>fi</pre><pre># Delete branches from Azure DevOps<br>for branch in &quot;${OLD_BRANCHES[@]}&quot;; do<br>    echo &quot;Deleting $REMOTE/$branch from Azure DevOps...&quot;<br>    git push $REMOTE --delete &quot;$branch&quot;<br>done</pre><pre>echo &quot;Old branches successfully deleted from Azure DevOps.&quot;</pre><h3>Key Features</h3><h3>Automatically Detects Old Branches</h3><p>The script checks when each branch was last modified.</p><p>Uses git for-each-ref to get the last commit timestamp.</p><p>Compares timestamps to filter branches older than 3 months.</p><h3>Prevents Accidental Deletion</h3><p>List branches before deleting them.</p><p>Ask for confirmation before proceeding.</p><h3>Azure DevOps Compatible</h3><p>Works with Azure Repos (Git) in Azure DevOps.</p><p>Uses git push origin — delete to remove branches remotely.</p><h3>Customizable</h3><p>Change the time threshold by modifying 3 months ago.</p><p>Change REMOTE=${1:-origin} to work with different Git remotes.</p><h3>🛠 How to Use the Script</h3><h3>Save the Script</h3><p>Create a new file called delete_old_devops_branches.sh and paste the script inside.</p><h3>Make it Executable</h3><p>Run the following command:<br> chmod +x delete_old_devops_branches.sh</p><h3>Run the Script</h3><p>Execute the script in your repository:<br> ./delete_old_devops_branches.sh<br> Or specify a different remote (if not origin):<br> ./delete_old_devops_branches.sh upstream</p><h3>Enhancing the Script (Optional)</h3><p>Want to add more features? Here are some ideas:</p><h3>Exclude Protected Branches (Main, Develop, etc.)</h3><p>Modify the script to skip the deletion of main, develop, or other critical branches:</p><pre>EXCLUDED_BRANCHES=(&quot;main&quot; &quot;develop&quot; &quot;release&quot;)<br>if [[ &quot; ${EXCLUDED_BRANCHES[@]} &quot; =~ &quot; $branch &quot; ]]; then<br>    continue<br>fi</pre><h3>Run in Dry-Run Mode</h3><p>Instead of deleting, list the branches:<br> git push --dry-run $REMOTE --delete &quot;$branch&quot;</p><h3>Schedule Automatic Cleanup</h3><p>Use cron jobs to run the script monthly:<br> crontab -e<br> Add this line:<br> 0 2 1 * * /path/to/delete_old_devops_branches.sh<br> This will run the script on the 1st of every month at 2 AM.</p><h3>Final Thoughts</h3><p>Cleaning remote branches in Azure DevOps is essential for maintaining a healthy Git repository. By automating this task with a simple Bash script, you save time, improve repository organization, and enforce best practices across your team.</p><p>This script is a starting point — you can extend it further with exclusions, dry-run mode, or automatic scheduling.</p><p>💡 Have any ideas to improve it? Share your thoughts in the comments!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ab3cfb7c0026" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Migrating GraphQL Scalar Implementation: Handling Deprecated Coercing Constructor]]></title>
            <link>https://medium.com/@dev.jefster/migrating-graphql-scalar-implementation-handling-deprecated-coercing-constructor-36085d56045c?source=rss-6829b15dd270------2</link>
            <guid isPermaLink="false">https://medium.com/p/36085d56045c</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[springboot-3]]></category>
            <dc:creator><![CDATA[Jefster]]></dc:creator>
            <pubDate>Fri, 28 Feb 2025 00:13:43 GMT</pubDate>
            <atom:updated>2025-02-28T00:13:43.712Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/990/0*yyMkqpsSA2mnUmOU" /></figure><h3>Introduction</h3><p>With the evolution of the graphql-java library, the Coercing interface has undergone changes that deprecate the previous constructor-based approach. This article guides developers through the necessary steps to migrate the existing scalar implementation to the latest version while ensuring compatibility and maintaining best practices.</p><h3>Understanding the Change</h3><p>Previously, scalar coercing in graphql-java used a constructor-based approach with methods like:</p><ul><li>serialize(Object dataFetcherResult)</li><li>parseValue(Object input)</li><li>parseLiteral(Object input)</li></ul><p>However, in newer versions, the Coercing interface now requires the inclusion of a GraphQLContext and Locale in the method signatures:</p><ul><li>serialize(Object dataFetcherResult, GraphQLContext context, Locale locale)</li><li>parseValue(Object input, GraphQLContext context, Locale locale)</li><li>parseLiteral(Value&lt;?&gt; input, CoercedVariables variables, GraphQLContext context, Locale locale)</li></ul><h3>Example of Deprecated Implementation</h3><p>The existing implementation before migration follows the old method signatures:</p><pre>@Configuration<br>public class GraphQlConfig {<br>    @Bean<br>    public RuntimeWiringConfigurer runtimeWiringConfigurer() {<br>        GraphQLScalarType scalarType = localDateTimeScalar();<br>        return wiringBuilder -&gt; wiringBuilder<br>                .scalar(scalarType)<br>                .scalar(ExtendedScalars.GraphQLLong)<br>                .scalar(ExtendedScalars.DateTime)<br>                .scalar(ExtendedScalars.GraphQLBigDecimal)<br>                .scalar(ExtendedScalars.Json);<br>    }<br>@Bean<br>    public GraphQLScalarType localDateTimeScalar() {<br>        var formatter = DateTimeFormatter.ofPattern(&quot;yyyy-MM-dd HH:mm&quot;);<br>        return GraphQLScalarType.newScalar()<br>                .name(&quot;LocalDateTime&quot;)<br>                .description(&quot;LocalDateTime as a GraphQL scalar.&quot;)<br>                .coercing(new Coercing&lt;LocalDateTime, String&gt;() {<br>                    @Override<br>                    public String serialize(Object dataFetcherResult) {<br>                        if (dataFetcherResult instanceof LocalDateTime dateTime) {<br>                            return formatter.format(dateTime);<br>                        }<br>                        throw new CoercingSerializeException(&quot;Expected a LocalDateTime object.&quot;);<br>                    }<br>                    @Override<br>                    public LocalDateTime parseValue(Object input) {<br>                        if (input instanceof String dateString) {<br>                            try {<br>                                return LocalDateTime.parse(dateString, formatter);<br>                            } catch (DateTimeParseException e) {<br>                                throw new CoercingParseValueException(&quot;Invalid date format: &quot; + dateString, e);<br>                            }<br>                        }<br>                        throw new CoercingParseValueException(&quot;Expected a String&quot;);<br>                    }<br>                    @Override<br>                    public LocalDateTime parseLiteral(Object input) {<br>                        if (input instanceof StringValue stringValue) {<br>                            try {<br>                                return LocalDateTime.parse(stringValue.getValue(), formatter);<br>                            } catch (DateTimeParseException e) {<br>                                throw new CoercingParseLiteralException(&quot;Invalid date literal: &quot; + stringValue.getValue(), e);<br>                            }<br>                        }<br>                        throw new CoercingParseLiteralException(&quot;Expected a StringValue.&quot;);<br>                    }<br>                }).build();<br>    }<br>}</pre><p>This approach will no longer work due to deprecations.</p><h3>Migration to the New Approach</h3><p>The new implementation should update the method signatures to include the required parameters:</p><pre>@Configuration<br>public class GraphQlConfig {<br>    @Bean<br>    public RuntimeWiringConfigurer runtimeWiringConfigurer() {<br>        GraphQLScalarType scalarType = localDateTimeScalar();<br>        return wiringBuilder -&gt; wiringBuilder<br>                .scalar(scalarType)<br>                .scalar(ExtendedScalars.GraphQLLong)<br>                .scalar(ExtendedScalars.DateTime)<br>                .scalar(ExtendedScalars.GraphQLBigDecimal)<br>                .scalar(ExtendedScalars.Json);<br>    }<br>    @Bean<br>    public GraphQLScalarType localDateTimeScalar() {<br>        var formatter = DateTimeFormatter.ofPattern(&quot;yyyy-MM-dd HH:mm&quot;);<br>        return GraphQLScalarType.newScalar()<br>                .name(&quot;LocalDateTime&quot;)<br>                .description(&quot;LocalDateTime as a GraphQL scalar.&quot;)<br>                .coercing(new Coercing&lt;LocalDateTime, String&gt;() {<br>                    @Override<br>                    public String serialize(@NotNull Object dataFetcherResult, @NotNull GraphQLContext context, @NotNull Locale locale) {<br>                        if (dataFetcherResult instanceof LocalDateTime dateTime) {<br>                            return formatter.format(dateTime);<br>                        }<br>                        throw new CoercingSerializeException(&quot;Expected a LocalDateTime object.&quot;);<br>                    }<br>                    @Override<br>                    public LocalDateTime parseValue(@NotNull Object input, @NotNull GraphQLContext context, @NotNull Locale locale) {<br>                        if (input instanceof String dateString) {<br>                            try {<br>                                return LocalDateTime.parse(dateString, formatter);<br>                            } catch (DateTimeParseException e) {<br>                                throw new CoercingParseValueException(&quot;Invalid date format: &quot; + dateString, e);<br>                            }<br>                        }<br>                        throw new CoercingParseValueException(&quot;Expected a String&quot;);<br>                    }<br>                    @Override<br>                    public LocalDateTime parseLiteral(@NotNull Value&lt;?&gt; input, @NotNull CoercedVariables variables, @NotNull GraphQLContext context, @NotNull Locale locale) {<br>                        if (input instanceof StringValue stringValue) {<br>                            try {<br>                                return LocalDateTime.parse(stringValue.getValue(), formatter);<br>                            } catch (DateTimeParseException e) {<br>                                throw new CoercingParseLiteralException(&quot;Invalid date literal: &quot; + stringValue.getValue(), e);<br>                            }<br>                        }<br>                        throw new CoercingParseLiteralException(&quot;Expected a StringValue.&quot;);<br>                    }<br>                }).build();<br>    }<br>}</pre><h3>Summary of Changes</h3><ol><li><strong>Method Signature Updates:</strong> The updated interface requires GraphQLContext and Locale parameters.</li><li><strong>Deprecated Method Replacement:</strong> Replace parseValue(Object input) and parseLiteral(Object input) with the updated versions that accept additional parameters.</li><li><strong>Backward Compatibility Considerations:</strong> Ensure that existing queries and mutations using the LocalDateTime scalar function correctly under the new implementation.</li></ol><h3>Conclusion</h3><p>Migrating the GraphQL scalar implementation is necessary to comply with the latest graphql-java API changes. By updating the method signatures and incorporating the GraphQLContext and Locale, developers can ensure compatibility and future-proof their applications. Always test thoroughly after making such changes to verify that existing GraphQL queries and mutations function as expected.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=36085d56045c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[OAuth2 in Spring Security: Understanding the Client, Authorization Server, and Resource Server]]></title>
            <link>https://medium.com/@dev.jefster/oauth2-in-spring-security-understanding-the-client-authorization-server-and-resource-server-e90c14630b20?source=rss-6829b15dd270------2</link>
            <guid isPermaLink="false">https://medium.com/p/e90c14630b20</guid>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[spring-security]]></category>
            <category><![CDATA[oauth2]]></category>
            <dc:creator><![CDATA[Jefster]]></dc:creator>
            <pubDate>Thu, 27 Feb 2025 11:57:22 GMT</pubDate>
            <atom:updated>2025-02-27T11:57:22.534Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*b4FC7XFxPZgSUys4rx9cSw.png" /></figure><h3>🔹 Introduction</h3><p>In <strong>Spring Security with OAuth2</strong>, three main components work together to manage authentication and authorization:</p><ol><li><strong>OAuth2 Client</strong> — Requests access to protected resources.</li><li><strong>Authorization Server</strong> — Issues and validates tokens.</li><li><strong>Resource Server</strong> — Protects APIs and verifies tokens.</li></ol><p>Understanding these components is crucial when <strong>securing a Spring Boot application</strong>.</p><p>In this article, I’ll break down the <strong>roles of the OAuth2 client, authorization server, and resource server</strong>, and show <strong>how they interact</strong> in a real-world application.</p><h3>🔹 What is OAuth2?</h3><p><strong>OAuth2 (Open Authorization 2.0)</strong> is an industry-standard <strong>protocol</strong> that allows secure authorization between services <strong>without exposing user credentials</strong>.</p><p>Instead of users providing usernames and passwords, OAuth2 uses <strong>access tokens</strong> to authenticate requests.</p><h3>1️⃣ What is an OAuth2 Client?</h3><h3>📝 Definition</h3><p>The <strong>OAuth2 Client</strong> is an <strong>application that requests access to a protected resource</strong> (e.g., API, user data).</p><h3>🔹 Examples</h3><ul><li>A <strong>frontend application</strong> requesting a token to access an API.</li><li>A <strong>mobile app</strong> requesting user profile data.</li><li>A <strong>third-party service</strong> accessing a user’s information (e.g., Google login for authentication).</li></ul><h3>🔹 How it Works</h3><ol><li><strong>The Client requests a token</strong> from the Authorization Server.</li><li><strong>The Authorization Server validates credentials</strong> and issues a JWT token.</li><li><strong>The Client uses the token</strong> to access protected APIs (Resource Server).</li></ol><h3>🔹 Example in Spring Boot</h3><p>In a Spring Boot application, an OAuth2 client can be configured using <strong>Spring Security</strong>.</p><p>Example configuration in application.yml:</p><pre>spring:<br>  security:<br>    oauth2:<br>      client:<br>        registration:<br>          google:<br>            client-id: YOUR_CLIENT_ID<br>            client-secret: YOUR_CLIENT_SECRET<br>            scope: profile, email</pre><p>🔹 <strong>This allows your app to authenticate users with Google OAuth2</strong>.</p><h3>2️⃣ What is an Authorization Server?</h3><h3>📝 Definition</h3><p>The <strong>Authorization Server</strong> is responsible for <strong>authenticating users</strong> and <strong>issuing access tokens</strong>.</p><h3>🔹 Key Responsibilities</h3><p>✅ <strong>Authenticates users</strong><br>✅ <strong>Issues JWT tokens</strong><br>✅ <strong>Manages token expiration &amp; refresh tokens</strong><br>✅ <strong>Defines authorization scopes</strong></p><h3>🔹 How it Works</h3><ol><li>The <strong>OAuth2 Client</strong> (e.g., frontend app) requests a token.</li><li>The <strong>Authorization Server validates credentials</strong>.</li><li>If valid, it <strong>issues a JWT token</strong>.</li><li>The <strong>Client uses the token</strong> to access APIs.</li></ol><h3>🔹 Example in Spring Boot</h3><p>Since Spring Boot 3+, the <strong>OAuth2 Authorization Server</strong> is a separate dependency.</p><p>Add the dependency:</p><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>    &lt;artifactId&gt;spring-boot-starter-oauth2-authorization-server&lt;/artifactId&gt;<br>&lt;/dependency&gt;</pre><p>Then configure an <strong>Authorization Server</strong> (AuthServerConfig.java):</p><pre>@Configuration<br>public class AuthServerConfig {<br>    @Bean<br>    public SecurityFilterChain authServerSecurityFilterChain(HttpSecurity http) throws Exception {<br>        OAuth2AuthorizationServerConfigurer authorizationServerConfigurer = OAuth2AuthorizationServerConfigurer.authorizationServer();<br>        http.securityMatcher(authorizationServerConfigurer.getEndpointsMatcher())<br>            .apply(authorizationServerConfigurer);<br><br>        return http.build();<br>    }<br><br>    @Bean<br>    public RegisteredClientRepository registeredClientRepository() {<br>        RegisteredClient registeredClient = RegisteredClient.withId(UUID.randomUUID().toString())<br>            .clientId(&quot;client-id&quot;)<br>            .clientSecret(&quot;{noop}client-secret&quot;)<br>            .authorizationGrantType(AuthorizationGrantType.CLIENT_CREDENTIALS)<br>            .scope(&quot;read&quot;)<br>            .scope(&quot;write&quot;)<br>            .build();<br><br>        return new InMemoryRegisteredClientRepository(registeredClient);<br>    }<br>}</pre><p>🔹 <strong>This configures the server to issue JWT tokens</strong>.</p><h3>3️⃣ What is a Resource Server?</h3><h3>📝 Definition</h3><p>The <strong>Resource Server</strong> is the <strong>API that serves protected resources</strong> and validates access tokens.</p><h3>🔹 Key Responsibilities</h3><p>✅ <strong>Protects APIs &amp; sensitive data</strong><br>✅ <strong>Verifies access tokens</strong> before allowing access<br>✅ <strong>Grants access based on scopes/roles</strong></p><h3>🔹 How it Works</h3><ol><li><strong>The client sends a request</strong> to the API <strong>with a JWT token</strong>.</li><li><strong>Resource Server verifies the token</strong>.</li><li>If valid, <strong>grant access</strong> to the requested resource.</li></ol><h3>🔹 Example in Spring Boot</h3><p>To configure a <strong>Resource Server</strong> (ResourceServerConfig.java):</p><pre>@Configuration<br>public class ResourceServerConfig {<br>    @Bean<br>    public SecurityFilterChain resourceServerSecurityFilterChain(HttpSecurity http) throws Exception {<br>        http<br>            .authorizeHttpRequests(auth -&gt; auth<br>                .requestMatchers(&quot;/public&quot;).permitAll()<br>                .anyRequest().authenticated()<br>            )<br>            .oauth2ResourceServer(oauth2 -&gt; oauth2.jwt(Customizer.withDefaults()));<br><br>        return http.build();<br>    }<br>}</pre><p>🔹 <strong>This ensures that only authenticated users can access protected endpoints</strong>.</p><h3>🔹 How Do These Components Work Together?</h3><h4>1️⃣ Step 1: Client Requests a Token</h4><pre>curl -X POST \<br>  -u client-id:client-secret \<br>  -d &quot;grant_type=client_credentials&quot; \<br>  http://localhost:8080/oauth2/token</pre><p>✅ The <strong>Authorization Server</strong> issues a JWT token.</p><h4>2️⃣ Step 2: Client Calls the API</h4><pre>curl -H &quot;Authorization: Bearer YOUR_ACCESS_TOKEN&quot; http://localhost:8080/api/protected</pre><p>✅ The <strong>Resource Server</strong> verifies the token and grants access.</p><p>🔹 Key Differences Between Components</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V0VJHcsUb5mfDhKUpcPxYA.png" /></figure><h3>🚀 Conclusion</h3><ul><li><strong>OAuth2 Client</strong> = Requests tokens.</li><li><strong>Authorization Server</strong> = Issues tokens.</li><li><strong>Resource Server</strong> = Validates tokens &amp; protects APIs.</li></ul><p>By <strong>separating concerns</strong>, OAuth2 <strong>enhances security and scalability</strong>.</p><p>Have questions? Let’s discuss this in the comments! 🚀🔥</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e90c14630b20" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Setting Up Spring Security with Spring Boot 3+ (Step-by-Step Guide)]]></title>
            <link>https://medium.com/@dev.jefster/setting-up-spring-security-with-spring-boot-3-step-by-step-guide-f9004f281c79?source=rss-6829b15dd270------2</link>
            <guid isPermaLink="false">https://medium.com/p/f9004f281c79</guid>
            <category><![CDATA[oauth2]]></category>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[spring-security]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Jefster]]></dc:creator>
            <pubDate>Thu, 27 Feb 2025 11:42:18 GMT</pubDate>
            <atom:updated>2025-02-27T11:42:18.855Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*b4FC7XFxPZgSUys4rx9cSw.png" /></figure><h3>A Practical Guide for Securing Your REST APIs with OAuth2 &amp; JWT</h3><blockquote><strong><em>Author:</em></strong><em> Jefster Farlei Fernandes Caixeta Júnior<br></em><strong><em>GitHub Repository:</em></strong><em> </em><a href="https://github.com/devjefster/springapp"><em>Spring Security Demo</em></a></blockquote><h3>🔹 Introduction</h3><p>Security is a fundamental aspect of any modern application. In this guide, I’ll walk you through how to <strong>set up Spring Security with OAuth2 and JWT authentication</strong> in <strong>Spring Boot 3+</strong>, following best practices.</p><p>We’ll implement:</p><ul><li><strong>An OAuth2 Authorization Server</strong> (issues JWT tokens)</li><li><strong>A Resource Server</strong> (validates JWTs &amp; protects APIs)</li><li><strong>User Authentication &amp; Registration</strong></li><li><strong>Role-Based Access Control</strong></li><li><strong>Pagination &amp; Filtering with Spring Data JPA</strong></li></ul><p>By the end of this guide, you’ll have a <strong>secure, production-ready Spring Boot application</strong> that implements <strong>OAuth2 and JWT authentication</strong>.</p><h3>🔹 Technologies Used</h3><ul><li><strong>Java 21</strong></li><li><strong>Spring Boot 3.2+</strong></li><li><strong>Spring Security</strong></li><li><strong>OAuth2 Authorization Server</strong></li><li><strong>Spring Data JPA</strong></li><li><strong>H2 / PostgreSQL</strong></li><li><strong>Lombok</strong></li></ul><h3>1️⃣ Setting Up a New Spring Boot 3+ Project</h3><p>First, generate a new <strong>Spring Boot 3+</strong> project using <a href="https://start.spring.io/">Spring Initializr</a>.</p><h4>Add the Required Dependencies</h4><pre><br>&lt;dependencies&gt;<br>    &lt;!-- Spring Boot Web --&gt;<br>    &lt;dependency&gt;<br>        &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>        &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt;<br>    &lt;/dependency&gt;<br><br>    &lt;!-- Spring Security &amp; OAuth2 Authorization Server --&gt;<br>    &lt;dependency&gt;<br>        &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>        &lt;artifactId&gt;spring-boot-starter-security&lt;/artifactId&gt;<br>    &lt;/dependency&gt;<br>    &lt;dependency&gt;<br>        &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>        &lt;artifactId&gt;spring-boot-starter-oauth2-authorization-server&lt;/artifactId&gt;<br>    &lt;/dependency&gt;<br>    <br>    &lt;!-- Spring Data JPA &amp; H2 Database --&gt;<br>    &lt;dependency&gt;<br>        &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>        &lt;artifactId&gt;spring-boot-starter-data-jpa&lt;/artifactId&gt;<br>    &lt;/dependency&gt;<br>    &lt;dependency&gt;<br>        &lt;groupId&gt;com.h2database&lt;/groupId&gt;<br>        &lt;artifactId&gt;h2&lt;/artifactId&gt;<br>        &lt;scope&gt;runtime&lt;/scope&gt;<br>    &lt;/dependency&gt;<br><br>    &lt;!-- JWT Support --&gt;<br>    &lt;dependency&gt;<br>        &lt;groupId&gt;org.springframework.security&lt;/groupId&gt;<br>        &lt;artifactId&gt;spring-security-oauth2-jose&lt;/artifactId&gt;<br>    &lt;/dependency&gt;<br><br>    &lt;!-- Lombok (Optional) --&gt;<br>    &lt;dependency&gt;<br>        &lt;groupId&gt;org.projectlombok&lt;/groupId&gt;<br>        &lt;artifactId&gt;lombok&lt;/artifactId&gt;<br>        &lt;scope&gt;provided&lt;/scope&gt;<br>    &lt;/dependency&gt;<br>&lt;/dependencies&gt;</pre><h3>2️⃣ Setting Up Spring Security &amp; OAuth2</h3><p>Spring Security requires <strong>two key configurations</strong>:</p><ol><li><strong>OAuth2 Authorization Server</strong> — Issues JWT tokens.</li><li><strong>Resource Server</strong> — Secures APIs and validates tokens.</li></ol><h4>Step 1: Configure the Authorization Server</h4><p>Create AuthServerConfig.java:</p><pre>@Configuration<br>public class AuthServerConfig {<br><br>    @Bean<br>    public SecurityFilterChain authServerSecurityFilterChain(HttpSecurity http) throws Exception {<br>        OAuth2AuthorizationServerConfigurer authorizationServerConfigurer = OAuth2AuthorizationServerConfigurer.authorizationServer();<br>        http.securityMatcher(authorizationServerConfigurer.getEndpointsMatcher())<br>            .with(authorizationServerConfigurer, (authorizationServer) -&gt;<br>                authorizationServer.oidc(Customizer.withDefaults()) // Enable OpenID Connect (OIDC)<br>            );<br><br>        return http.build();<br>    }<br><br>    @Bean<br>    public RegisteredClientRepository registeredClientRepository() {<br>        RegisteredClient registeredClient = RegisteredClient.withId(UUID.randomUUID().toString())<br>            .clientId(&quot;client-id&quot;)<br>            .clientSecret(&quot;{noop}client-secret&quot;) // No encoding for testing<br>            .authorizationGrantType(AuthorizationGrantType.CLIENT_CREDENTIALS)<br>            .authorizationGrantType(AuthorizationGrantType.REFRESH_TOKEN)<br>            .scope(&quot;read&quot;)<br>            .scope(&quot;write&quot;)<br>            .build();<br><br>        return new InMemoryRegisteredClientRepository(registeredClient);<br>    }<br>}</pre><p>✅ <strong>Handles OAuth2 token generation</strong><br>✅ <strong>Registers OAuth2 clients</strong> (e.g., frontend apps, external APIs)</p><h4>Step 2: Configure the Resource Server</h4><p>Create ResourceServerConfig.java:</p><pre>@Configuration<br>public class ResourceServerConfig {<br><br>    @Bean<br>    public SecurityFilterChain resourceServerSecurityFilterChain(HttpSecurity http) throws Exception {<br>        http<br>            .authorizeHttpRequests(auth -&gt; auth<br>                .requestMatchers(&quot;/auth/register&quot;, &quot;/auth/login&quot;).permitAll() // Public access<br>                .anyRequest().authenticated()<br>            )<br>            .oauth2ResourceServer(oauth2 -&gt; oauth2.jwt(Customizer.withDefaults()));<br><br>        return http.build();<br>    }<br>}</pre><p>✅ <strong>Requires JWT authentication for protected APIs</strong><br>✅ <strong>Allows public access to </strong><strong>/auth/register and </strong><strong>/auth/login</strong></p><h3>3️⃣ Implementing User Authentication &amp; Registration</h3><p>To store and authenticate users, we’ll use <strong>Spring Data JPA</strong>.</p><h4>🔹 Step 1: Create the User Entity</h4><pre>@Entity<br>@Table(name = &quot;users&quot;)<br>public class User implements UserDetails {<br>    @Id<br>    @GeneratedValue(strategy = GenerationType.IDENTITY)<br>    private Long id;<br><br>    @Column(unique = true, nullable = false)<br>    private String username;<br><br>    @Column(nullable = false)<br>    private String password;<br><br>    @Override<br>    public Collection&lt;? extends GrantedAuthority&gt; getAuthorities() {<br>        return List.of();<br>    }<br><br>    @Override<br>    public boolean isEnabled() { return true; }<br>}jav</pre><h4>🔹 Step 2: Create the UserService</h4><pre>@Service<br>public class UserService implements UserDetailsService {<br><br>    private final UserRepository userRepository;<br>    private final PasswordEncoder passwordEncoder;<br><br>    public UserService(UserRepository userRepository, PasswordEncoder passwordEncoder) {<br>        this.userRepository = userRepository;<br>        this.passwordEncoder = passwordEncoder;<br>    }<br><br>    public User registerUser(String username, String password) {<br>        User user = new User();<br>        user.setUsername(username);<br>        user.setPassword(passwordEncoder.encode(password));<br>        return userRepository.save(user);<br>    }<br><br>    @Override<br>    public UserDetails loadUserByUsername(String username) {<br>        return userRepository.findByUsername(username).orElseThrow(() -&gt; new UsernameNotFoundException(&quot;User not found&quot;));<br>    }<br>}</pre><p>✅ <strong>Hashes passwords before storing them</strong><br>✅ <strong>Loads users for authentication</strong></p><h4>🔹 Step 3: Create the Authentication Controllers</h4><h4>Register Controller (POST /auth/register)</h4><pre>@RestController<br>@RequestMapping(&quot;/auth&quot;)<br>public class RegisterController {<br>    private final UserService userService;<br><br>    public RegisterController(UserService userService) {<br>        this.userService = userService;<br>    }<br><br>    @PostMapping(&quot;/register&quot;)<br>    public ResponseEntity&lt;String&gt; register(@RequestBody Map&lt;String, String&gt; request) {<br>        userService.registerUser(request.get(&quot;username&quot;), request.get(&quot;password&quot;));<br>        return ResponseEntity.ok(&quot;User registered successfully&quot;);<br>    }<br>}</pre><h4>Login Controller (POST /auth/login)</h4><pre>@RestController<br>@RequestMapping(&quot;/auth&quot;)<br>public class LoginController {<br><br>    private final AuthenticationManager authenticationManager;<br>    private final JwtEncoder jwtEncoder;<br><br>    public LoginController(AuthenticationManager authenticationManager, JwtEncoder jwtEncoder) {<br>        this.authenticationManager = authenticationManager;<br>        this.jwtEncoder = jwtEncoder;<br>    }<br><br>    @PostMapping(&quot;/login&quot;)<br>    public Map&lt;String, String&gt; login(@RequestBody Map&lt;String, String&gt; request) {<br>        Authentication authentication = authenticationManager.authenticate(<br>            new UsernamePasswordAuthenticationToken(request.get(&quot;username&quot;), request.get(&quot;password&quot;))<br>        );<br>        SecurityContextHolder.getContext().setAuthentication(authentication);<br>        String token = jwtEncoder.encode(JwtEncoderParameters.from(JwtClaimsSet.builder().subject(request.get(&quot;username&quot;)).build())).getTokenValue();<br>        return Map.of(&quot;access_token&quot;, token);<br>    }<br>}</pre><h3>🚀 Conclusion</h3><p>Congratulations! 🎉 You have successfully built a <strong>Spring Boot 3+ secure API</strong> with OAuth2, JWT authentication, and user management.</p><p>👉 <strong>Check out the full code on GitHub:</strong> <a href="https://github.com/devjefster/springapp">Spring Security Demo</a></p><p>Let me know in the comments if you have any questions! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f9004f281c79" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a High-Performance Java Cache with TTL, LRU, and Persistence]]></title>
            <link>https://medium.com/@dev.jefster/building-a-high-performance-java-cache-with-ttl-lru-and-persistence-3dbd5f0dcf1e?source=rss-6829b15dd270------2</link>
            <guid isPermaLink="false">https://medium.com/p/3dbd5f0dcf1e</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[ttl]]></category>
            <category><![CDATA[cache]]></category>
            <category><![CDATA[lru]]></category>
            <category><![CDATA[async]]></category>
            <dc:creator><![CDATA[Jefster]]></dc:creator>
            <pubDate>Mon, 17 Feb 2025 18:19:06 GMT</pubDate>
            <atom:updated>2025-02-17T18:19:06.200Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p8U-oQme2r4pnHMa2kk_Gw.png" /></figure><h4>Introduction</h4><p>Caching is an essential technique to improve the performance of applications by reducing expensive computations and database calls. While existing caching solutions like Ehcache and Caffeine are powerful, they can be overkill for small projects. Enter MicroCache — a lightweight, in-memory cache built in pure Java, featuring TTL-based expiration, LRU eviction, async loading, and optional disk persistence.</p><h4>Why Build a Custom Cache?</h4><p>Most developers rely on third-party caching libraries, but sometimes, a simpler, self-contained solution is preferable. MicroCache offers:</p><ul><li>🚀 Minimal dependency overhead — pure Java, no external libraries.</li><li>⏳ Time-To-Live (TTL) support — automatic expiration of stale items.</li><li>♻️ Least Recently Used (LRU) eviction — removes old entries when the cache reaches capacity.</li><li>⚡ Asynchronous data loading — fetch missing data in the background.</li><li>💾 Optional persistence — store and reload cache data across application restarts.</li></ul><h4>How It Works</h4><p>MicroCache leverages Java’s ConcurrentHashMap for thread-safe operations and ScheduledExecutorService to handle TTL expiration. It supports both synchronous and asynchronous retrieval of values.</p><p><strong>Key Features</strong></p><ul><li>✅ Thread-safe caching using ConcurrentHashMap</li><li>✅ TTL expiration — auto-removes old data</li><li>✅ LRU eviction — manages memory efficiently</li><li>✅ Async loading — avoids blocking operations</li><li>✅ Optional disk persistence — ensures data durability</li><li>✅ Memory monitoring — tracks resource usage</li></ul><h4>Code Walkthrough</h4><p><strong>1️⃣ Initializing MicroCache</strong></p><p>Creating an instance of MicroCache is simple. You can specify a TTL, LRU size, and whether to enable persistence.</p><pre>MicroCache&lt;String, String&gt; cache = new MicroCache&lt;&gt;(<br>    key -&gt; System.out.println(&quot;Expired: &quot; + key),<br>    key -&gt; &quot;Loaded async value for &quot; + key,<br>    100,  // Max size<br>    &quot;cache_data.ser&quot;,  // Persistence file<br>    true  // Enable persistence<br>);</pre><p><strong>2️⃣ Adding and Retrieving Values</strong></p><pre>cache.put(&quot;testKey&quot;, &quot;Hello, World!&quot;, 5000); // Store value with 5s TTL<br>System.out.println(cache.get(&quot;testKey&quot;)); // Retrieves value</pre><p><strong>3️⃣ Handling Expiration</strong></p><pre>Thread.sleep(6000); // Wait for expiration<br>System.out.println(cache.get(&quot;testKey&quot;)); // Should return null</pre><p><strong>4️⃣ Performance Testing</strong></p><pre>long start = System.nanoTime();<br>for (int i = 0; i &lt; 100000; i++) {<br>    cache.put(&quot;key&quot; + i, &quot;value&quot; + i, 5000);<br>}<br>long end = System.nanoTime();<br>System.out.println(&quot;Insertion time: &quot; + (end - start) / 1_000_000 + &quot; ms&quot;);<br>System.out.println(&quot;Memory usage: &quot; + MicroCache.getMemoryUsage() + &quot; MB&quot;);</pre><h4>Why MicroCache?</h4><p>While other caching solutions exist, MicroCache is perfect for lightweight, standalone applications. It provides a great learning experience for Java developers looking to understand concurrent programming and memory management.</p><h4>Final Thoughts</h4><p>MicroCache is open-source! You can find the complete project on GitHub: <a href="https://github.com/devjefster/micro-cache-ttl">MicroCache Repository</a>. Feel free to explore, contribute, and suggest improvements!</p><p>MicroCache is a flexible and efficient caching solution that brings the power of TTL expiration, LRU eviction, and persistence into a simple Java-based library. Whether you’re working on a small microservice or need a lightweight caching layer, MicroCache delivers without the complexity of third-party dependencies.<br><br>Let me know what you think about MicroCache in the comments! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3dbd5f0dcf1e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Advanced System Monitoring in Java Using OSHI]]></title>
            <link>https://medium.com/@dev.jefster/advanced-system-monitoring-in-java-using-oshi-8c5f8df666b4?source=rss-6829b15dd270------2</link>
            <guid isPermaLink="false">https://medium.com/p/8c5f8df666b4</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[metrics]]></category>
            <category><![CDATA[jvm]]></category>
            <category><![CDATA[monitoring]]></category>
            <category><![CDATA[oshi]]></category>
            <dc:creator><![CDATA[Jefster]]></dc:creator>
            <pubDate>Tue, 11 Feb 2025 22:01:38 GMT</pubDate>
            <atom:updated>2025-02-11T22:01:38.185Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p8U-oQme2r4pnHMa2kk_Gw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/493/1*Wofoh4C_McRZiflimuPexA.png" /></figure><h3>Introduction</h3><p>System monitoring is an essential aspect of application performance management. While Java’s built-in ManagementFactory provides some system metrics, it lacks <strong>detailed CPU utilization, memory stats, and hardware monitoring</strong>.</p><p>To overcome these limitations, we can use <strong>OSHI (</strong><strong>oshi-core)</strong>, a powerful <strong>cross-platform hardware monitoring library</strong> that provides accurate real-time system information.</p><p>In this article, we’ll build a <strong>full-fledged Java monitoring service using OSHI</strong> and integrate it into our application.</p><h3>1️⃣ Setting Up OSHI in Your Project</h3><p>Before we start coding, let’s add the <strong>OSHI dependency</strong> to our Maven project.</p><h3>📌 Adding OSHI to pom.xml</h3><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;com.github.oshi&lt;/groupId&gt;<br>    &lt;artifactId&gt;oshi-core&lt;/artifactId&gt;<br>    &lt;version&gt;6.6.6&lt;/version&gt;<br>&lt;/dependency&gt;</pre><p>This will enable OSHI to collect <strong>CPU usage, memory, disk, and network statistics</strong> in real-time.</p><h3>2️⃣ Implementing SystemMonitoringServiceWithOshi</h3><p>We will now create a <strong>monitoring service that captures system metrics</strong> using OSHI.</p><h3>📌 Full Implementation of SystemMonitoringServiceWithOshi</h3><pre>package com.devjefster.service;<br><br>import oshi.SystemInfo;<br>import oshi.hardware.CentralProcessor;<br>import oshi.hardware.GlobalMemory;<br>import oshi.hardware.HardwareAbstractionLayer;<br>import oshi.hardware.NetworkIF;<br>import java.io.File;<br>import java.util.List;<br>import java.util.logging.Level;<br>import java.util.logging.Logger;<br><br>public class SystemMonitoringServiceWithOshi {<br>    private static final Logger logger = Logger.getLogger(SystemMonitoringServiceWithOshi.class.getName());<br>    private final SystemInfo systemInfo;<br>    private final HardwareAbstractionLayer hardware;<br>    private final CentralProcessor processor;<br>    private final GlobalMemory memory;<br><br>    public SystemMonitoringServiceWithOshi() {<br>        this.systemInfo = new SystemInfo();<br>        this.hardware = systemInfo.getHardware();<br>        this.processor = hardware.getProcessor();<br>        this.memory = hardware.getMemory();<br>    }<br><br>    public void checkSystemUsage(String serviceName) {<br>        logInfo(&quot;🔹 Starting system monitoring...&quot;, serviceName);<br>        try {<br>            checkCpuUsage(serviceName);<br>            checkMemoryUsage(serviceName);<br>            checkDiskUsage(serviceName);<br>            checkNetworkUsage(serviceName);<br>        } catch (Exception e) {<br>            logError(&quot;Error while monitoring system metrics&quot;, serviceName, e);<br>        }<br>        logInfo(&quot;✅ Monitoring completed&quot;, serviceName);<br>    }<br><br>    private void checkCpuUsage(String serviceName) {<br>        double cpuLoad = processor.getSystemCpuLoadBetweenTicks() * 100;<br>        logInfo(String.format(&quot;CPU Usage: %.2f%%&quot;, cpuLoad), serviceName);<br>    }<br><br>    private void checkMemoryUsage(String serviceName) {<br>        long totalMemory = memory.getTotal();<br>        long availableMemory = memory.getAvailable();<br>        long usedMemory = totalMemory - availableMemory;<br>        double usagePercentage = (double) usedMemory / totalMemory * 100;<br>        logInfo(String.format(&quot;Memory Usage: %.2f%% (Used: %dMB / Total: %dMB)&quot;,<br>                usagePercentage, usedMemory / 1048576, totalMemory / 1048576), serviceName);<br>    }<br><br>    private void checkDiskUsage(String serviceName) {<br>        File root = new File(&quot;/&quot;);<br>        long totalSpace = root.getTotalSpace();<br>        long freeSpace = root.getFreeSpace();<br>        logInfo(String.format(&quot;Disk Usage: %dGB free of %dGB&quot;,<br>                freeSpace / 1073741824, totalSpace / 1073741824), serviceName);<br>    }<br><br>    private void checkNetworkUsage(String serviceName) {<br>        List&lt;NetworkIF&gt; networkInterfaces = hardware.getNetworkIFs();<br>        for (NetworkIF net : networkInterfaces) {<br>            logInfo(String.format(&quot;Network Interface: %s - Received: %dMB, Sent: %dMB&quot;,<br>                    net.getName(), net.getBytesRecv() / 1048576, net.getBytesSent() / 1048576), serviceName);<br>        }<br>    }<br><br>    private void logInfo(String message, String serviceName) {<br>        logger.log(Level.INFO, &quot;[{0}] {1}&quot;, new Object[]{serviceName, message});<br>    }<br><br>    private void logError(String message, String serviceName, Exception e) {<br>        logger.log(Level.SEVERE, &quot;[{0}] {1} - {2}&quot;, new Object[]{serviceName, message, e.getMessage()});<br>    }<br>}</pre><h3>3️⃣ Integrating SystemMonitoringServiceWithOshi in the main Class</h3><pre>package com.devjefster;<br><br>import com.devjefster.service.SystemMonitoringServiceWithOshi;<br><br>public class App {<br>    public static void main(String[] args) {<br>        SystemMonitoringServiceWithOshi monitoringService = new SystemMonitoringServiceWithOshi();<br>        System.out.println(&quot;🔹 Starting System Monitoring with OSHI...&quot;);<br><br>        while (true) {<br>            monitoringService.checkSystemUsage(&quot;MonitoringApp&quot;);<br>            try {<br>                Thread.sleep(5000); // Run monitoring every 5 seconds<br>            } catch (InterruptedException e) {<br>                System.err.println(&quot;Monitoring interrupted: &quot; + e.getMessage());<br>                Thread.currentThread().interrupt();<br>                break;<br>            }<br>        }<br>    }<br>}</pre><h3>4️⃣ Running the OSHI-Based Monitoring Application</h3><p>After compiling your project with Maven, you can run the application:</p><pre>mvn clean install<br>java -jar target/java-monitoring-1.0-SNAPSHOT.jar</pre><h3>🔹 Expected Console Output</h3><pre>🔹 Starting System Monitoring with OSHI...<br>✅ [MonitoringApp] CPU Usage: 45.25%<br>✅ [MonitoringApp] Memory Usage: 78.5% (Used: 8192MB / Total: 16384MB)<br>✅ [MonitoringApp] Disk Usage: 120GB free of 500GB<br>✅ [MonitoringApp] Network Interface: eth0 - Received: 120MB, Sent: 30MB<br>✅ [MonitoringApp] Monitoring completed</pre><h3>🔹 Conclusion</h3><p>By integrating <strong>OSHI</strong>, we built a <strong>highly detailed system monitoring service</strong> that provides <strong>real-time CPU, memory, disk, and network statistics</strong>. Compared to ManagementFactory, OSHI offers <strong>more precise and cross-platform system metrics</strong>.</p><p>For further enhancements, consider: ✅ <strong>Logging metrics into a database</strong> (e.g., InfluxDB, Prometheus) ✅ <strong>Exposing monitoring data via a REST API</strong> ✅ <strong>Visualizing system metrics using Grafana</strong></p><p>The complete source code is available on GitHub: <a href="https://github.com/devjefster/monitoring-java">Monitoring System Metrics in Java</a> 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8c5f8df666b4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Monitoring System Metrics in Java Without External Libraries: Full Implementation]]></title>
            <link>https://medium.com/@dev.jefster/monitoring-system-metrics-in-java-without-external-libraries-full-implementation-4d65ae20a230?source=rss-6829b15dd270------2</link>
            <guid isPermaLink="false">https://medium.com/p/4d65ae20a230</guid>
            <category><![CDATA[system]]></category>
            <category><![CDATA[jvm]]></category>
            <category><![CDATA[metrics]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Jefster]]></dc:creator>
            <pubDate>Tue, 11 Feb 2025 21:49:33 GMT</pubDate>
            <atom:updated>2025-02-11T21:49:33.406Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p8U-oQme2r4pnHMa2kk_Gw.png" /></figure><h3>Introduction</h3><p>System monitoring is crucial for applications that need to track <strong>CPU usage, memory consumption, disk space, and network activity</strong>. Many developers rely on external libraries like <strong>OSHI</strong> for detailed system metrics. However, for <strong>lightweight applications</strong>, Java’s built-in ManagementFactory and Runtime utilities provide a simple way to monitor system metrics <strong>without dependencies</strong>.</p><p>In this article, we’ll implement a <strong>full Java monitoring service</strong>, integrate it with a main class, and create a <strong>continuous monitoring loop</strong>.</p><h3>1️⃣ Implementing the SystemMonitoringService Class</h3><p>Java’s ManagementFactory provides access to <strong>CPU load, memory, and threads</strong>, while the File class helps track <strong>disk usage</strong>. Let’s build a <strong>self-contained monitoring class</strong>.</p><h3>📌 The Complete SystemMonitoringService Implementation</h3><pre>package com.devjefster.service;<br><br>import java.io.File;<br>import java.lang.management.GarbageCollectorMXBean;<br>import java.lang.management.ManagementFactory;<br>import java.lang.management.OperatingSystemMXBean;<br>import java.lang.management.ThreadMXBean;<br>import java.net.NetworkInterface;<br>import java.net.SocketException;<br>import java.time.Instant;<br>import java.time.LocalDateTime;<br>import java.time.ZoneId;<br>import java.util.Collections;<br>import java.util.Enumeration;<br>import java.util.logging.Level;<br>import java.util.logging.Logger;<br><br>public class SystemMonitoringService {<br>    private static final long STARTUP_TIME = ManagementFactory.getRuntimeMXBean().getStartTime();<br>    private static final Logger logger = Logger.getLogger(SystemMonitoringService.class.getName());<br>    <br>    private final OperatingSystemMXBean osBean;<br>    private final Runtime runtime;<br>    private final ThreadMXBean threadMXBean;<br>    private final GarbageCollectorMXBean gcBean;<br><br>    public SystemMonitoringService() {<br>        this.osBean = ManagementFactory.getOperatingSystemMXBean();<br>        this.runtime = Runtime.getRuntime();<br>        this.threadMXBean = ManagementFactory.getThreadMXBean();<br>        this.gcBean = ManagementFactory.getGarbageCollectorMXBeans().get(0);<br>    }<br><br>    public void checkSystemUsage(String serviceName) {<br>        logStart(serviceName);<br>        try {<br>            checkHeapMemoryUsage(serviceName);<br>            checkCpuUsage(serviceName);<br>            checkDiskUsage(serviceName);<br>            checkNetworkUsage(serviceName);<br>            checkThreadCount(serviceName);<br>            checkGCStats(serviceName);<br>        } catch (Exception exception) {<br>            logError(&quot;Error during system usage check&quot;, serviceName, exception);<br>        }<br>        logEnd(serviceName);<br>    }<br><br>    private void checkHeapMemoryUsage(String serviceName) {<br>        long total = runtime.totalMemory();<br>        long free = runtime.freeMemory();<br>        long used = total - free;<br>        logInfo(String.format(&quot;Heap Memory Usage: %dMB / %dMB&quot;, used / 1048576, total / 1048576), serviceName);<br>    }<br><br>    private void checkCpuUsage(String serviceName) {<br>        double load = osBean.getSystemLoadAverage();<br>        logInfo(String.format(&quot;CPU Load: %.2f&quot;, load), serviceName);<br>    }<br><br>    private void checkDiskUsage(String serviceName) {<br>        File root = new File(&quot;/&quot;);<br>        long total = root.getTotalSpace();<br>        long free = root.getFreeSpace();<br>        logInfo(String.format(&quot;Disk Usage: %dGB free of %dGB&quot;, free / 1073741824, total / 1073741824), serviceName);<br>    }<br><br>    private void checkNetworkUsage(String serviceName) {<br>        try {<br>            Enumeration&lt;NetworkInterface&gt; networkInterfaces = NetworkInterface.getNetworkInterfaces();<br>            for (NetworkInterface net : Collections.list(networkInterfaces)) {<br>                logInfo(String.format(&quot;Network Interface: %s&quot;, net.getName()), serviceName);<br>            }<br>        } catch (SocketException e) {<br>            logError(&quot;Error retrieving network interfaces&quot;, serviceName, e);<br>        }<br>    }<br><br>    private void checkThreadCount(String serviceName) {<br>        int threadCount = threadMXBean.getThreadCount();<br>        logInfo(String.format(&quot;Active Threads: %d&quot;, threadCount), serviceName);<br>    }<br><br>    private void checkGCStats(String serviceName) {<br>        long gcCount = gcBean.getCollectionCount();<br>        logInfo(String.format(&quot;GC Collections: %d&quot;, gcCount), serviceName);<br>    }<br><br>    public void logStartupTime(String serviceName) {<br>        Instant startupInstant = Instant.ofEpochMilli(STARTUP_TIME);<br>        LocalDateTime startupTime = LocalDateTime.ofInstant(startupInstant, ZoneId.systemDefault());<br>        logInfo(&quot;Application Startup Time: &quot; + startupTime, serviceName);<br>    }<br><br>    private void logInfo(String message, String serviceName) {<br>        logger.log(Level.INFO, &quot;[{0}] {1}&quot;, new Object[]{serviceName, message});<br>    }<br><br>    private void logError(String message, String serviceName, Exception exception) {<br>        logger.log(Level.SEVERE, &quot;[{0}] {1} - {2}&quot;, new Object[]{serviceName, message, exception.getMessage()});<br>    }<br><br>    private void logStart(String serviceName) {<br>        logger.log(Level.INFO, &quot;🔹 [{0}] Monitoring started&quot;, new Object[]{serviceName});<br>    }<br><br>    private void logEnd(String serviceName) {<br>        logger.log(Level.INFO, &quot;✅ [{0}] Monitoring completed&quot;, new Object[]{serviceName});<br>    }<br>}</pre><h3>2️⃣ Integrating SystemMonitoringService in the main Class</h3><p>Now, let’s integrate the SystemMonitoringService into our main class for continuous monitoring.</p><h3>📌 App.java - Running the Monitoring Service</h3><pre>package com.devjefster;<br><br>import com.devjefster.service.SystemMonitoringService;<br><br>public class App {<br>    public static void main(String[] args) {<br>        SystemMonitoringService monitoringService = new SystemMonitoringService();<br>        System.out.println(&quot;🔹 Starting System Monitoring...&quot;);<br>        <br>        monitoringService.logStartupTime(&quot;MonitoringApp&quot;);<br>        while (true) {<br>            monitoringService.checkSystemUsage(&quot;MonitoringApp&quot;);<br>            try {<br>                Thread.sleep(5000); // Run every 5 seconds<br>            } catch (InterruptedException e) {<br>                System.err.println(&quot;Monitoring interrupted: &quot; + e.getMessage());<br>                Thread.currentThread().interrupt();<br>                break;<br>            }<br>        }<br>    }<br>}</pre><h3>3️⃣ Running the Application</h3><p>After compiling the project with Maven, you can run:</p><pre>mvn clean install<br>java -jar target/java-monitoring-1.0-SNAPSHOT.jar</pre><pre>🔹 Starting System Monitoring...<br>✅ [MonitoringApp] Application Startup Time: 2025-02-11T12:00:00<br>✅ [MonitoringApp] Monitoring started<br>✅ [MonitoringApp] Heap Memory Usage: 512MB / 1024MB<br>✅ [MonitoringApp] CPU Load: 3.50<br>✅ [MonitoringApp] Disk Usage: 100GB free of 250GB<br>✅ [MonitoringApp] Monitoring completed</pre><h3>📌 GitHub Repository</h3><p>The complete source code is available on GitHub: <a href="https://github.com/devjefster/monitoring-java">Monitoring System Metrics in Java</a></p><h3>🔹 Conclusion</h3><p>This article covered a <strong>complete system monitoring solution in Java</strong> without external dependencies. While this approach works well for basic monitoring, it lacks real-time <strong>CPU percentage tracking and network throughput analysis</strong>. In our next article, we will integrate **OSHI (oshi-core) for advanced monitoring. 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4d65ae20a230" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GoValidator — The Lightweight and Powerful Validation Library for Go Developers]]></title>
            <link>https://medium.com/@dev.jefster/govalidator-the-lightweight-and-powerful-validation-library-for-go-developers-6920b67e8809?source=rss-6829b15dd270------2</link>
            <guid isPermaLink="false">https://medium.com/p/6920b67e8809</guid>
            <category><![CDATA[go]]></category>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[validation]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[libraries]]></category>
            <dc:creator><![CDATA[Jefster]]></dc:creator>
            <pubDate>Mon, 10 Feb 2025 13:36:30 GMT</pubDate>
            <atom:updated>2025-02-10T13:36:30.410Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PspTMv4bPFrSg-eZcZXeXw.png" /></figure><h3>GoValidator — The Lightweight and Powerful Validation Library for Go Developers</h3><h3>🌟 Introduction</h3><p>Handling <strong>input validation</strong> is one of the most common yet repetitive tasks in software development. In the <strong>Java</strong> ecosystem, developers often rely on <strong>Bean Validation (Jakarta Validation)</strong> but Go lacks a built-in equivalent.</p><p>That’s why I built <strong>GoValidator</strong> — a <strong>lightweight, powerful, and easy-to-use validation library</strong> designed specifically for Go!</p><h3>📌 Why GoValidator?</h3><p>✅ <strong>Easy-to-use struct-based validation</strong><br>✅ <strong>Supports numbers, strings, booleans, collections, and dates</strong><br>✅ <strong>Inspired by Java Bean Validation but optimized for Go</strong><br>✅ <strong>Flexible rules like </strong><strong>minSize, </strong><strong>isTrue, </strong><strong>past, and more</strong><br>✅ <strong>Lightweight with zero external dependencies</strong></p><h3>📌 Getting Started</h3><h3>🔹 Installation</h3><p>To install GoValidator as a Go module:</p><pre>go get github.com/devjefster/GoValidator@latest</pre><h3>🔹 Basic Usage</h3><p>To validate a struct, simply add validate tags to your fields.</p><pre>package main<br><br>import (<br> &quot;fmt&quot;<br> &quot;github.com/devjefster/GoValidator&quot;<br>)<br><br>type User struct {<br> Username string `validate:&quot;required,minSize=3,maxSize=15&quot;`<br> Email    string `validate:&quot;required,email&quot;`<br> Age      int    `validate:&quot;required,positive&quot;`<br>}<br><br>func main() {<br> user := User{<br>  Username: &quot;jd&quot;,<br>  Email:    &quot;invalid-email&quot;,<br>  Age:      -5,<br> }<br><br> errors := validator.Validate(user)<br><br> if errors.HasErrors() {<br>  fmt.Println(&quot;Validation failed:&quot;)<br>  for _, err := range errors {<br>   fmt.Println(&quot;-&quot;, err)<br>  }<br> } else {<br>  fmt.Println(&quot;Validation passed ✅&quot;)<br> }<br>}</pre><p>🔹 Output:</p><pre>Validation failed:<br>- Username must have at least 3 characters<br>- Email is not a valid email<br>- Age must be positive</pre><h3>📌 Available Validation Rules</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/741/1*rUEnkp2Y4_CJ6qwvcGQAlg.png" /><figcaption>Available Validation Rules. Source: README.md</figcaption></figure><h3>📌 Advanced Example</h3><p>This example demonstrates <strong>all validation rules</strong> applied to a User struct.</p><pre>package main<br><br>import (<br> &quot;fmt&quot;<br> &quot;github.com/devjefster/GoValidator&quot;<br>)<br><br>type User struct {<br> Username      string   `validate:&quot;required,minSize=3,maxSize=15&quot;`<br> Email         string   `validate:&quot;required,email&quot;`<br> Age           int      `validate:&quot;required,positive&quot;`<br> Balance       float64  `validate:&quot;positiveOrZero&quot;`<br> IsActive      bool     `validate:&quot;isTrue&quot;`<br> Tags          []string `validate:&quot;minSize=1,maxSize=5&quot;`<br> Birthdate     string   `validate:&quot;date=2006-01-02,pastInclusive=2006-01-02&quot;`<br> Subscription  string   `validate:&quot;date=2006-01-02,future=2006-01-02&quot;`<br> PhoneNumbers  []string `validate:&quot;size=2&quot;`<br> Comment       string   `validate:&quot;maxSize=200&quot;`<br> FavoriteItems []int    `validate:&quot;minSize=2&quot;`<br>}<br><br>func main() {<br> user := User{<br>  Username:      &quot;johndoe&quot;,<br>  Email:         &quot;johndoe@example.com&quot;,<br>  Age:           25,<br>  Balance:       100.50,<br>  IsActive:      true,<br>  Tags:          []string{&quot;Go&quot;, &quot;Golang&quot;},<br>  Birthdate:     &quot;1995-06-15&quot;,<br>  Subscription:  &quot;2025-01-01&quot;,<br>  PhoneNumbers:  []string{&quot;123-456-7890&quot;, &quot;987-654-3210&quot;},<br>  Comment:       &quot;This is a sample comment.&quot;,<br>  FavoriteItems: []int{1, 2},<br> }<br><br> errors := validator.Validate(user)<br><br> if errors.HasErrors() {<br>  fmt.Println(&quot;Validation failed:&quot;)<br>  for _, err := range errors {<br>   fmt.Println(&quot;-&quot;, err)<br>  }<br> } else {<br>  fmt.Println(&quot;Validation passed ✅&quot;)<br> }<br>}</pre><h3>📌 Running Tests</h3><p>To ensure everything is working, run:</p><pre>go test -v ./...</pre><h3>📌 Contribute &amp; Support</h3><p>Want to improve <strong>GoValidator</strong>? Feel free to: ✅ <strong>Fork the repo</strong> → <a href="https://github.com/devjefster/GoValidator">GitHub Repo</a><br>✅ <strong>Submit pull requests</strong><br>✅ <strong>Report issues</strong></p><h3>📌 Final Thoughts</h3><p><strong>GoValidator</strong> brings <strong>simple and powerful validation</strong> to the Go ecosystem, filling a gap that many developers have faced. It’s lightweight, easy to use, and fully extensible.</p><p>Try it out, contribute, and let’s make <strong>Go validation better together</strong>! 🚀🔥</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6920b67e8809" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Building GoShortUniqueID: A Lightweight, Customizable, and Sortable ID Generator for Go]]></title>
            <link>https://medium.com/@dev.jefster/building-goshortuniqueid-a-lightweight-customizable-and-sortable-id-generator-for-go-c5d5e1ece6d8?source=rss-6829b15dd270------2</link>
            <guid isPermaLink="false">https://medium.com/p/c5d5e1ece6d8</guid>
            <category><![CDATA[go]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[uuid]]></category>
            <dc:creator><![CDATA[Jefster]]></dc:creator>
            <pubDate>Mon, 10 Feb 2025 11:58:33 GMT</pubDate>
            <atom:updated>2025-02-10T11:58:33.416Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PspTMv4bPFrSg-eZcZXeXw.png" /></figure><p>We developers often need <strong>unique identifiers</strong> for various use cases: database keys, API tokens, URL slugs, and more. While UUIDs are a popular choice, they are long and not human-readable. Inspired by this challenge, I built <strong>GoShortUniqueID</strong>, a lightweight library for generating <strong>short, sortable, and customizable unique IDs</strong>.</p><p>In this article, I’ll explain the motivation behind the library, its features, and how you can integrate it into your Go projects.</p><h3>🌟 Why GoShortUniqueID?</h3><p>When working on my projects, I realized that most ID solutions (like UUIDs) had limitations:</p><ul><li><strong>Too Long</strong>: UUIDs are 36 characters by default, which can be overkill for small-scale applications.</li><li><strong>Not Human-Readable</strong>: UUIDs like 550e8400-e29b-41d4-a716-446655440000 are not user-friendly.</li><li><strong>Not Sortable</strong>: UUIDs don’t help when you want IDs to be chronologically ordered.</li></ul><p>To solve these issues, I built <strong>GoShortUniqueID</strong> with the following goals:</p><ol><li><strong>Short and Human-Readable</strong>: IDs should be compact and easy to read.</li><li><strong>Chronologically Sortable</strong>: IDs should naturally sort by creation time.</li><li><strong>Customizable</strong>: Developers should be able to control the length and character set.</li><li><strong>Thread-Safe</strong>: The library should work seamlessly in concurrent environments.</li></ol><h3>🚀 Features</h3><p>Here’s what makes GoShortUniqueID stand out:</p><ul><li><strong>Chronological Order</strong>: Each ID starts with a timestamp (YYMMDDHHmmss), making it sortable.</li><li><strong>Custom Length</strong>: You can define the length of the random part.</li><li><strong>Custom Charset</strong>: Use alphanumeric, numeric-only, or your custom character set.</li><li><strong>Thread-Safe</strong>: Built-in atomic counters prevent collisions in concurrent environments.</li><li><strong>URL-Friendly</strong>: Encodes IDs in Base64 or Base58 for shorter, database-safe strings.</li></ul><h3>🛠️ How It Works</h3><p>At its core, GoShortUniqueID combines:</p><ol><li>A <strong>timestamp prefix</strong> (e.g., YYMMDDHHmmss).</li><li>A <strong>random string</strong> of customizable length.</li><li>A <strong>4-digit counter</strong> to ensure uniqueness within the same millisecond.</li></ol><p>Here’s a sample ID:</p><pre>240210120530XYZ9876</pre><ul><li><strong>240210120530</strong>: Timestamp (YYMMDDHHmmss).</li><li><strong>XYZ9876</strong>: Random string (customizable length).</li><li><strong>0001</strong>: Counter to prevent collisions.</li></ul><h3>💻 Getting Started</h3><h3>Installation</h3><p>To install the library, run:</p><pre>package main<br><br>import (<br> &quot;fmt&quot;<br> &quot;github.com/devjefster/GoShortUniqueID/idgen&quot;<br>)<br><br>func main() {<br> // Create an ID generator with default settings<br> idGen := idgen.New(6, &quot;&quot;, &quot;&quot;)<br><br> // Generate unique IDs<br> for i := 0; i &lt; 5; i++ {<br>  fmt.Println(idGen.Generate())<br> }<br>}</pre><p>🔹 <strong>Example Output</strong>:</p><pre>240210120530XYZ9876<br>240210120530ABC5432<br>240210120530TUV7890</pre><h3>Advanced Customization</h3><p><strong>Custom Character Set</strong>: Use a numeric-only character set:</p><pre>idGen := idgen.New(8, &quot;1234567890&quot;, &quot;&quot;)<br>fmt.Println(idGen.Generate())</pre><p><strong>Custom Timestamp Format</strong>: Use the full YYYYMMDDHHMMSS format:</p><pre>idGen := idgen.New(6, &quot;&quot;, &quot;20060102150405&quot;)<br>fmt.Println(idGen.Generate())</pre><p><strong>URL-Friendly Encoding</strong>: Encode IDs as Base64 or Base58 for shorter, safe strings:</p><pre>id := idGen.Generate()<br>fmt.Println(&quot;Base64:&quot;, idgen.EncodeBase64(id))<br>fmt.Println(&quot;Base58:&quot;, idgen.EncodeBase58(id))</pre><h3>⚡ Performance</h3><p>GoShortUniqueID is highly optimized for speed and concurrency. It can generate over <strong>1 million unique IDs per second</strong>. Here’s a sample benchmark result:</p><pre>BenchmarkGenerate-8                   1000000       1200 ns/op<br>BenchmarkGenerate_Concurrent-8        2000000        800 ns/op<br>BenchmarkEncodeBase64-8               3000000        500 ns/op<br>BenchmarkEncodeBase58-8               2500000        600 ns/op</pre><h3>Under the Hood</h3><p>GoShortUniqueID uses:</p><ol><li><strong>Atomic Counters</strong>: Ensures thread safety during ID generation.</li><li><strong>Random Sources</strong>: Generates unique random strings based on custom character sets.</li><li><strong>Time Formatting</strong>: Utilizes Go’s time package for efficient timestamp generation.</li></ol><h3>Use Cases</h3><p>Here are some scenarios where GoShortUniqueID can shine:</p><ul><li><strong>Database Keys</strong>: Replace UUIDs with shorter, sortable IDs.</li><li><strong>API Tokens</strong>: Generate human-readable API keys.</li><li><strong>URL Slugs</strong>: Use compact IDs for cleaner URLs.</li><li><strong>Concurrency-Safe Identifiers</strong>: Handle high-throughput systems without collisions.</li></ul><h3>📜 License</h3><p>GoShortUniqueID is open-source and licensed under the <strong>MIT License</strong>. You can find the full text of the license <a href="https://github.com/devjefster/GoShortUniqueID/blob/main/LICENSE">here</a>.</p><h3>Conclusion</h3><p>GoShortUniqueID is designed to make ID generation <strong>simpler, faster, and more customizable</strong>. Whether you’re building APIs, working with databases, or creating unique keys, this library offers a robust solution.</p><p>👉 <strong>Check out the project on GitHub</strong>: <a href="https://github.com/devjefster/GoShortUniqueID">GoShortUniqueID</a></p><p>Feel free to share your thoughts or contribute to the project. I’d love to see how you’re using GoShortUniqueID in your projects!</p><p>What do you think of this draft? Would you like me to refine any section or add additional details? 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c5d5e1ece6d8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using TypeScript Enums in Select Components with React]]></title>
            <link>https://medium.com/@dev.jefster/using-typescript-enums-in-select-components-with-react-d33a733767a9?source=rss-6829b15dd270------2</link>
            <guid isPermaLink="false">https://medium.com/p/d33a733767a9</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[enum]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Jefster]]></dc:creator>
            <pubDate>Mon, 30 Dec 2024 20:38:45 GMT</pubDate>
            <atom:updated>2024-12-30T20:38:45.333Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*nn5p8XSge23k3dmXS-EGng.png" /></figure><p>When working on React projects with TypeScript, enums are a great way to manage constant values in a type-safe manner. They help ensure consistency and reduce the risk of errors. In this article, I’ll show you how to create a reusable Selector component that supports TypeScript enums, making it easy to use enums in dropdown menus while maintaining type safety and flexibility.</p><h3>Why Use Enums?</h3><p>Enums allow you to define a set of named constants. For example:</p><pre>export enum UserRole {<br>    ADMIN = &quot;admin&quot;,<br>    USER = &quot;user&quot;,<br>    GUEST = &quot;guest&quot;,<br>}</pre><p>Enums are particularly useful for values that don’t change frequently, like roles, categories, or statuses. Using enums with React forms ensures that your code remains consistent and reduces the risk of typos.</p><h3>The Problem</h3><p>While using enums with React’s &lt;select&gt; is straightforward, it can get repetitive and error-prone if you manually map the enum values every time. A reusable Selector component solves this problem by dynamically generating dropdown options from the enum.</p><h3>Building the Selector Component</h3><p>Here’s how to create a reusable Selector component that works seamlessly with TypeScript enums.</p><h4>Step 1: Define the Component</h4><p>The Selector component dynamically maps a TypeScript enum to &lt;option&gt; elements. It also supports optional transformations for readable labels.</p><pre>import React from &quot;react&quot;;<br><br>interface SelectorProps&lt;T&gt; {<br>    value?: T[keyof T]; // Selected value, based on the enum type<br>    placeholder?: string; // Optional placeholder text<br>    enumType: T; // The TypeScript enum<br>    onChange: (selectedKey: T[keyof T]) =&gt; void; // Callback when an option is selected<br>    labelTransform?: (key: keyof T) =&gt; string; // Optional transformation for readable labels<br>}<br><br>const Selector = &lt;T extends Record&lt;string, string&gt;&gt;({<br>    value,<br>    placeholder = &quot;Select an option&quot;,<br>    enumType,<br>    onChange,<br>    labelTransform,<br>}: SelectorProps&lt;T&gt;) =&gt; {<br>    const handleChange = (e: React.ChangeEvent&lt;HTMLSelectElement&gt;) =&gt; {<br>        onChange(e.target.value as T[keyof T]); // Pass the selected value to the parent<br>    };<br><br>    const options = Object.entries(enumType).map(([key, val]) =&gt; ({<br>        key,<br>        value: val,<br>        label: labelTransform ? labelTransform(key as keyof T) : key.replace(/_/g, &quot; &quot;),<br>    }));<br><br>    return (<br>        &lt;select value={value} onChange={handleChange} className=&quot;select-class&quot;&gt;<br>            &lt;option value=&quot;&quot;&gt;{placeholder}&lt;/option&gt;<br>            {options.map((option) =&gt; (<br>                &lt;option key={option.key} value={option.value}&gt;<br>                    {option.label}<br>                &lt;/option&gt;<br>            ))}<br>        &lt;/select&gt;<br>    );<br>};<br><br>export default Selector;</pre><h4>Step 2: Use the Component with an Enum</h4><p>Here’s how you can use the Selector component with an UserRole enum:</p><pre>import React, { useState } from &quot;react&quot;;<br>import { Selector } from &quot;./Selector&quot;;<br><br>enum UserRole {<br>    ADMIN = &quot;admin&quot;,<br>    USER = &quot;user&quot;,<br>    GUEST = &quot;guest&quot;,<br>}<br><br>const App = () =&gt; {<br>    const [role, setRole] = useState&lt;UserRole | &quot;&quot;&gt;(&quot;&quot;);<br><br>    return (<br>        &lt;div&gt;<br>            &lt;h1&gt;Select a User Role&lt;/h1&gt;<br>            &lt;Selector<br>                enumType={UserRole}<br>                value={role}<br>                placeholder=&quot;Choose a role&quot;<br>                onChange={(selectedRole) =&gt; setRole(selectedRole)}<br>                labelTransform={(key) =&gt; key.charAt(0) + key.slice(1).toLowerCase()} // Optional: Capitalize labels<br>            /&gt;<br>            &lt;p&gt;Selected Role: {role || &quot;None&quot;}&lt;/p&gt;<br>        &lt;/div&gt;<br>    );<br>};<br><br>export default App;</pre><h3>Why This Approach Works</h3><p><strong>Type Safety</strong>:</p><ul><li>Ensures that only valid enum values are used.</li></ul><p><strong>Dynamic Options</strong>:</p><ul><li>Automatically generates options from the enum, avoiding manual mapping.</li></ul><p><strong>Customizable Labels</strong>:</p><ul><li>Use the labelTransform prop to transform enum keys into user-friendly labels.</li></ul><h3>Conclusion</h3><p>This reusable Selector component simplifies working with enums in React, making your forms cleaner and your codebase safer. By leveraging TypeScript&#39;s powerful type system, you can build robust and maintainable components that adapt to changes effortlessly.</p><p>Enums are just the start — this approach can be extended to handle other structured data. Try it out and elevate your forms today!</p><p>If you found this helpful, feel free to share or leave a comment! 😊</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d33a733767a9" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>