<?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 Matheshyogeswaran on Medium]]></title>
        <description><![CDATA[Stories by Matheshyogeswaran on Medium]]></description>
        <link>https://medium.com/@matheshyogeswaran?source=rss-505ef1b70e94------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*7nAwKASCUznmImQ7icsCaw.jpeg</url>
            <title>Stories by Matheshyogeswaran on Medium</title>
            <link>https://medium.com/@matheshyogeswaran?source=rss-505ef1b70e94------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 03:11:26 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@matheshyogeswaran/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[Dockerizing a Spring Boot + MongoDB Application (Step-by-Step Guide)]]></title>
            <link>https://matheshyogeswaran.medium.com/dockerizing-a-spring-boot-mongodb-application-step-by-step-guide-9dad206dc8c1?source=rss-505ef1b70e94------2</link>
            <guid isPermaLink="false">https://medium.com/p/9dad206dc8c1</guid>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[docker-compose]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Matheshyogeswaran]]></dc:creator>
            <pubDate>Sat, 14 Feb 2026 10:56:17 GMT</pubDate>
            <atom:updated>2026-02-14T10:56:17.527Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello everyone! Containerization has become an essential skill for backend developers. It eliminates environment-related issues, improves portability, and makes applications production-ready.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xzq79mNSK_zJSD7LETgV8A.png" /><figcaption>Artwork By A<a href="https://matheshyogeswaran.medium.com/">uthor</a></figcaption></figure><p>In this article, I’ll walk you through how I dockerized my <strong>Spring Boot Book Store application</strong> with <strong>MongoDB</strong> using Docker and Docker Compose.</p><p>By the end of this guide, you’ll be able to run everything with a single command:</p><pre>docker-compose up --build</pre><p>For this guide, I will use an application I already developed and explained in this article:</p><p><a href="https://medium.com/@matheshyogeswaran/spring-boot-jwt-role-based-authentication-with-mongodb-building-a-book-store-application-66197ff76c01">Spring Boot JWT Role-Based Authentication with MongoDB — Building a Book Store Application.</a></p><p>The project is a simple <strong>Book Store backend application</strong> built with Spring Boot and MongoDB.</p><p>The goal was to:</p><ul><li>Containerize the Spring Boot application</li><li>Run MongoDB inside Docker</li><li>Connect both services using Docker Compose</li><li>Ensure data persistence</li></ul><h3>Step 1: Build the Spring Boot Application</h3><p>Before creating a Docker image, we need to generate the JAR file.</p><pre>mvn clean package -DskipTests</pre><h3>Why -DskipTests?</h3><p>Sometimes, integration tests try to connect to MongoDB during the build process. If MongoDB isn’t running, tests may fail. Skipping tests ensures a smooth build during Dockerization.</p><p>After running this command, Maven generates:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/1*1Q7ImLPJyEo8CannukeUOA.png" /><figcaption>book-store.jar</figcaption></figure><pre>target/book-store.jar</pre><h3>🐳 Step 2: Create the Dockerfile</h3><p>Next, create a Dockerfile in the project root directory.</p><pre># Use OpenJDK 22<br>FROM openjdk:22-jdk</pre><pre># Set working directory inside container<br>WORKDIR /app</pre><pre># Copy the built jar into the container<br>COPY target/book-store.jar book-store.jar</pre><pre># Expose Spring Boot default port<br>EXPOSE 8080</pre><pre># Run the Spring Boot application<br>ENTRYPOINT [&quot;java&quot;, &quot;-jar&quot;, &quot;book-store.jar&quot;]</pre><h3>Explanation</h3><ul><li>FROM openjdk:22-jdk → Base Java image</li><li>WORKDIR /app → Working directory inside container</li><li>COPY target/book-store.jar → Copies the generated JAR file into the container. Make sure the JAR name matches the one created by Maven inside the target folder.</li><li>EXPOSE 8080 → Opens application port</li><li>ENTRYPOINT → Runs the application</li></ul><p>This Dockerfile defines how our Spring Boot application runs inside a container.</p><h3>🐳 Step 3: Create docker-compose.yml</h3><p>To run Spring Boot and MongoDB together, we use Docker Compose.</p><p>Create a docker-compose.yml file:</p><pre><br>services:<br>  app:<br>    build: .<br>    ports:<br>      - &quot;8080:8080&quot;<br>    environment:<br>      - SPRING_DATA_MONGODB_HOST=mongo<br>      - SPRING_DATA_MONGODB_PORT=27017<br>    depends_on:<br>      - mongo<br><br>  mongo:<br>    image: mongo:7.0<br>    container_name: bookstore-mongo<br>    ports:<br>      - &quot;27017:27017&quot;<br>    environment:<br>      MONGO_INITDB_DATABASE: bookstore<br>      MONGO_INITDB_ROOT_USERNAME: root<br>      MONGO_INITDB_ROOT_PASSWORD: rootpassword<br>    volumes:<br>      - mongo-data:/data/db<br><br>volumes:<br>  mongo-data:</pre><h3>🔍 Important Concepts Explained</h3><h3>1. Why use mongo instead of localhost?</h3><p>Inside Docker:</p><ul><li>localhost refers to the container itself</li><li>mongo refers to the MongoDB service defined in Docker Compose</li></ul><p>Docker automatically creates a network and allows services to communicate using their service names.</p><p>That’s why we use:</p><pre>SPRING_DATA_MONGODB_HOST=mongo</pre><p>instead of:</p><pre>localhost</pre><h3>2️⃣ What does depends_on do?</h3><pre>depends_on:<br>  - mongo</pre><p>It ensures the Mongo container starts before the app container.</p><p>However, it does NOT guarantee MongoDB is fully ready — only that the container has started.</p><h3>3️⃣ Why use a Volume?</h3><pre>volumes:<br>  - mongo-data:/data/db</pre><p>This ensures MongoDB data persists even if containers are stopped or removed.</p><p>Without volumes, all data would be lost on container restart.</p><h3>▶️ Step 4: Run the Application</h3><p>Now everything is ready.</p><p>Run:</p><pre>docker-compose up --build</pre><p>Once started:</p><ul><li>Spring Boot → <a href="http://localhost:8080/">http://localhost:8080</a></li><li>MongoDB → Running inside Docker</li><li>Both connected via internal Docker network</li></ul><h3>⚠️ Common Mistakes (And How to Avoid Them)</h3><h3>❌ Using localhost inside Docker</h3><p>This is the most common mistake.</p><p>Inside containers, localhost does NOT refer to your machine — it refers to the container itself.</p><p>Always use the service name (mongo) instead.</p><h3>Forgetting to Build the JAR</h3><p>If you don’t run:</p><pre>mvn clean package</pre><p>before building the Docker image, the JAR file won’t exist — and Docker build will fail.</p><h3>🎯 What We Achieved</h3><ul><li>Spring Boot running inside Docker</li><li>MongoDB running inside Docker</li><li>Both connected using Docker networking</li><li>Persistent MongoDB storage</li><li>Clean and portable setup</li></ul><p>This setup eliminates “works on my machine” problems and prepares the project for production deployment.</p><p>You can access the complete source code on GitHub:</p><p><a href="https://github.com/matheshyogeswaran/book-store/tree/Docker-setup">GitHub - matheshyogeswaran/book-store at Docker-setup</a></p><p>if you found this guide helpful, feel free to connect with me on <a href="https://www.linkedin.com/in/mathesh-yogeswaran/">LinkedIn</a> or leave a comment on Medium.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9dad206dc8c1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Boot JWT Role-Based Authentication with MongoDB: Building a Book Store Application]]></title>
            <link>https://matheshyogeswaran.medium.com/spring-boot-jwt-role-based-authentication-with-mongodb-building-a-book-store-application-66197ff76c01?source=rss-505ef1b70e94------2</link>
            <guid isPermaLink="false">https://medium.com/p/66197ff76c01</guid>
            <category><![CDATA[jwt]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[spring-framework]]></category>
            <dc:creator><![CDATA[Matheshyogeswaran]]></dc:creator>
            <pubDate>Sun, 08 Feb 2026 19:20:51 GMT</pubDate>
            <atom:updated>2026-02-14T10:45:43.127Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello everyone. Today, we are going to implement <strong>JWT token-based role authentication</strong> in a small Spring Boot application.</p><p>We’ll build a <strong>Book Store application</strong> where:</p><ul><li><strong>Users</strong> can view books.</li><li><strong>Admins</strong> can create, update, and delete books.</li></ul><p>We’ll start by creating CRUD operations and then implement <strong>JWT role-based authentication</strong>.</p><h3>1. Setup Spring Boot</h3><p>In Spring Initializr, select the following dependencies:</p><ul><li>Spring Web</li><li>Spring Data MongoDB</li><li>Spring Security</li></ul><p>In application.properties:</p><pre>spring.application.name=book-store<br>server.port=8080<br>spring.mongodb.host=localhost<br>spring.mongodb.port=27017<br>spring.mongodb.database=bookstore</pre><blockquote><strong><em>Explanation:</em></strong><em> This sets the application name, port, and MongoDB connection details.</em></blockquote><h3>2. Book Entity</h3><pre>package com.mathesh.book_store.entity;<br>public record Book(String bookId, String name, String price, String author) {}</pre><blockquote><strong><em>Explanation:</em></strong><em> Defines the </em><em>Book entity with fields: </em><em>bookId, </em><em>name, </em><em>price, and </em><em>author.</em></blockquote><h3>3. Book DTO</h3><pre>package com.mathesh.book_store.dto;<br>public record BookDto(String bookId, String name, String price, String author) {}</pre><blockquote><strong><em>Explanation:</em></strong><em> Data Transfer Object (DTO) used to transfer book data between layers.</em></blockquote><h3>4. Book Mapper</h3><pre>package com.mathesh.book_store.mapper;<br><br>import com.mathesh.book_store.dto.BookDto;<br>import com.mathesh.book_store.entity.Book;<br><br>public class BookMapper {<br><br>    public static BookDto toDto(Book book)<br>    {<br>        BookDto bookDto = new BookDto(book.bookId(), book.name(), book.price(), book.author());<br>        return bookDto;<br>    }<br><br>    public static Book toEntity(BookDto bookDto)<br>    {<br>        Book book = new Book(bookDto.bookId(), bookDto.name(), bookDto.price(), bookDto.author());<br>        return book;<br>    }<br>}</pre><blockquote><strong><em>Explanation:</em></strong><em> Maps between </em><em>Book entity and </em><em>BookDto for cleaner separation of layers.</em></blockquote><h3>5. Book Repository</h3><pre>package com.mathesh.book_store.repository;<br><br>import com.mathesh.book_store.entity.Book;<br>import org.springframework.data.mongodb.repository.DeleteQuery;<br>import org.springframework.data.mongodb.repository.MongoRepository;<br>import org.springframework.data.mongodb.repository.Query;<br>import org.springframework.data.mongodb.repository.Update;<br><br>public interface BookRepository extends MongoRepository&lt;Book, String&gt; {<br><br>    @Query(&quot;{bookId :  &#39;?0&#39;}&quot;)<br>    Book findBooksByBookId(String bookId);<br><br>    @Query(value = &quot;{&#39;bookId&#39;: {$eq :  ?0}}&quot;)<br>    @Update(pipeline = &quot;{ &#39;$set&#39;: { &#39;name&#39;: ?1 } }&quot;)<br>    void updateBookNameByBookId(String bookId,String name);<br><br>    @DeleteQuery<br>    void deleteBookByBookId(String bookId);<br>}</pre><blockquote><strong><em>Explanation:</em></strong><em> Handles CRUD operations with MongoDB. Custom queries for finding, updating, and deleting books are defined.</em></blockquote><h3>6. Book Service</h3><pre>package com.mathesh.book_store.service;<br><br>import com.mathesh.book_store.dto.BookDto;<br>import org.springframework.stereotype.Service;<br><br>import java.util.List;<br><br>@Service<br>public interface BookService {<br><br>    public BookDto getBook(String bookId);<br><br>    public List&lt;BookDto&gt; getAllBooks();<br><br>    public BookDto createBook(BookDto bookDto);<br><br>    public BookDto updateBookName(BookDto bookDto);<br><br>    void deleteBookByBookId(String bookId);<br>}</pre><blockquote><strong><em>Explanation:</em></strong><em> Service interface defines the business logic methods for book operations.</em></blockquote><h3>7. Book Service Implementation</h3><pre>package com.mathesh.book_store.service.impl;<br><br>import com.mathesh.book_store.dto.BookDto;<br>import com.mathesh.book_store.entity.Book;<br>import com.mathesh.book_store.mapper.BookMapper;<br>import com.mathesh.book_store.repository.BookRepository;<br>import com.mathesh.book_store.service.BookService;<br>import org.springframework.stereotype.Service;<br><br>import java.util.ArrayList;<br>import java.util.List;<br><br>@Service<br>public class BookServiceImpl implements BookService {<br><br>    BookRepository bookRepository;<br>    public BookServiceImpl(BookRepository bookRepository)<br>    {<br>        this.bookRepository = bookRepository;<br>    }<br><br>    @Override<br>    public BookDto getBook(String bookId) {<br>        Book book = bookRepository.findBooksByBookId(bookId);<br>        BookDto bookDto = BookMapper.toDto(book);<br>        return bookDto;<br>    }<br><br>    @Override<br>    public List&lt;BookDto&gt; getAllBooks() {<br>        List&lt;Book&gt; books = bookRepository.findAll();<br>        List&lt;BookDto&gt; bookDtoList = new ArrayList&lt;&gt;();<br>        for(Book book:books)<br>        {<br>            bookDtoList.add(BookMapper.toDto(book));<br>        }<br>        return bookDtoList;<br>    }<br><br>    @Override<br>    public BookDto createBook(BookDto bookDto) {<br><br>        Book book = bookRepository.insert(BookMapper.toEntity(bookDto));<br><br>        return BookMapper.toDto(book);<br>    }<br><br>    @Override<br>    public BookDto updateBookName(BookDto bookDto) {<br>        bookRepository.updateBookNameByBookId(bookDto.bookId(),bookDto.name());<br>        Book book = bookRepository.findBooksByBookId(bookDto.bookId());<br><br><br>        return BookMapper.toDto(book);<br>    }<br><br>    @Override<br>    public void deleteBookByBookId(String bookId) {<br>        bookRepository.deleteBookByBookId(bookId);<br><br>    }<br>}</pre><blockquote><strong><em>Explanation:</em></strong><em> Implements the service methods using </em><em>BookRepository and </em><em>BookMapper. Handles all CRUD operations.</em></blockquote><h3>8. Book Controller</h3><pre>package com.mathesh.book_store.controller;<br><br>import com.mathesh.book_store.dto.BookDto;<br>import com.mathesh.book_store.service.BookService;<br>import org.springframework.http.HttpStatus;<br>import org.springframework.http.ResponseEntity;<br>import org.springframework.security.access.prepost.PreAuthorize;<br>import org.springframework.web.bind.annotation.*;<br><br>import java.util.List;<br><br>@RestController<br>@RequestMapping(&quot;book-store&quot;)<br>public class BookController {<br><br>    BookService bookService;<br><br>    public BookController(BookService bookService) {<br>        this.bookService = bookService;<br>    }<br><br>    @GetMapping(&quot;/{bookId}&quot;)<br>    public ResponseEntity&lt;BookDto&gt; getBook(@PathVariable String bookId) {<br>        BookDto bookDto = bookService.getBook(bookId);<br>        return new ResponseEntity&lt;&gt;(bookDto, HttpStatus.OK);<br>    }<br><br>    @GetMapping(&quot;/&quot;)<br>    public ResponseEntity&lt;List&lt;BookDto&gt;&gt; getAllBooks() {<br>        List&lt;BookDto&gt; bookDtoList = bookService.getAllBooks();<br>        return new ResponseEntity&lt;&gt;(bookDtoList,HttpStatus.OK);<br>        <br>    }<br><br><br>    @PostMapping(&quot;/&quot;)<br>    public ResponseEntity&lt;BookDto&gt; createBooks(@RequestBody BookDto bookDto) {<br>        BookDto bookDto1 = bookService.createBook(bookDto);<br>        return new ResponseEntity&lt;&gt;(bookDto1,HttpStatus.OK);<br>        <br>    }<br><br>    @PutMapping(&quot;/&quot;)<br>    public ResponseEntity&lt;BookDto&gt; put(@RequestBody BookDto bookDto) {<br>       BookDto bookDto1 =  bookService.updateBookName(bookDto);<br>       return new ResponseEntity&lt;&gt;(bookDto1,HttpStatus.OK);<br><br><br>    }<br><br>    @DeleteMapping(&quot;/{bookId}&quot;)<br>    public ResponseEntity&lt;String&gt; deleteBook(@PathVariable  String bookId) {<br>        bookService.deleteBookByBookId(bookId);<br>        return new ResponseEntity&lt;&gt;(&quot;Book Deleted&quot;+bookId,HttpStatus.OK);<br>        <br>    }<br><br>    <br>}</pre><blockquote><strong><em>Explanation:</em></strong><em> REST controller for handling API requests.</em></blockquote><h3>9. Next Step: JWT Role-Based Authentication</h3><blockquote><em>Now that CRUD operations are ready, we can integrate </em><strong><em>JWT authentication</em></strong><em> to protect these APIs and enforce roles.</em></blockquote><p>In pom.xml, add the following dependencies.</p><pre>&lt;!-- Spring Security --&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><br>&lt;!-- JWT --&gt;<br>&lt;dependency&gt;<br>    &lt;groupId&gt;io.jsonwebtoken&lt;/groupId&gt;<br>    &lt;artifactId&gt;jjwt-api&lt;/artifactId&gt;<br>    &lt;version&gt;0.11.5&lt;/version&gt;<br>&lt;/dependency&gt;<br>&lt;dependency&gt;<br>    &lt;groupId&gt;io.jsonwebtoken&lt;/groupId&gt;<br>    &lt;artifactId&gt;jjwt-impl&lt;/artifactId&gt;<br>    &lt;version&gt;0.11.5&lt;/version&gt;<br>    &lt;scope&gt;runtime&lt;/scope&gt;<br>&lt;/dependency&gt;<br>&lt;dependency&gt;<br>    &lt;groupId&gt;io.jsonwebtoken&lt;/groupId&gt;<br>    &lt;artifactId&gt;jjwt-jackson&lt;/artifactId&gt;<br>    &lt;version&gt;0.11.5&lt;/version&gt;<br>    &lt;scope&gt;runtime&lt;/scope&gt;<br>&lt;/dependency&gt;</pre><h3>10. User Entity &amp; Role Enum</h3><pre>package com.mathesh.book_store.entity;import lombok.Data;<br>import org.springframework.data.annotation.Id;<br>import org.springframework.data.mongodb.core.mapping.Document;<br>import java.util.Set;@Document(collection = &quot;users&quot;)<br>@Data<br>public class User {<br>    @Id<br>    private String id;<br>    private String username;<br>    private String password;<br>    private Set&lt;Role&gt; roles;<br>}enum Role {<br>    ROLE_USER,<br>    ROLE_ADMIN<br>}</pre><blockquote><strong><em>Explanation:</em></strong><em><br> Defines a </em><em>User entity for MongoDB with </em><em>username, </em><em>password, and </em><em>roles.<br> </em><em>Role enum defines </em><strong><em>user roles</em></strong><em> that will be used for authorization.</em></blockquote><h3>11. JWT Utility</h3><pre>package com.mathesh.book_store.config;<br><br>import io.jsonwebtoken.*;<br>import io.jsonwebtoken.security.Keys;<br>import org.springframework.stereotype.Component;<br><br>import java.nio.charset.StandardCharsets;<br>import java.security.Key;<br>import java.util.Date;<br><br>@Component<br>public class JwtUtils {<br><br><br>    private final String jwtSecret = &quot;aVeryLongSecretKeyThatIsAtLeast64CharactersLongToBeSecureForHS512&quot;;<br>    private final long jwtExpirationMs = 86400000; // 1 day<br><br>    // Convert secret string to Key<br>    private final Key key = Keys.hmacShaKeyFor(jwtSecret.getBytes(StandardCharsets.UTF_8));<br><br>    public String generateJwtToken(String username) {<br>        return Jwts.builder()<br>                .setSubject(username)<br>                .setIssuedAt(new Date())<br>                .setExpiration(new Date(System.currentTimeMillis() + jwtExpirationMs))<br>                .signWith(key, SignatureAlgorithm.HS512) // &lt;-- use Key, not String<br>                .compact();<br>    }<br><br>    public String getUsernameFromJwt(String token) {<br>        return Jwts.parserBuilder()<br>                .setSigningKey(key) // &lt;-- use Key<br>                .build()<br>                .parseClaimsJws(token)<br>                .getBody()<br>                .getSubject();<br>    }<br><br>    public boolean validateJwtToken(String token) {<br>        try {<br>            Jwts.parserBuilder()<br>                    .setSigningKey(key) // &lt;-- use Key<br>                    .build()<br>                    .parseClaimsJws(token);<br>            return true;<br>        } catch (JwtException e) {<br>            return false;<br>        }<br>    }<br>}</pre><blockquote><strong><em>Explanation: </em></strong><em>Utility class for generating, validating, and parsing JWT tokens.</em></blockquote><ul><li>generateJwtToken() creates a token for a user.</li><li>getUsernameFromJwt() retrieves the username from the token.</li><li>validateJwtToken() checks if the token is valid.</li></ul><h3>12. Password Encoder Configuration</h3><pre>package com.mathesh.book_store.config;<br><br>import org.springframework.context.annotation.Bean;<br>import org.springframework.context.annotation.Configuration;<br>import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;<br>import org.springframework.security.crypto.password.PasswordEncoder;<br><br>@Configuration<br>public class PasswordConfig {<br><br>    @Bean<br>    public PasswordEncoder passwordEncoder() {<br>        return new BCryptPasswordEncoder();<br>    }<br><br>}</pre><blockquote><strong><em>Explanation:</em></strong><em><br> Defines a </em><strong><em>BCrypt password encoder</em></strong><em> bean for encrypting passwords before saving to MongoDB.</em></blockquote><h3>13. Security Configuration</h3><pre>package com.mathesh.book_store.config;<br><br><br>import com.mathesh.book_store.filter.JwtAuthenticationFilter;<br>import org.springframework.context.annotation.Bean;<br>import org.springframework.context.annotation.Configuration;<br>import org.springframework.security.authentication.AuthenticationManager;<br>import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;<br>import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;<br>import org.springframework.security.config.annotation.web.builders.HttpSecurity;<br>import org.springframework.security.web.SecurityFilterChain;<br>import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;<br><br>@Configuration<br>@EnableMethodSecurity<br>public class SecurityConfig {<br><br>    private final JwtAuthenticationFilter jwtFilter;<br><br>    public SecurityConfig(JwtAuthenticationFilter jwtFilter) {<br>        this.jwtFilter = jwtFilter;<br>    }<br><br>    @Bean<br>    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {<br>        http<br>                .csrf(csrf -&gt; csrf.disable())<br>                .authorizeHttpRequests(auth -&gt; auth<br>                        .requestMatchers(&quot;/auth/**&quot;).permitAll()<br>                        .requestMatchers(&quot;/book-store/**&quot;).authenticated()<br>                )<br>                .addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class);<br><br>        return http.build();<br>    }<br><br>    @Bean<br>    public AuthenticationManager authManager(AuthenticationConfiguration config) throws Exception {<br>        return config.getAuthenticationManager();<br>    }<br>}</pre><blockquote><strong><em>Explanation:</em></strong><em><br> Configures Spring Security to:</em></blockquote><ul><li>Permit all requests to /auth/** (login endpoints).</li><li>Protect /book-store/** endpoints with authentication.</li><li>Add JwtAuthenticationFilter to validate JWT tokens for every request.</li></ul><h3>14. User Repository</h3><pre>package com.mathesh.book_store.repository;<br>import com.mathesh.book_store.entity.User;<br>import org.springframework.data.mongodb.repository.MongoRepository;<br>import java.util.Optional;<br>public interface UserRepository extends MongoRepository&lt;User, String&gt; {<br>    Optional&lt;User&gt; findByUsername(String username);<br>}</pre><blockquote><strong><em>Explanation:</em></strong><em><br> Repository to fetch users from MongoDB. Supports finding users by </em><em>username for authentication.</em></blockquote><h3>15. Custom User Details Service</h3><pre>package com.mathesh.book_store.service;<br><br>import com.mathesh.book_store.entity.User;<br>import com.mathesh.book_store.repository.UserRepository;<br>import org.springframework.security.core.userdetails.UserDetails;<br>import org.springframework.security.core.userdetails.UserDetailsService;<br>import org.springframework.security.core.userdetails.UsernameNotFoundException;<br>import org.springframework.stereotype.Service;<br><br>@Service<br>public class CustomUserDetailsService implements UserDetailsService {<br><br>    private final UserRepository repo;<br><br>    public CustomUserDetailsService(UserRepository repo) {<br>        this.repo = repo;<br>    }<br><br>    @Override<br>    public UserDetails loadUserByUsername(String username) {<br><br>        User user = repo.findByUsername(username)<br>                .orElseThrow(() -&gt; new UsernameNotFoundException(&quot;User not found&quot;));<br><br>        return org.springframework.security.core.userdetails.User<br>                .withUsername(user.getUsername())<br>                .password(user.getPassword())<br>                .authorities(<br>                        user.getRoles().stream()<br>                                .map(Enum::name)<br>                                .toArray(String[]::new)<br>                )<br>                .build();<br>    }<br>}<br><br></pre><blockquote><strong><em>Explanation:</em></strong><em><br> Custom service that loads user details from MongoDB.<br> Spring Security uses this for authentication and role checks.</em></blockquote><h3>16. JWT Authentication Filter</h3><pre>package com.mathesh.book_store.filter;<br><br><br>import com.mathesh.book_store.config.JwtUtils;<br>import com.mathesh.book_store.service.CustomUserDetailsService;<br>import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;<br>import org.springframework.security.core.context.SecurityContextHolder;<br>import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;<br>import org.springframework.stereotype.Component;<br>import org.springframework.web.filter.OncePerRequestFilter;<br><br>import jakarta.servlet.FilterChain;<br>import jakarta.servlet.ServletException;<br>import jakarta.servlet.http.HttpServletRequest;<br>import jakarta.servlet.http.HttpServletResponse;<br>import java.io.IOException;<br><br>@Component<br>public class JwtAuthenticationFilter extends OncePerRequestFilter {<br><br>    private final JwtUtils jwtUtils;<br>    private final CustomUserDetailsService userDetailsService;<br><br>    public JwtAuthenticationFilter(JwtUtils jwtUtils, CustomUserDetailsService userDetailsService) {<br>        this.jwtUtils = jwtUtils;<br>        this.userDetailsService = userDetailsService;<br>    }<br><br>    @Override<br>    protected void doFilterInternal(HttpServletRequest request,<br>                                    HttpServletResponse response,<br>                                    FilterChain filterChain) throws ServletException, IOException {<br><br>        String header = request.getHeader(&quot;Authorization&quot;);<br>        String token = null;<br>        String username = null;<br><br>        if (header != null &amp;&amp; header.startsWith(&quot;Bearer &quot;)) {<br>            token = header.substring(7);<br>            if (jwtUtils.validateJwtToken(token)) {<br>                username = jwtUtils.getUsernameFromJwt(token);<br>            }<br>        }<br><br>        if (username != null &amp;&amp; SecurityContextHolder.getContext().getAuthentication() == null) {<br>            var userDetails = userDetailsService.loadUserByUsername(username);<br>            var authToken = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());<br>            authToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));<br>            SecurityContextHolder.getContext().setAuthentication(authToken);<br>        }<br><br>        filterChain.doFilter(request, response);<br>    }<br>}<br><br></pre><blockquote><strong><em>Explanation:</em></strong><em><br> Intercepts every HTTP request, extracts the JWT token, validates it, and sets authentication in the security context so Spring Security can enforce role-based access.</em></blockquote><h3>17. Auth Controller</h3><pre>package com.mathesh.book_store.controller;<br><br><br>import com.mathesh.book_store.dto.AuthResponse;<br>import com.mathesh.book_store.dto.LoginRequest;<br>import com.mathesh.book_store.config.JwtUtils;<br>import org.springframework.security.authentication.AuthenticationManager;<br>import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;<br>import org.springframework.security.core.Authentication;<br>import org.springframework.security.core.userdetails.UserDetails;<br>import org.springframework.web.bind.annotation.*;<br><br>@RestController<br>@RequestMapping(&quot;/auth&quot;)<br>public class AuthController {<br><br>    private final AuthenticationManager authManager;<br>    private final JwtUtils jwtUtils;<br><br>    public AuthController(AuthenticationManager authManager, JwtUtils jwtUtils) {<br>        this.authManager = authManager;<br>        this.jwtUtils = jwtUtils;<br>    }<br><br>    @PostMapping(&quot;/login&quot;)<br>    public AuthResponse login(@RequestBody LoginRequest request) {<br>        Authentication authentication = authManager.authenticate(<br>                new UsernamePasswordAuthenticationToken(request.getUsername(), request.getPassword())<br>        );<br><br>        UserDetails userDetails = (UserDetails) authentication.getPrincipal();<br>        String token = jwtUtils.generateJwtToken(userDetails.getUsername());<br><br>        return new AuthResponse(token);<br>    }<br>}</pre><blockquote><strong><em>Explanation:</em></strong><em><br> Login endpoint authenticates a user and returns a JWT token.<br> The token is then used in the </em><em>Authorization header for accessing protected endpoints.</em></blockquote><h3>18. Data Loader for Initial Users</h3><pre>package com.mathesh.book_store.util;<br><br>import com.mathesh.book_store.entity.Role;<br>import com.mathesh.book_store.entity.User;<br>import com.mathesh.book_store.repository.UserRepository;<br>import org.springframework.boot.CommandLineRunner;<br>import org.springframework.security.crypto.password.PasswordEncoder;<br>import org.springframework.stereotype.Component;<br><br>import java.util.Set;<br><br>@Component<br>public class DataLoader implements CommandLineRunner {<br><br>    private final UserRepository repo;<br>    private final PasswordEncoder encoder;<br><br>    public DataLoader(UserRepository repo, PasswordEncoder encoder) {<br>        this.repo = repo;<br>        this.encoder = encoder;<br>    }<br><br>    @Override<br>    public void run(String... args) {<br>        // Create ADMIN if not exists<br>        if (repo.findByUsername(&quot;admin&quot;).isEmpty()) {<br>            User admin = new User();<br>            admin.setUsername(&quot;admin&quot;);<br>            admin.setPassword(encoder.encode(&quot;admin123&quot;));<br>            admin.setRoles(Set.of(Role.ROLE_ADMIN));<br>            repo.save(admin);<br>            System.out.println(&quot; Admin user created: admin/admin123&quot;);<br>        } else {<br>            System.out.println(&quot; Admin user already exists&quot;);<br>        }<br><br>        // Create normal USER if not exists<br>        if (repo.findByUsername(&quot;user&quot;).isEmpty()) {<br>            User user = new User();<br>            user.setUsername(&quot;user&quot;);<br>            user.setPassword(encoder.encode(&quot;user123&quot;));<br>            user.setRoles(Set.of(Role.ROLE_USER));<br>            repo.save(user);<br>            System.out.println(&quot; Normal user created: user/user123&quot;);<br>        } else {<br>            System.out.println(&quot; Normal user already exists&quot;);<br>        }<br>    }<br>}</pre><blockquote><strong><em>Explanation:</em></strong><em><br> Pre-loads a default </em><em>ADMIN and </em><em>USER into the database so you can test authentication and role-based access immediately.</em></blockquote><h3>Testing the Role-Based JWT Authentication</h3><p>With this setup:</p><ul><li>Users can login via /auth/login and get a <strong>JWT token</strong>.</li><li>Add Authorization: Bearer &lt;token&gt; header to access /book-store/** endpoints.</li><li>Role-based access is enforced using @PreAuthorize.</li></ul><h3>Steps to Test in Postman</h3><p><strong>Login as Admin</strong></p><ul><li>Endpoint: POST /auth/login</li><li>Body: { “username”: “admin”, “password”: “admin123” }</li></ul><p><strong>Login as Admin</strong></p><ul><li>Endpoint: POST /auth/login</li><li>Body: { “username”: “user”, “password”: “user123” }</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1H51_fZStw-y0_fX28uImw.gif" /><figcaption>Get the token</figcaption></figure><p>now we can use that user token for get all books</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h6JlKDdlRTpYwtIdst8QwQ.gif" /><figcaption>Get all book with user token &amp; without token</figcaption></figure><p>Now, try using the user token to create a book (admin-only access).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6EJp9RXY5cI5p33VPb0tBg.gif" /><figcaption>create book with user token, it will fail</figcaption></figure><p>Now, try creating a book using the admin token — it should work successfully.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ThQ0eeBSUGuICIp1pUGZ-Q.gif" /><figcaption>create book with admin token</figcaption></figure><p>From these tests, we can confirm that <strong>role-based authentication is working perfectly</strong>.</p><p>You can check out the full code on <strong>GitHub</strong>: <a href="https://github.com/matheshyogeswaran/book-store/tree/JwtAuth">Book Store JWT Auth</a></p><p>If you have any questions, feel free to <strong>leave a comment below</strong> or <strong>connect with me on </strong><a href="https://www.linkedin.com/in/mathesh-yogeswaran/"><strong>LinkedIn</strong></a>.</p><p>✨ Happy coding, and enjoy building secure Spring Boot applications with JWT!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=66197ff76c01" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting Started with CRUD Operations in Spring Boot and MongoDB: A Beginner’s Guide]]></title>
            <link>https://matheshyogeswaran.medium.com/getting-started-with-crud-operations-in-spring-boot-and-mongodb-a-beginners-guide-0a4fbb8bac41?source=rss-505ef1b70e94------2</link>
            <guid isPermaLink="false">https://medium.com/p/0a4fbb8bac41</guid>
            <category><![CDATA[crud]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[beginner]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[mongodb]]></category>
            <dc:creator><![CDATA[Matheshyogeswaran]]></dc:creator>
            <pubDate>Thu, 29 Jan 2026 20:33:06 GMT</pubDate>
            <atom:updated>2026-01-29T20:33:06.225Z</atom:updated>
            <content:encoded><![CDATA[<p>Welcome to this beginner-friendly tutorial, Today, we’ll explore <strong>creating, reading, updating, and deleting (CRUD) data</strong> in a Spring Boot application using MongoDB. By the end, you’ll have a fully working REST API and a clear understanding of <strong>best practices in project organization</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Tb_7emYqvYQSRemp-Zi0fQ.png" /><figcaption>Artwork by <a href="https://medium.com/@matheshyogeswaran">Author</a></figcaption></figure><h3>Step 1: Set Up Your Spring Boot Project</h3><p>Go to <a href="https://start.spring.io/"><strong>Spring Initializr</strong></a>.</p><p>Choose:</p><ul><li><strong>Project</strong>: Maven</li><li><strong>Language</strong>: Java</li><li><strong>Java</strong>: 25</li></ul><p>Add dependencies:</p><ul><li><strong>Spring Web</strong></li><li><strong>Spring Data MongoDB</strong></li></ul><p>Click <strong>Generate</strong>, download, unzip, and open the project in <strong>IntelliJ IDEA</strong> or your favorite IDE.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yYYwB7plcyWWbz3Cf-ZT0Q.png" /><figcaption>Creating Spring Boot Project in Spring Initializr</figcaption></figure><h3>Step 2: Configure MongoDB</h3><p>Since we’re using <strong>MongoDB</strong>, we need to configure Spring Boot to connect to it.</p><p>application.properties</p><pre>spring:<br>  data:<br>    mongodb:<br>      uri: mongodb://localhost:27017/studentdb<br>server:<br>  port: 8080</pre><p><strong>Explanation:</strong></p><ul><li>studentdb is the MongoDB database. If it doesn’t exist, MongoDB will create it automatically.</li><li>We’re using <strong>localhost</strong> for development. In production, you’d use a MongoDB Atlas connection string.</li></ul><h3>Step 3: Organize Your Project</h3><p>Good structure = maintainable code. Recommended package structure:</p><pre>src/main/java/com/example/mongodbcrud<br> ├── controller<br> ├── model<br> ├── repository<br> ├── service<br> └── MongodbCrudApplication.java</pre><p><strong>Explanation of layers:</strong></p><ul><li><strong>Controller</strong>: Handles HTTP requests and responses.</li><li><strong>Model</strong>: Defines the data structure stored in MongoDB.</li><li><strong>Repository</strong>: Interfaces directly with the database.</li><li><strong>Service</strong>: Contains business logic between controller and repository.</li></ul><h3>Step 4: Create the Data Model</h3><p>Create a Student class in model package:</p><pre>package com.basic.crud.model;<br><br>import org.springframework.data.annotation.Id;<br>import org.springframework.data.mongodb.core.mapping.Document;<br><br>@Document(collection = &quot;students&quot;)<br>public class Student {<br><br>    @Id<br>    private String id; // MongoDB ID<br><br>    private String name;<br>    private String email;<br>    private int age;<br><br>    // Getters and setters<br>    public String getId() { return id; }<br>    public void setId(String id) { this.id = id; }<br>    public String getName() { return name; }<br>    public void setName(String name) { this.name = name; }<br>    public String getEmail() { return email; }<br>    public void setEmail(String email) { this.email = email; }<br>    public int getAge() { return age; }<br>    public void setAge(int age) { this.age = age; }<br>}</pre><p><strong>Explanation:</strong></p><ul><li>@Document marks this class as a MongoDB collection.</li><li>@Id marks the primary key field.</li><li>MongoDB auto-generates IDs for String type.</li></ul><h3>Step 5: Create the Repository</h3><p>repository/StudentRepository.java</p><pre>package com.basic.crud.repository;<br><br>import com.basic.crud.model.Student;<br>import org.springframework.data.mongodb.repository.MongoRepository;<br><br>public interface StudentRepository extends MongoRepository&lt;Student, String&gt; {<br>}</pre><p><strong>Why this is great:</strong><br> No implementation needed — Spring Data MongoDB auto-generates <strong>save, findAll, findById, deleteById</strong>.</p><h3>Step 6: Create the Service Layer</h3><p>service/StudentService.java</p><pre>package com.basic.crud.service;<br><br><br>import com.basic.crud.model.Student;<br>import com.basic.crud.repository.StudentRepository;<br>import org.springframework.stereotype.Service;<br><br>import java.util.List;<br><br>@Service<br>public class StudentService {<br><br>    private final StudentRepository repository;<br><br>    public StudentService(StudentRepository repository) {<br>        this.repository = repository;<br>    }<br><br>    public Student create(Student student) {<br>        return repository.save(student);<br>    }<br><br>    public List&lt;Student&gt; getAll() {<br>        return repository.findAll();<br>    }<br><br>    public Student getById(String id) {<br>        return repository.findById(id)<br>                .orElseThrow(() -&gt; new RuntimeException(&quot;Student not found&quot;));<br>    }<br><br>    public Student update(String id, Student student) {<br>        Student existing = getById(id);<br>        existing.setName(student.getName());<br>        existing.setEmail(student.getEmail());<br>        existing.setAge(student.getAge());<br>        return repository.save(existing);<br>    }<br><br>    public void delete(String id) {<br>        repository.deleteById(id);<br>    }<br>}<br><br></pre><p><strong>Explanation:</strong></p><ul><li>Controller will call <strong>service</strong> for business logic.</li><li>Keeps Controller clean.</li><li>Makes testing easier.</li></ul><h3>Step 7: Create the Controller</h3><p>controller/StudentController.java</p><pre>package com.basic.crud.controller;<br><br><br>import com.basic.crud.model.Student;<br>import com.basic.crud.service.StudentService;<br>import org.springframework.web.bind.annotation.*;<br><br>import java.util.List;<br><br>@RestController<br>@RequestMapping(&quot;/api/students&quot;)<br>public class StudentController {<br><br>    private final StudentService service;<br><br>    public StudentController(StudentService service) {<br>        this.service = service;<br>    }<br><br>    @PostMapping<br>    public Student create(@RequestBody Student student) {<br>        return service.create(student);<br>    }<br><br>    @GetMapping<br>    public List&lt;Student&gt; getAll() {<br>        return service.getAll();<br>    }<br><br>    @GetMapping(&quot;/{id}&quot;)<br>    public Student getById(@PathVariable String id) {<br>        return service.getById(id);<br>    }<br><br>    @PutMapping(&quot;/{id}&quot;)<br>    public Student update(@PathVariable String id, @RequestBody Student student) {<br>        return service.update(id, student);<br>    }<br><br>    @DeleteMapping(&quot;/{id}&quot;)<br>    public void delete(@PathVariable String id) {<br>        service.delete(id);<br>    }<br>}<br><br></pre><p><strong>Explanation:</strong></p><ul><li>@RestController → JSON responses automatically</li><li>@RequestMapping(&quot;/api/students&quot;) → API base URL</li><li>Methods correspond to CRUD operations</li></ul><p>Step 8: Run Your Application</p><h3>Step 8: Test Your API</h3><p>Run Your Application after test using Postman.</p><p>Create Student:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z4PxG2uGizBiuk9HzY007w.png" /><figcaption>Creating a Student in Postman</figcaption></figure><p>Get All Students:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q-hvr4KCNuLZ0lXIsfRD2g.png" /><figcaption>Get All students</figcaption></figure><p>Update Student:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*65dfGnKXiZqZR_Ji8FXKrw.png" /><figcaption>Update Student</figcaption></figure><p>Delete Student:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ksw4SkLXBp-4QJBaBQkqcw.png" /><figcaption>Delete a student</figcaption></figure><h3>Conclusion</h3><p>You now have a <strong>full Spring Boot + MongoDB CRUD application,</strong><br> You learned:</p><ul><li>Project structure</li><li>MongoDB integration</li><li>Repository, Service, Controller separation</li><li>REST API endpoints</li></ul><p>To access the complete code for this tutorial, please visit the <a href="https://github.com/matheshyogeswaran/crud-springboot-mongodb.git">GitHub</a> repository. If you’d like to connect, feel free to find me on <a href="https://www.linkedin.com/in/mathesh-yogeswaran/">LinkedIn</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0a4fbb8bac41" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I Uploaded a New AAB File After Losing My Keystore]]></title>
            <link>https://blog.stackademic.com/how-i-uploaded-a-new-aab-file-after-losing-my-keystore-6cce06760fa8?source=rss-505ef1b70e94------2</link>
            <guid isPermaLink="false">https://medium.com/p/6cce06760fa8</guid>
            <category><![CDATA[google-play-store]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[keystore]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[androiddev]]></category>
            <dc:creator><![CDATA[Matheshyogeswaran]]></dc:creator>
            <pubDate>Tue, 09 Sep 2025 08:56:17 GMT</pubDate>
            <atom:updated>2025-09-10T09:13:23.933Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello everyone, today I want to share one of the scariest moments I’ve faced as an Android developer — losing my keystore file.</p><p>Without the keystore, you can’t sign your app, which means you can’t upload updates to the Google Play Store. Basically, your app is stuck forever.</p><p>But thankfully, because I had enabled Google Play App Signing, I was able to recover and successfully upload a new AAB file.</p><p>Here’s exactly how I did it step by step.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FzmOpBcZ07teIfPbW6kcjg.png" /><figcaption>Artwork By <a href="https://medium.com/@matheshyogeswaran">Author</a></figcaption></figure><h3>🔑 Why the Keystore Matters</h3><ul><li>The keystore is used to <strong>sign your APK/AAB builds</strong>.</li><li>Every update must be signed with the <strong>same key</strong>.</li><li>If the keystore is lost, <strong>Google Play will reject your new uploads</strong>.</li></ul><p>Normally, this would be the end of the road. But with <strong>Google Play App Signing</strong>, there’s still a way forward.Google Play App Signing to the Rescue</p><h3>Google Play App Signing to the Rescue</h3><p>When you opt into Google Play App Signing:</p><ul><li>Google keeps your <strong>app signing key</strong> safe on their servers.</li><li>You only need your <strong>upload key</strong>, which can be reset if lost.</li></ul><p>This was my saving grace. Google handled the heavy lifting and ensured users never noticed a thing.</p><h3>📝 Step-by-Step Guide</h3><h3>1. Check App Integrity in Play Console</h3><ul><li>Go to Google Play Console.</li><li>Select your app → <strong>Setup → App Integrity</strong>.</li><li>Here you’ll see two keys:</li><li><strong>App signing key (Google’s copy)</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oznKgGgvMmAiv-a9azcGnA.png" /><figcaption><strong>App signing key</strong></figcaption></figure><ul><li><strong>Upload key (your copy, the one you lost).</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3YaH-8TFib74HvvjHr0BDA.png" /><figcaption><strong>Upload key (your copy, the one you lost).</strong></figcaption></figure><h3>2. Contact Google Support to Reset Upload Key</h3><ul><li>Tell them you’ve lost your keystore and request an <strong>upload key reset</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*umXlcAAg6b9Iuiv2yO38kA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uXOiL80G8acp8PlK5k1BaA.png" /></figure><h3>3. Generate a New Keystore</h3><p>On your local machine, generate a new keystore with this command:</p><pre>keytool -genkeypair -alias upload-key \<br>  -keyalg RSA -keysize 2048 -validity 10000 \<br>  -keystore upload-keystore.jks</pre><p>👉 Choose a strong password and back it up this time.</p><h3>4. Export a Certificate</h3><p>Now export the certificate from the keystore to share with Google:</p><pre>keytool -export -rfc -alias upload-key \<br>  -file upload_certificate.pem \<br>  -keystore upload-keystore.jks</pre><p>This .pem file is what Google needs.</p><ul><li>They will replace your old upload key with the new one.</li></ul><h3>6. Build &amp; Upload Your AAB</h3><p>Once Google confirms the reset</p><ul><li>Build your AAB with the new keystore.</li><li>Upload it in Play Console.</li><li>Google will re-sign it with the original app signing key, so your users can update seamlessly.</li></ul><h3>If You Don’t Have Play App Signing</h3><p>Unfortunately, if you never opted into Google Play App Signing, there’s no way to update your existing app after losing the keystore. The only option is to publish a <strong>new app with a new package name</strong>.</p><p>I hope this guide helps if you ever find yourself in the same situation.<br> If you’ve been through something similar, I’d love to hear how you handled it — drop a comment below.</p><p>And if you found this useful, don’t forget to connect with me on <a href="https://www.linkedin.com/in/mathesh-yogeswaran/">LinkedIn</a>.</p><h3>A message from our Founder</h3><p><strong>Hey, </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>Sunil</strong></a><strong> here.</strong> I wanted to take a moment to thank you for reading until the end and for being a part of this community.</p><p>Did you know that our team run these publications as a volunteer effort to over 3.5m monthly readers? <strong>We don’t receive any funding, we do this to support the community. ❤️</strong></p><p>If you want to show some love, please take a moment to <strong>follow me on </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>LinkedIn</strong></a><strong>, </strong><a href="https://tiktok.com/@messyfounder"><strong>TikTok</strong></a>, <a href="https://instagram.com/sunilsandhu"><strong>Instagram</strong></a>. You can also subscribe to our <a href="https://newsletter.plainenglish.io/"><strong>weekly newsletter</strong></a>.</p><p>And before you go, don’t forget to <strong>clap</strong> and <strong>follow</strong> the writer️!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6cce06760fa8" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/how-i-uploaded-a-new-aab-file-after-losing-my-keystore-6cce06760fa8">How I Uploaded a New AAB File After Losing My Keystore</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Securing APIs with Amazon Cognito Across Multiple AWS Environments]]></title>
            <link>https://aws.plainenglish.io/securing-apis-with-amazon-cognito-across-multiple-aws-environments-65b77953cfdc?source=rss-505ef1b70e94------2</link>
            <guid isPermaLink="false">https://medium.com/p/65b77953cfdc</guid>
            <category><![CDATA[aws-cognito]]></category>
            <category><![CDATA[authorization]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[authentication]]></category>
            <dc:creator><![CDATA[Matheshyogeswaran]]></dc:creator>
            <pubDate>Tue, 26 Aug 2025 04:07:43 GMT</pubDate>
            <atom:updated>2025-08-31T13:19:24.125Z</atom:updated>
            <content:encoded><![CDATA[<p>When building mobile or web applications, it’s common to end up with multiple APIs deployed across different AWS environments. That works fine for scaling teams and infrastructure ,but things get messy when you want <strong>centralized authentication</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U8RWeV09G4kF4w1y_f_HDA.png" /><figcaption>ArtWork By <a href="https://medium.com/@matheshyogeswaran">Author</a></figcaption></figure><p>Recently, I worked on a project where several APIs lived in one AWS environment, another API lived in a separate environment, and the <strong>Cognito User Pool</strong> was in yet another. The goal was secure all APIs with a single authentication mechanism, without moving resources around.</p><p>Here’s how we made it work.</p><h3>The Setup</h3><ul><li><strong>Several APIs</strong> → Hosted in <strong>AWS Environment A</strong></li><li><strong>Another API</strong> → Hosted in <strong>AWS Environment B</strong></li><li><strong>Amazon Cognito User Pool</strong> → Lives in <strong>AWS Environment C</strong></li></ul><p>We needed all these APIs to require authentication via the Cognito User Pool in Environment C.</p><h3>The Requirements</h3><ol><li>Cognito User Pool must remain in <strong>Environment C</strong>.</li><li>All APIs must sit behind <strong>API Gateway</strong>.</li><li>Ideally, everything should be in the same AWS region (to avoid cross-region token validation issues). If not, make sure JWT validation works across regions.</li><li>Clients authenticate via Cognito → receive a JWT token → use that token to call any API.</li></ol><h3>Step 1: Configure API Gateway Authorizer</h3><ul><li>In <strong>API Gateway (Environment A)</strong>, open the API you want to secure.</li><li>Navigate to <strong>Authorizers</strong> → <strong>Create New Authorizer</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S2xn0lVGj_SdA-AggLy94Q.png" /><figcaption>Create New Authorizer</figcaption></figure><ul><li>Choose <strong>Cognito</strong> as the type.</li></ul><h3>Step 2: Link the Cognito User Pool</h3><ul><li>In <strong>Cognito (Environment C)</strong>, open your User Pool → copy the <strong>Pool ARN</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7w9JsbQQAqYox81EftD4HA.png" /><figcaption>copy the Pool ARN</figcaption></figure><ul><li>Back in API Gateway, paste the ARN into the Authorizer configuration.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*63aluy3Z0-bfg7StGKiPxA.png" /><figcaption>Authorizer configuration</figcaption></figure><h3>Step 3: Attach Authorizer to API Methods</h3><ul><li>Go to the resource methods.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pLKkfAew-rxYbBzi228Z6g.png" /><figcaption>resource methods</figcaption></figure><ul><li>Under <strong>Authorization</strong>, select the Cognito authorizer you just created.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EWzGDZ9KzLV8bd4QXR3FPw.png" /><figcaption>select the Cognito authorizer you just created</figcaption></figure><ul><li>Deploy the changes.</li></ul><h3>Step 4: Test It</h3><p>Two simple checks validated the setup:</p><p><strong>Test 1: No Token</strong></p><ul><li>Request without Authorization header.</li><li>Result: 401 Unauthorized</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xb-XpAbzhbnsTKNuD2zl4w.png" /><figcaption>Request without Authorization header</figcaption></figure><p><strong>Test 2: Valid Token</strong></p><ul><li>Request with a valid JWT from Cognito.</li><li>Result: 200 OK expected data</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JsnAoHezv33JwbcOGXLW8Q.png" /><figcaption>Request with a valid JWT from Cognito</figcaption></figure><h3>Why This Works</h3><ul><li><strong>Centralized user management</strong> with one Cognito pool.</li><li><strong>Secure APIs across environments</strong> without custom auth logic.</li><li><strong>Scalable model</strong>: new APIs can easily plug into the same pool.</li></ul><p>As long as your environments are in the same AWS region ,or your services can verify cross-region tokens — this setup just works.</p><p>In summary, securing APIs across multiple AWS environments with a centralized Cognito User Pool is both achievable and scalable. By leveraging API Gateway Cognito Authorizers, you eliminate the need for custom JWT validation, simplify authentication, and maintain a consistent security model across all services. This setup not only streamlines client interactions but also future-proofs your architecture as you add new APIs.</p><p>If you’ve faced similar challenges securing APIs across different AWS environments, I’d love to hear how you approached them. Feel free to share your experience in the comments , and if you’d like to continue the conversation, connect with me on <a href="https://www.linkedin.com/in/mathesh-yogeswaran/">LinkedIn</a>.</p><h3>A message from our Founder</h3><p><strong>Hey, </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>Sunil</strong></a><strong> here.</strong> I wanted to take a moment to thank you for reading until the end and for being a part of this community.</p><p>Did you know that our team run these publications as a volunteer effort to over 3.5m monthly readers? <strong>We don’t receive any funding, we do this to support the community. ❤️</strong></p><p>If you want to show some love, please take a moment to <strong>follow me on </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>LinkedIn</strong></a><strong>, </strong><a href="https://tiktok.com/@messyfounder"><strong>TikTok</strong></a>, <a href="https://instagram.com/sunilsandhu"><strong>Instagram</strong></a>. You can also subscribe to our <a href="https://newsletter.plainenglish.io/"><strong>weekly newsletter</strong></a>.</p><p>And before you go, don’t forget to <strong>clap</strong> and <strong>follow</strong> the writer️!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=65b77953cfdc" width="1" height="1" alt=""><hr><p><a href="https://aws.plainenglish.io/securing-apis-with-amazon-cognito-across-multiple-aws-environments-65b77953cfdc">Securing APIs with Amazon Cognito Across Multiple AWS Environments</a> was originally published in <a href="https://aws.plainenglish.io/">AWS in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AWS Cognito Tokens]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://aws.plainenglish.io/aws-cognito-tokens-3b89313b5859?source=rss-505ef1b70e94------2"><img src="https://cdn-images-1.medium.com/max/1920/1*8GKMqDWRHgUsD0jB7lGk8A.png" width="1920"></a></p><p class="medium-feed-snippet">When you authenticate with Amazon Cognito, it returns three tokens
1.ID token
2.Access token
3.Refresh token</p><p class="medium-feed-link"><a href="https://aws.plainenglish.io/aws-cognito-tokens-3b89313b5859?source=rss-505ef1b70e94------2">Continue reading on AWS in Plain English »</a></p></div>]]></description>
            <link>https://aws.plainenglish.io/aws-cognito-tokens-3b89313b5859?source=rss-505ef1b70e94------2</link>
            <guid isPermaLink="false">https://medium.com/p/3b89313b5859</guid>
            <category><![CDATA[token]]></category>
            <category><![CDATA[aws-cognito]]></category>
            <category><![CDATA[jwt]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Matheshyogeswaran]]></dc:creator>
            <pubDate>Fri, 15 Aug 2025 12:03:52 GMT</pubDate>
            <atom:updated>2025-08-31T13:19:19.322Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Mastering Pagination in React: A Step-by-Step Guide for Machine Coding Round]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://javascript.plainenglish.io/mastering-pagination-in-react-a-step-by-step-guide-for-machine-coding-round-50d8e359947d?source=rss-505ef1b70e94------2"><img src="https://cdn-images-1.medium.com/max/1152/1*-l64M4Fgm2MQCyYn4VSIPA.gif" width="1152"></a></p><p class="medium-feed-snippet">Hello everyone! Today, we&#x2019;re going to explore a real-world machine coding interview in React.</p><p class="medium-feed-link"><a href="https://javascript.plainenglish.io/mastering-pagination-in-react-a-step-by-step-guide-for-machine-coding-round-50d8e359947d?source=rss-505ef1b70e94------2">Continue reading on JavaScript in Plain English »</a></p></div>]]></description>
            <link>https://javascript.plainenglish.io/mastering-pagination-in-react-a-step-by-step-guide-for-machine-coding-round-50d8e359947d?source=rss-505ef1b70e94------2</link>
            <guid isPermaLink="false">https://medium.com/p/50d8e359947d</guid>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[pagination]]></category>
            <category><![CDATA[interview-preparation]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Matheshyogeswaran]]></dc:creator>
            <pubDate>Mon, 10 Feb 2025 10:53:07 GMT</pubDate>
            <atom:updated>2025-02-17T01:34:20.706Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[React Native Navigation: When and Where to Use Each Method?]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://javascript.plainenglish.io/react-native-navigation-when-and-where-to-use-each-method-45764b7c144c?source=rss-505ef1b70e94------2"><img src="https://cdn-images-1.medium.com/max/1920/1*crIPN_rvR8xEtosPziZqdA.png" width="1920"></a></p><p class="medium-feed-snippet">Read this article without a paywall using this friend link!</p><p class="medium-feed-link"><a href="https://javascript.plainenglish.io/react-native-navigation-when-and-where-to-use-each-method-45764b7c144c?source=rss-505ef1b70e94------2">Continue reading on JavaScript in Plain English »</a></p></div>]]></description>
            <link>https://javascript.plainenglish.io/react-native-navigation-when-and-where-to-use-each-method-45764b7c144c?source=rss-505ef1b70e94------2</link>
            <guid isPermaLink="false">https://medium.com/p/45764b7c144c</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[best-practices]]></category>
            <category><![CDATA[navigation]]></category>
            <dc:creator><![CDATA[Matheshyogeswaran]]></dc:creator>
            <pubDate>Wed, 29 Jan 2025 15:50:40 GMT</pubDate>
            <atom:updated>2025-02-03T01:20:33.573Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Building a GIS-Powered Parking Management System with Streamlit]]></title>
            <link>https://matheshyogeswaran.medium.com/building-a-gis-powered-parking-management-system-with-streamlit-830b1884fc60?source=rss-505ef1b70e94------2</link>
            <guid isPermaLink="false">https://medium.com/p/830b1884fc60</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[folium]]></category>
            <category><![CDATA[geopandas]]></category>
            <category><![CDATA[parking-management]]></category>
            <category><![CDATA[streamlit]]></category>
            <dc:creator><![CDATA[Matheshyogeswaran]]></dc:creator>
            <pubDate>Tue, 14 Jan 2025 13:26:25 GMT</pubDate>
            <atom:updated>2025-01-14T13:26:25.235Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>GIS (Geographic Information Systems)</strong> enables countless possibilities for managing spatial data and building practical applications. In this blog, I’ll walk you through how I developed a <strong>parking management system</strong> for the <strong>University of Moratuwa</strong> using Python libraries such as <strong>Streamlit</strong>, <strong>GeoPandas</strong>, and <strong>Folium</strong>. The application combines real-time data visualization, interactivity, and spatial computations to provide a seamless user experience.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*DAJvSdFWTk8Wm4Z8aLK-cw.gif" /><figcaption>Demo Of Project</figcaption></figure><h3>What’s in this Article?</h3><ul><li><strong>The Problem and Motivation</strong></li><li><strong>Tech Stack Overview</strong></li><li><strong>Detailed Implementation Steps</strong></li><li><strong>Running the Application</strong></li><li><strong>Future Enhancements</strong></li></ul><h3>🛠 The Problem and Motivation</h3><p>Finding parking is a universal challenge, especially in busy university campuses like the <strong>University of Moratuwa</strong>. This project aims to simplify the process of locating available parking spaces near specific gates using real-time data visualization and interactive filters.</p><p>The goal:</p><ol><li>Allow users to select a university gate and visualize nearby parking slots.</li><li>Enable admins to update slot availability dynamically.</li><li>Provide real-time, GIS-driven spatial insights.</li></ol><h3>🚀 Tech Stack Overview</h3><h4>Python Libraries:</h4><ul><li><strong>Streamlit</strong>: For creating the web-based application.</li><li><strong>GeoPandas</strong>: For handling geospatial data.</li><li><strong>Shapely</strong>: For spatial computations.</li><li><strong>Folium</strong>: For interactive map rendering.</li><li><strong>Random</strong>: To simulate parking slot availability.</li></ul><h4>Other Tools:</h4><ul><li><strong>Google Maps</strong>: To extract gate and parking slot coordinates and save them as GeoJSON files.</li><li><strong>ngrok</strong>: To expose the local application to the web for testing and collaboration.</li></ul><h3>📂 Data Files for the Project</h3><p>The geospatial data used in this project, including <strong>gates</strong> and <strong>parking slots</strong>, is stored as GeoJSON files. You can download these files to replicate or enhance the project:</p><ul><li><strong>Gates Data</strong>: Contains the coordinates of all gates at the University of Moratuwa.</li><li><strong>Parking Slots Data</strong>: Contains the coordinates of parking slots and is used to compute availability and proximity to selected gates.</li></ul><p>👉 <a href="https://drive.google.com/drive/folders/1TQBl1CJHtu0SbBvnpQANN40e9xEzrgf0?usp=drive_link">Download the data files from Google Drive</a></p><p><strong>How to Use the Data:</strong></p><ol><li>Download the GeoJSON files from the link above.</li><li>Place them in the same directory as your Python script (e.g., app.py).</li><li>The application will automatically load and process the data for visualization and analysis.</li></ol><h3>📂 Implementation Steps</h3><h4>1. Set Up the Environment</h4><p>Install the required Python libraries:</p><pre>pip install geopandas shapely rasterio folium streamlit pyngrok</pre><h4>2. Load and Preprocess GeoJSON Data</h4><p>Using <strong>Google Maps</strong>, I extracted and saved the locations of university gates and parking slots in GeoJSON format. The data is loaded and preprocessed as follows:</p><pre># Load gates and parking slots<br>gates = gpd.read_file(&quot;gates.geojson&quot;).to_crs(&quot;EPSG:4326&quot;)  # Ensure WGS84 CRS<br>parking_slots = gpd.read_file(&quot;parking_slots.geojson&quot;).to_crs(&quot;EPSG:4326&quot;)<br># Add random availability status<br>parking_slots[&quot;availability&quot;] = [random.choice([0, 1]) for _ in range(len(parking_slots))]</pre><h4>3. Interactive Gate Selection</h4><p>Using <strong>Streamlit</strong>, users can select a gate. The app calculates distances (in meters and degrees) from the selected gate to each parking slot.</p><pre># Select a gate<br>selected_gate_id = st.selectbox(&quot;Select a Gate&quot;, options=gates.index, format_func=lambda x: f&quot;Gate {x + 1}&quot;)<br>selected_gate = gates.loc[selected_gate_id].geometry<br># Calculate distances in meters<br>parking_slots[&quot;distance_to_gate_meters&quot;] = parking_slots.to_crs(&quot;EPSG:3857&quot;).geometry.apply(<br>    lambda x: selected_gate.to_crs(&quot;EPSG:3857&quot;).distance(x)<br>)</pre><h4>4. Dynamic Buffer Filtering</h4><p>Users can filter parking slots within a user-defined radius (in meters) of the selected gate using a buffer zone.</p><pre>buffer_radius = st.slider(&quot;Buffer Radius (meters)&quot;, min_value=10, max_value=200, value=50)<br>buffer = selected_gate.buffer(buffer_radius / 111_139)  # Convert meters to degrees<br>nearby_slots = parking_slots[parking_slots.geometry.within(buffer)]</pre><h4>5. Update Slot Availability</h4><p>Admins can mark available slots as filled, and the app recalculates the nearest available slots dynamically.</p><pre># Mark slots as filled<br>available_slots = parking_slots[parking_slots[&quot;availability&quot;] == 1]<br>slot_to_fill = st.selectbox(&quot;Mark a Slot as Filled&quot;, available_slots.index)<br>if st.button(&quot;Update&quot;):<br>    parking_slots.loc[slot_to_fill, &quot;availability&quot;] = 0</pre><h4>6. Visualizing on a Map</h4><p>The app uses <strong>Folium</strong> to render gates, parking slots, and buffer zones on an interactive map.</p><pre>m = folium.Map(location=[selected_gate.y, selected_gate.x], zoom_start=17)<br><br># Add the selected gate<br>folium.Marker(location=[selected_gate.y, selected_gate.x], popup=&quot;Selected Gate&quot;).add_to(m)<br><br># Add parking slots<br>for _, slot in parking_slots.iterrows():<br>    color = &quot;blue&quot; if slot[&quot;availability&quot;] == 1 else &quot;red&quot;<br>    folium.CircleMarker(location=[slot.geometry.y, slot.geometry.x], color=color).add_to(m)<br><br># Display map in Streamlit<br>m.save(&quot;map.html&quot;)<br>st.components.v1.html(open(&quot;map.html&quot;, &quot;r&quot;).read(), height=600)</pre><h4>7. Deploy with ngrok</h4><p>Expose the app to the web for easy sharing and collaboration using <strong>ngrok</strong>. Add your <strong>ngrok auth token</strong> for authentication:</p><pre>ngrok config add-authtoken YOUR_AUTH_TOKEN</pre><h3>🖥 Running the Application</h3><ol><li>Save the code as app.py.</li><li>Run the application locally:</li></ol><pre>streamlit run app.py</pre><ol><li>Copy the ngrok URL (e.g., https://your-ngrok-url.ngrok-free.app) to share your app.</li></ol><h3>🌟 Features Summary</h3><ol><li><strong>Gate-based Slot Filtering</strong>: Select a gate to view nearby parking slots.</li><li><strong>Dynamic Updates</strong>: Mark slots as filled and get real-time updates.</li><li><strong>Buffer Visualization</strong>: Adjust the buffer radius to see slots within range.</li><li><strong>Interactive Maps</strong>: Visualize parking slots and availability with color coding.</li></ol><h3>Final Thoughts</h3><p>This GIS-based application showcases how Python and open-source tools can solve real-world problems. Whether managing parking at a university or scaling up to a city-wide system, GIS technology proves its immense value.</p><p>Try building your own GIS projects and let me know about your experience in the comments. 🚗💨</p><h3>Complete Code for the GIS-Powered Parking Management System</h3><p>Here is the full implementation of the parking management system discussed in the blog. Copy and paste this code into your google colab environment to get started.<br>make sure upload your both gate and parking geojson</p><pre>!pip install geopandas shapely rasterio folium streamlit<br><br>%%writefile app.py<br>import streamlit as st<br>import geopandas as gpd<br>import folium<br>from shapely.geometry import Point<br>import random<br><br># Load gates from the GeoJSON file<br>gates = gpd.read_file(&quot;gates.geojson&quot;)<br>gates = gates.to_crs(&quot;EPSG:4326&quot;)  # Ensure CRS is WGS84<br><br># Initialize parking slots in session state<br>if &quot;parking_slots&quot; not in st.session_state:<br>    # Load parking slots from GeoJSON file<br>    parking_slots = gpd.read_file(&quot;parking_slots.geojson&quot;)<br>    parking_slots = parking_slots.to_crs(&quot;EPSG:4326&quot;)  # Ensure CRS is WGS84<br><br>    # Add random availability status to parking slots<br>    parking_slots[&quot;availability&quot;] = [random.choice([0, 1]) for _ in range(len(parking_slots))]<br>    st.session_state[&quot;parking_slots&quot;] = parking_slots<br>else:<br>    parking_slots = st.session_state[&quot;parking_slots&quot;]<br><br># Streamlit App<br>st.title(&quot;University of Moratuwa Parking Availability&quot;)<br><br># Gate selection<br>gate_options = {index: f&quot;Gate {index+1}&quot; for index in gates.index}<br>selected_gate_id = st.selectbox(&quot;Select a Gate&quot;, options=list(gate_options.keys()), format_func=lambda x: gate_options[x])<br>selected_gate = gates.loc[selected_gate_id].geometry<br><br># Update distances in degrees (current implementation)<br>parking_slots[&quot;distance_to_gate_degrees&quot;] = parking_slots.geometry.apply(lambda x: selected_gate.distance(x))<br><br># Reproject parking_slots and selected_gate to a metric CRS (e.g., EPSG:3857 for meters)<br>parking_slots_metric = parking_slots.to_crs(&quot;EPSG:3857&quot;)<br>selected_gate_metric = gpd.GeoSeries([selected_gate], crs=&quot;EPSG:4326&quot;).to_crs(&quot;EPSG:3857&quot;).iloc[0]<br><br># Calculate distance in meters<br>parking_slots_metric[&quot;distance_to_gate_meters&quot;] = parking_slots_metric.geometry.apply(lambda x: selected_gate_metric.distance(x))<br><br># Copy the calculated distances in meters back to the original GeoDataFrame<br>parking_slots[&quot;distance_to_gate_meters&quot;] = parking_slots_metric[&quot;distance_to_gate_meters&quot;]<br><br># Display distances in both degrees and meters<br>st.subheader(&quot;Parking Slots with Distances (Degrees and Meters)&quot;)<br>st.write(parking_slots[[&quot;geometry&quot;, &quot;distance_to_gate_degrees&quot;, &quot;distance_to_gate_meters&quot;, &quot;availability&quot;]])<br><br># Filter for slots near the selected gate using a buffer<br>st.subheader(&quot;Nearby Slots Within Range&quot;)<br>buffer_radius = st.slider(&quot;Buffer Radius (meters)&quot;, min_value=10, max_value=200, value=50)<br>buffer = selected_gate.buffer(buffer_radius / 111_139)  # Convert meters to degrees<br>nearby_slots = parking_slots[parking_slots.geometry.within(buffer)]<br><br># Display slots within the buffer<br>if not nearby_slots.empty:<br>    st.write(&quot;Slots within the selected range:&quot;)<br>    st.write(nearby_slots[[&quot;geometry&quot;, &quot;distance_to_gate_degrees&quot;, &quot;availability&quot;]])<br>else:<br>    st.write(&quot;No slots found within the selected range.&quot;)<br><br># Allow admin to mark any available slot as filled<br>st.subheader(&quot;Mark Any Slot as Filled&quot;)<br>available_slots = parking_slots[parking_slots[&quot;availability&quot;] == 1].copy()<br>if not available_slots.empty:<br>    slot_to_fill = st.selectbox(<br>        &quot;Select a Slot to Mark as Filled&quot;,<br>        options=available_slots.index,<br>        format_func=lambda x: f&quot;Slot {x} (Distance: {available_slots.loc[x, &#39;distance_to_gate_degrees&#39;]:.2f} meters)&quot;,<br>    )<br>    if st.button(&quot;Mark as Filled&quot;):<br>        # Mark the selected slot as filled<br>        st.session_state[&quot;parking_slots&quot;].loc[slot_to_fill, &quot;availability&quot;] = 0<br>        st.success(f&quot;Slot {slot_to_fill} marked as filled.&quot;)<br>else:<br>    st.write(&quot;No available slots to mark as filled.&quot;)<br><br># Recalculate nearest available slots after marking a slot as filled<br>available_slots = st.session_state[&quot;parking_slots&quot;][st.session_state[&quot;parking_slots&quot;][&quot;availability&quot;] == 1].copy()<br>nearest_slots = available_slots.sort_values(&quot;distance_to_gate_degrees&quot;).head(5)<br><br># Display nearest available slots<br>st.subheader(&quot;Nearest Available Parking Slots&quot;)<br>if not nearest_slots.empty:<br>    st.write(nearest_slots[[&quot;geometry&quot;, &quot;distance_to_gate_degrees&quot;, &quot;availability&quot;]])<br>else:<br>    st.write(&quot;No available parking slots at the moment.&quot;)<br><br># Create a map<br>st.subheader(&quot;Map Visualization&quot;)<br>m = folium.Map(location=[selected_gate.y, selected_gate.x], zoom_start=17)<br><br># Add the selected gate to the map<br>folium.Marker(<br>    location=[selected_gate.y, selected_gate.x],<br>    popup=&quot;Selected Gate&quot;,<br>    icon=folium.Icon(color=&quot;green&quot;, icon=&quot;info-sign&quot;),<br>).add_to(m)<br><br># Add all parking slots to the map<br>for _, row in parking_slots.iterrows():<br>    color = &quot;red&quot; if row[&quot;availability&quot;] == 0 else &quot;blue&quot;<br>    folium.CircleMarker(<br>        location=[row.geometry.y, row.geometry.x],<br>        radius=5,<br>        color=color,<br>        fill=True,<br>        fill_color=color,<br>        popup=f&quot;Slot ID: {row.name}, Available: {&#39;Yes&#39; if row[&#39;availability&#39;] == 1 else &#39;No&#39;}&quot;,<br>    ).add_to(m)<br><br># Highlight nearest available slots<br>for _, row in nearest_slots.iterrows():<br>    folium.CircleMarker(<br>        location=[row.geometry.y, row.geometry.x],<br>        radius=8,<br>        color=&quot;yellow&quot;,<br>        fill=True,<br>        fill_color=&quot;yellow&quot;,<br>        popup=f&quot;Nearest Slot: {row.name}, Distance: {row[&#39;distance_to_gate_degrees&#39;]:.2f} meters&quot;,<br>    ).add_to(m)<br><br># Add buffer visualization<br>folium.Polygon(<br>    [[p[1], p[0]] for p in buffer.exterior.coords],<br>    color=&quot;green&quot;,<br>    fill=True,<br>    fill_opacity=0.1,<br>    popup=&quot;Buffer Area&quot;,<br>).add_to(m)<br><br># Save map to HTML and render in Streamlit<br>map_file = &quot;map.html&quot;<br>m.save(map_file)<br>st.components.v1.html(open(map_file, &quot;r&quot;).read(), height=600)<br><br># Add a legend for the colors<br>st.subheader(&quot;Map Legend&quot;)<br>st.markdown(&quot;&quot;&quot;<br>- 🟦 **Blue**: Available parking slots<br>- 🟥 **Red**: Filled parking slots<br>- 🟨 **Yellow**: Nearest available parking slots to the selected gate<br>- 🟩 **Green**: Selected gate and buffer area<br>&quot;&quot;&quot;)<br><br>!ngrok config add-authtoken #add your token<br><br>from pyngrok import ngrok<br>import threading<br>import os<br><br># Function to start the Streamlit app<br>def run_streamlit():<br>    os.system(&quot;streamlit run app.py&quot;)<br><br># Start Streamlit server in a thread<br>thread = threading.Thread(target=run_streamlit)<br>thread.start()<br><br># Expose Streamlit app via ngrok<br>public_url = ngrok.connect(8501)<br>print(f&quot;Public URL: {public_url}&quot;)</pre><p>If you have any questions, feel free to ask in the comments below or connect with me on <a href="https://www.linkedin.com/in/mathesh-yogeswaran/">LinkedIn</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=830b1884fc60" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Integrate Google AdMob with a React Native CLI App: Interstitial Ads with Example]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://javascript.plainenglish.io/integrate-google-admob-with-a-react-native-cli-app-interstitial-ads-with-example-1317717a7e84?source=rss-505ef1b70e94------2"><img src="https://cdn-images-1.medium.com/max/1920/1*qxc70ug5s3Suor0Wq9kRWw.png" width="1920"></a></p><p class="medium-feed-snippet">Hello everyone, today we are going to look at how we can integrate Google AdMob with a React Native CLI app. In this blog, we will create&#x2026;</p><p class="medium-feed-link"><a href="https://javascript.plainenglish.io/integrate-google-admob-with-a-react-native-cli-app-interstitial-ads-with-example-1317717a7e84?source=rss-505ef1b70e94------2">Continue reading on JavaScript in Plain English »</a></p></div>]]></description>
            <link>https://javascript.plainenglish.io/integrate-google-admob-with-a-react-native-cli-app-interstitial-ads-with-example-1317717a7e84?source=rss-505ef1b70e94------2</link>
            <guid isPermaLink="false">https://medium.com/p/1317717a7e84</guid>
            <category><![CDATA[react-native-development]]></category>
            <category><![CDATA[google-admob]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[react-native-app]]></category>
            <category><![CDATA[adsense]]></category>
            <dc:creator><![CDATA[Matheshyogeswaran]]></dc:creator>
            <pubDate>Sat, 19 Oct 2024 13:43:55 GMT</pubDate>
            <atom:updated>2024-10-23T03:30:28.989Z</atom:updated>
        </item>
    </channel>
</rss>