<?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 Olulode Olatunbosun on Medium]]></title>
        <description><![CDATA[Stories by Olulode Olatunbosun on Medium]]></description>
        <link>https://medium.com/@olaolulode?source=rss-f8cd0ba28757------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*cZp1Tnvzcd-MRzS-4XdFjQ.jpeg</url>
            <title>Stories by Olulode Olatunbosun on Medium</title>
            <link>https://medium.com/@olaolulode?source=rss-f8cd0ba28757------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 05:52:27 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@olaolulode/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[Uploading Files To Cloudflare R2 With Springboot]]></title>
            <link>https://olaolulode.medium.com/uploading-files-to-cloudflare-r2-with-springboot-cc180cc85540?source=rss-f8cd0ba28757------2</link>
            <guid isPermaLink="false">https://medium.com/p/cc180cc85540</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[file-upload]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[cloudflare-r2]]></category>
            <category><![CDATA[java-programming]]></category>
            <dc:creator><![CDATA[Olulode Olatunbosun]]></dc:creator>
            <pubDate>Thu, 21 Aug 2025 06:32:00 GMT</pubDate>
            <atom:updated>2025-08-21T06:32:00.937Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zN0YfMn6F9JRNOUM6Wc3LQ.jpeg" /></figure><p>Cloudflare R2 is a storage service designed to provide object storage that is cost-effective and performant, especially for large-scale applications. In this article, we will explore how to integrate Cloudflare R2 with a Spring Boot application to upload files. This guide is ideal for developers looking to leverage Cloudflare’s scalable storage solution with the simplicity of Spring Boot.</p><h4>Prerequisites</h4><p>Before we begin in, ensure you have the following prepared:</p><ul><li><a href="https://www.oracle.com/in/java/technologies/downloads/"><strong>Java Development Kit (JDK)</strong></a> installed.</li><li><a href="https://spring.io/guides/gs/spring-boot"><strong>Spring Boot</strong></a> setup in your development environment.</li><li><a href="https://maven.apache.org/install.html"><strong>Maven</strong></a><strong>/</strong><a href="https://gradle.org/install/"><strong>Gradle</strong></a> for dependency management.</li><li>An active <a href="https://www.cloudflare.com/developer-platform/r2/"><strong>Cloudflare account</strong></a> with access to R2.</li></ul><p><em>Basic understanding of Spring Boot and RESTful APIs will also be </em><a href="https://www.youtube.com/watch?v=UgX5lgv4uVM"><em>beneficial</em></a><em>.</em></p><p><strong>In this tutorial, you will learn the following</strong></p><ul><li>Setting Up Cloudflare R2</li><li>Setting up Spring Boot Project</li><li>Implementing the Cloudflare R2 with Springboot</li></ul><h4><strong>Setting Up Cloudflare R2</strong></h4><p>First log in to your Cloudflare dashboard, navigate to R2 section, follow the on screen instructions to create a new bucket. Then,generate an API token with required permissions to easily interact with the R2 bucket.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gRoVqFWXe2i2A2L5svLZ4w.jpeg" /><figcaption>Creating bucket and api token</figcaption></figure><h4>Spring Boot Project Setup</h4><p>To initiate the setup of a Spring Boot application, I typically utilize<a href="https://start.spring.io/"> Spring Initializr</a> to kickstart the project. Ensure that you include the following dependencies in your pom.xml or build.gradle file:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YDnvPS7XTFOSF_FFro3IlA.png" /><figcaption>spring initializr</figcaption></figure><pre><br>  &lt;!-- https://mvnrepository.com/artifact/software.amazon.awssdk/s3 --&gt;<br>  &lt;dependency&gt;<br>   &lt;groupId&gt;software.amazon.awssdk&lt;/groupId&gt;<br>   &lt;artifactId&gt;s3&lt;/artifactId&gt;<br>   &lt;version&gt;2.27.14&lt;/version&gt;<br> &lt;/dependency&gt;</pre><p>For Cloudflare R2, we use the Amazon S3 SDK<em> (software.amazon.awssdk:s3)</em> since R2 is fully compatible with the S3 API. This allows us to interact with R2 using the official and well-documented <a href="https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html">AWS SDK</a>, eliminating the need for a separate Cloudflare module. This approach also offers flexibility ensuring the application can work with any future storage provider that is supports the S3 API.</p><p>We also need to configure the application.yml file with the generated access-key, secret-key, and bucket-name. Here&#39;s what the configuration should look like in application.yml. Additionally, I&#39;ll provide the equivalent configuration for application.properties.</p><pre>application:<br>  cloudflare:<br>    r2:<br>        access-key: &lt;access-key&gt;<br>        secret-key: &lt;secret-key&gt;<br>        endpoint: &lt;endpoint&gt;<br>        bucket-name: &lt;bucket-name&gt;<br>        public-url: &lt;public-url&gt;</pre><pre>cloudflare.r2.access-key=&lt;your-access-key&gt;<br>cloudflare.r2.secret-key=&lt;your-secret-key&gt;<br>cloudflare.r2.bucket-name=&lt;your-bucket-name&gt;<br>cloudflare.r2.endpoint=&lt;your-endpoint&gt;<br>cloudflare.r2.public-url=&lt;your-public-url&gt;</pre><p>With the project setup complete, we can now proceed to integrate the SDK into our application.</p><h4>Implementing the Cloudflare R2 with Springboot</h4><p>After setting up Cloudflare and adding the necessary configurations, we’ll create a service to handle file uploads and return the URL, which can then be stored in our database or used as needed. our service would look like the below snippet we created a class CloudFlareR2Service</p><pre>/**<br> * @author olulodeolatunbosun<br> * @created 9/8/24/09/2024 - 3:37 pm<br> */<br><br>@Configuration<br>public class CloudflareR2Service {<br><br>    @Value(&quot;${application.cloudflare.r2.access-key}&quot;)<br>    private String accessKey;<br><br>    @Value(&quot;${application.cloudflare.r2.secret-key}&quot;)<br>    private String secretKey;<br><br>    @Value(&quot;${application.cloudflare.r2.endpoint}&quot;)<br>    private String endpoint;<br> <br>    @Value(&quot;${application.cloudflare.r2.bucket-name}&quot;)<br>    private String bucketName;<br><br>    @Value(&quot;${application.cloudflare.r2.public-url}&quot;)<br>    private String publicUrl;<br>}</pre><p>The code block below defines a configuration class used to manage the integration with Cloudflare R2, with variables sourced from the application.yml file. These variables are explained as follows:</p><ul><li>accessKey: Stores the access key required to authenticate API requests to Cloudflare R2.</li><li>secretKey: Holds the secret key used in conjunction with the access key to securely access Cloudflare R2.</li><li>endpoint: Specifies the endpoint URL for interacting with Cloudflare R2 storage, similar to AWS S3 endpoints.</li><li>bucketName: The name of the R2 storage bucket where objects will be stored or retrieved.</li><li>publicUrl: The public-facing URL for accessing objects stored in the Cloudflare R2 bucket.</li></ul><pre>public String uploadFile(MultipartFile file, boolean isPublic) throws IOException {<br><br><br>        AwsBasicCredentials awsCredentials = AwsBasicCredentials.create(accessKey, secretKey);<br><br>        S3Configuration serviceConfiguration = S3Configuration.builder()<br>                .pathStyleAccessEnabled(true)<br>                .build();<br><br>        S3Client s3Client =  S3Client.builder()<br>                .credentialsProvider(StaticCredentialsProvider.create(awsCredentials))<br>                .endpointOverride(URI.create(endpoint))<br>                .serviceConfiguration(serviceConfiguration)<br>                .region(Region.US_EAST_1)<br>                .build();<br><br>        // Ensure the bucket exists (create it if it does not)<br>        try {<br>            s3Client.headBucket(HeadBucketRequest.builder().bucket(bucketName).build());<br>        } catch (NoSuchBucketException e) {<br>            s3Client.createBucket(CreateBucketRequest.builder().bucket(bucketName).build());<br>        }<br>}</pre><p>This method handles file uploads to Cloudflare R2, leveraging the AWS S3-compatible API. It takes in a MultipartFile and a boolean isPublic to determine if the file should be publicly accessible.</p><p><strong>Key Steps:</strong></p><ol><li><strong>Credentials Setup</strong>: AWS credentials (accessKey, secretKey) are created for authenticating requests.</li><li><strong>S3 Client Configuration</strong>: A client is configured to connect to Cloudflare R2, overriding the default S3 endpoint.</li><li><strong>Bucket Check</strong>: The method checks if the bucket exists using headBucket. If not, it creates the bucket with createBucket.</li></ol><p>In summary, this method ensures proper configuration and bucket availability before proceeding with the file upload process.</p><p>The final code blocks shows how it was sent to r2 bucket</p><pre>      // Generate a unique key name for the file<br>        String keyName = UUID.randomUUID().toString() + &quot;_&quot; + file.getOriginalFilename();<br><br>        //converting the file to byte<br>        byte[] fileBytes = file.getBytes();<br><br>        // Create the PutObjectRequest with the appropriate ACL<br>        PutObjectRequest.Builder putObjectRequestBuilder = PutObjectRequest.builder()<br>                .bucket(bucketName)<br>                .key(keyName);<br><br>        if (isPublic) {<br>            putObjectRequestBuilder.acl(ObjectCannedACL.PUBLIC_READ); // Set the object to be public<br>        }<br><br>        // Put the object into the R2 bucket<br>        s3Client.putObject(<br>                putObjectRequestBuilder.build(),<br>                RequestBody.fromBytes(fileBytes)<br>        );<br><br>        // Construct the full URL to the uploaded file<br>        return String.format(&quot;%s/%s&quot;, publicUrl, keyName);</pre><p><strong>Generate Key Name</strong>: A unique key is created for the file using UUID combined with the original file name.</p><ol><li><strong>Convert File to Bytes</strong>: The file is converted to a byte array (fileBytes).</li><li><strong>Put Object Request</strong>: A PutObjectRequest is created, setting the bucket name and key. If the file is public, it&#39;s assigned the PUBLIC_READ access control (ACL).</li><li><strong>Upload File</strong>: The file is uploaded to the R2 bucketusing s3Client.putObject.</li><li><strong>Return URL</strong>: The full URL to the uploaded file is constructed and returned.</li></ol><p>In short, this part uploads the file to R2 and provides a public URL if the file is set to be publicly accessible.</p><pre>/**<br> * @author olulodeolatunbosun<br> * @created 9/8/24/09/2024 - 3:37 pm<br> */<br><br>@Configuration<br>public class CloudflareR2Service {<br><br>    @Value(&quot;${application.cloudflare.r2.access-key}&quot;)<br>    private String accessKey;<br><br>    @Value(&quot;${application.cloudflare.r2.secret-key}&quot;)<br>    private String secretKey;<br><br>    @Value(&quot;${application.cloudflare.r2.endpoint}&quot;)<br>    private String endpoint;<br> <br>    @Value(&quot;${application.cloudflare.r2.bucket-name}&quot;)<br>    private String bucketName;<br><br>    @Value(&quot;${application.cloudflare.r2.public-url}&quot;)<br>    private String publicUrl;<br><br><br>    public String uploadFile(MultipartFile file, boolean isPublic) throws IOException {<br><br><br>        AwsBasicCredentials awsCredentials = AwsBasicCredentials.create(accessKey, secretKey);<br><br>        S3Configuration serviceConfiguration = S3Configuration.builder()<br>                .pathStyleAccessEnabled(true)<br>                .build();<br><br>        S3Client s3Client =  S3Client.builder()<br>                .credentialsProvider(StaticCredentialsProvider.create(awsCredentials))<br>                .endpointOverride(URI.create(endpoint))<br>                .serviceConfiguration(serviceConfiguration)<br>                .region(Region.US_EAST_1)<br>                .build();<br><br>        // Ensure the bucket exists (create it if it does not)<br>        try {<br>            s3Client.headBucket(HeadBucketRequest.builder().bucket(bucketName).build());<br>        } catch (NoSuchBucketException e) {<br>            s3Client.createBucket(CreateBucketRequest.builder().bucket(bucketName).build());<br>        }<br><br>        // Generating a unique key name for the file<br>        String keyName = UUID.randomUUID().toString() + &quot;_&quot; + file.getOriginalFilename();<br><br>        //converting the file to byte<br>        byte[] fileBytes = file.getBytes();<br><br>        // Create the PutObjectRequest with the appropriate ACL<br>        PutObjectRequest.Builder putObjectRequestBuilder = PutObjectRequest.builder()<br>                .bucket(bucketName)<br>                .key(keyName);<br><br>        if (isPublic) {<br>            putObjectRequestBuilder.acl(ObjectCannedACL.PUBLIC_READ); <br>        }<br>        // Put the object into the R2 bucket<br>        s3Client.putObject(<br>                putObjectRequestBuilder.build(),<br>                RequestBody.fromBytes(fileBytes)<br>        );<br>        //returning the full url<br>        return String.format(&quot;%s/%s&quot;, publicUrl, keyName);<br>    }<br>}</pre><p>The break down of the code is just into two sections</p><h4>Configuration and Setup</h4><p>The code loads Cloudflare R2 credentials and bucket details from the configuration file using @Value. It then sets up an S3Client with these credentials, the Cloudflare R2 endpoint, and path-style access. The client checks if the specified bucket exists, and if not, it creates one.</p><h4>File Upload and URL Generation</h4><p>The file is converted to a byte array, and a unique key is generated for it. The PutObjectRequest is built, specifying whether the file should be public. The file is then uploaded to the R2 bucket using s3Client.putObject(). Finally, the full URL of the uploaded file is constructed and returned.</p><h3>Controller Implementation</h3><p>After successfully creating the service we can now use this service in our controller and it looks like below snippet</p><pre>/**<br> * @author olulodeolatunbosun<br> * @created 9/8/24/09/2024 - 1:43 pm<br> */<br><br>@RestController<br>@RequestMapping(&quot;/api/v1/upload&quot;)<br>public class ArticleController {<br><br>    private final CloudflareR2Service cloudflareR2Config;<br><br>    public ArticleController(CloudflareR2Service cloudflareR2Config) {<br>        this.cloudflareR2Config = cloudflareR2Config;<br>    }<br><br><br>    // Add your endpoints here<br>    @PostMapping(value = &quot;/file&quot;, consumes = {&quot;multipart/form-data&quot;})<br>    public ResponseEntity&lt;String&gt; uploadFile(@RequestParam(&quot;file&quot;) MultipartFile file) throws IOException {<br>        String  url =   cloudflareR2Config.uploadFile(file, true);<br>        return ResponseEntity.ok(&quot;File uploaded successfully to &quot; + url);<br>    }<br><br><br>}</pre><h4>Controller Setup</h4><p>This code defines a REST controller (ArticleController) that handles file uploads via an API endpoint (/api/v1/upload). It uses dependency injection to access the CloudflareR2Service for handling file uploads. The @RestController and @RequestMapping annotations define the controller and base route for the API.</p><h4>File Upload Endpoint</h4><p>The uploadFile method maps to a POST request (/file) and accepts a file using the @RequestParam(&quot;file&quot;). It calls CloudflareR2Service to upload the file, then returns a success message with the uploaded file’s URL. The @PostMapping annotation specifies multipart/form-data as the content type, which is necessary for sending files in a form submission. This encoding type allows large files, such as images or documents, to be transmitted properly in the request.</p><p>Finally, we’ll test our API using Postman to verify that the file is successfully uploaded to Cloudflare R2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rw9cWjOlehV-KnyZEv1wEw.png" /><figcaption>Request to be sent to our controller via postman.</figcaption></figure><p>The image below displays the response from Postman, showing the URL to access the uploaded file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pH4j7iVmPR09z1Cx8A1-bQ.png" /></figure><h4>Conclusion</h4><p>We have walked through the process of setting up a Spring Boot application to upload files to Cloudflare R2. With this integration, you can take advantage of R2’s scalable and cost-effective storage in your Spring Boot applications.</p><h4>Additional Resources and References</h4><ul><li><a href="https://developers.cloudflare.com/r2/api/s3/api/">Cloudflare R2 Documentation</a></li><li><a href="https://spring.io/projects/spring-boot">Spring Boot Official Documentation</a></li><li><a href="https://docs.aws.amazon.com/sdk-for-java/v1/developer-guide/welcome.html">AWS SDK for Java Documentation</a></li></ul><p>Full code is here on <a href="https://github.com/horlathunbhosun/tutorial-springboot-clouflareR2">github</a> .</p><p>Thanks for following through. Keeping learning and happy hacking</p><p>Let connect on <a href="https://www.linkedin.com/in/olulode-olatunbosun/">LinkedIn </a>and <a href="https://x.com/olaolulode">Twitter</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cc180cc85540" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sending Email Notifications with RabbitMQ Using Java (Spring Boot)]]></title>
            <link>https://olaolulode.medium.com/sending-email-notifications-with-rabbitmq-using-java-spring-boot-fc50f6bdb878?source=rss-f8cd0ba28757------2</link>
            <guid isPermaLink="false">https://medium.com/p/fc50f6bdb878</guid>
            <category><![CDATA[java-email]]></category>
            <category><![CDATA[rabbitmq]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Olulode Olatunbosun]]></dc:creator>
            <pubDate>Sun, 19 May 2024 12:33:36 GMT</pubDate>
            <atom:updated>2024-05-19T21:06:19.919Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TPeyqGkXEnVJzqOMbvwd2Q.jpeg" /></figure><p>RabbitMQ serves as a message broker, acting as a middleman to facilitate communication between different parts of a software system. It manages message queuing, routing, and delivery, enabling components to interact seamlessly. In this tutorial, you’ll learn how to set up RabbitMQ using Docker, connect it with a Spring Boot application, and use it to send email notifications asynchronously.</p><p>In this tutorial, you will learn the following</p><ul><li>What is async programming?</li><li>How to Setting up rabbitmq using docker</li><li>Connect it with Spring boot application</li><li>Send email notification asynchronously</li></ul><h3>What is Asynchronous Programming?</h3><p>Asynchronous programming enables tasks to operate independently of the main program flow, allowing multiple operations to execute concurrently. Unlike synchronous programming, where tasks are executed sequentially, asynchronous programming allows the program to initiate a task and proceed with other tasks while awaiting the completion of the initial one. This method prevents blocking, enhances performance, and optimizes resource usage. Asynchronous programming is particularly useful when dealing with tasks such as sending emails, generating reports with large volumes of data, verifying transactions, and more.</p><h3><strong>Setting up a spring boot application</strong></h3><p>To initiate the setup of a Spring Boot application, I typically utilize<a href="https://start.spring.io/"> Spring Initializr</a> to kickstart the project. Below, I’ll outline the process of adding necessary dependencies for our application. In this particular use case, we’ll include Spring for RabbitMQ, as it’s integral to the purpose of this application. Additionally, you’ll find a list of other dependencies that are essential for configuring the Spring Boot application. Below snapshot covers the setup we need to get the application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VzJJKJhk6LfK--tcr8ZvlA.png" /><figcaption>snapshot of setting up springboot application</figcaption></figure><p>Once the application setup is complete, you’ll generate and open it in your Integrated Development Environment (IDE), where you should see a structure resembling the image below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/645/1*C7ljvAY-iO21EE1-hug6EA.png" /><figcaption>a screenshot of the structure of the application</figcaption></figure><p>Following the setup, I’ll proceed to create the required classes and structure for our application. The resulting structure may resemble the image below, but it’s not mandatory to strictly adhere to this convention.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/739/1*h9-vIIHg5NxRBZJ99bCGhg.png" /><figcaption>this screenshot shows how i structured my project</figcaption></figure><h3>Setting Up RabbitMQ Using Docker with docker compose</h3><p>Create a docker-compose.yml file in the root directory of your Spring Boot application to set up RabbitMQ:</p><pre>version: &#39;3.8&#39;  # specify your Docker Compose version<br>services:<br>  rabbitmq:<br>    container_name: rabbitmq-new<br>    image: rabbitmq:3-management<br>    ports:<br>      - &quot;5672:5672&quot;<br>      - &quot;15672:15672&quot;<br>    environment:<br>      RABBITMQ_DEFAULT_USER: ${RABBITMQ_USERNAME} # RabbitMQ username<br>      RABBITMQ_DEFAULT_PASS: ${RABBITMQ_PASSWORD} # RabbitMQ password</pre><p>This configuration exposes both the RabbitMQ server port (5672) and the web console port (15672). The management tag in the Docker image enables access to the web interface. Set up the default user and password using environment variables.</p><p>You will also need to create a bash script start-service.sh<em> </em>to start the Docker container with a bash script</p><pre>#!/bin/bash<br>export RABBITMQ_USERNAME=myuser<br>export RABBITMQ_PASSWORD=mypassword<br><br>docker compose up</pre><p>Once we’ve created the bash script to start our application, we need to make it executable by running the command chmod +x nameofyourscript.sh. To run the script, we use ./nameofyourscript.sh.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gsg7Jnk9GfyYm0hacgJsUA.png" /><figcaption>a snapshot showing how i started the docker file</figcaption></figure><p>Upon execution, we&#39;ll observe RabbitMQ starting up within Docker. We can access its web interface through the exposed port specified in the Docker Compose file. This interface provides insights and control over RabbitMQ&#39;s functionalities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eloNcNrkfaM5uPSztYH5rg.png" /><figcaption>a snapshot for the login interface</figcaption></figure><p>After logging into the interface using the credentials set in the bash script, we’ll access the following interface.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jj5TUJfNHPZOLPMdVOCKMQ.png" /><figcaption>snapshot of the rabbitmq interface where we see our queues</figcaption></figure><h3>Connecting RabbitMQ with Spring Boot for Email Notifications</h3><h4>RabbitMQ Configuration Class</h4><p>Create a configuration class named RabbitMQConfig in your Spring Boot application. Add the following three properties to the application.yml file, each serving a distinct purpose:</p><ol><li>Queue name: Specifies the name of the queue where messages will be stored before processing.</li><li>Exchange email name: Identifies the exchange to which messages will be sent for email processing.</li><li>Email routing key: Determines the routing of messages within the exchange for email-related operations.</li></ol><pre>@Configuration<br>public class RabbitMQConfig {<br>    @Value(&quot;${rabbitmq.queue.email.name}&quot;)<br>    private String emailQueue;<br><br>    @Value(&quot;${rabbitmq.exchange.email.name}&quot;)<br>    private String emailExchange;<br><br>    @Value(&quot;${rabbitmq.binding.email.name}&quot;)<br>    private String emailRoutingKey;<br><br>    @Bean<br>    public Queue emailQueue() {<br>        return new Queue(emailQueue);<br>    }<br><br>    @Bean<br>    public TopicExchange emailExchange() {<br>        return new TopicExchange(emailExchange);<br>    }<br><br>    @Bean<br>    public Binding emailBinding() {<br>        return BindingBuilder.bind(emailQueue())<br>                .to(emailExchange())<br>                .with(emailRoutingKey);<br>    }<br><br>    @Bean<br>    public AmqpTemplate amqpTemplate(ConnectionFactory connectionFactory) {<br>        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);<br>        rabbitTemplate.setMessageConverter(converter());<br>        return rabbitTemplate;<br>    }<br><br>    @Bean<br>    public Jackson2JsonMessageConverter converter() {<br>        return new Jackson2JsonMessageConverter();<br>    }<br>}</pre><p>This class sets up the RabbitMQ queue, exchange, and binding. It also configures an AmqpTemplate for sending messages and a message converter for JSON format</p><h4>Email Detail DTO</h4><p>What is DTO( Data transfer object) ? A Data Transfer Object (DTO) is a design pattern used for transferring data between software components or layers within an application. In the context this email detail DTO, it’s a structure that holds essential information about an email, such as sender, recipients, subject, and body. This DTO allows for organized and efficient transfer of email-related data between different parts of the application.</p><p>Define a Data Transfer Object (DTO) for email details:</p><pre>@Data<br>@Builder<br>public class EmailDetailDTO {<br>    private String to;<br>    private String subject;<br>    private Map&lt;String, Object&gt; dynamicValue;<br>    private String templateName;<br>}</pre><h4>Email Service Class</h4><p>Create a service class EmailService to handle email sending:</p><pre>@Service<br>@RequiredArgsConstructor<br>public class EmailService {<br>    private final JavaMailSender emailSender;<br><br>    @Value(&quot;${application.mail.sent.from}&quot;)<br>    private String fromUsr;<br><br>    public void sendEmail(String to, String subject, String body) throws MessagingException {<br>        MimeMessage message = emailSender.createMimeMessage();<br>        MimeMessageHelper helper = new MimeMessageHelper(message, true, &quot;UTF-8&quot;);<br>        helper.setTo(to);<br>        helper.setFrom(fromUsr);<br>        helper.setSubject(subject);<br>        helper.setText(body, true);<br>        emailSender.send(message);<br>    }<br><br>    @RabbitListener(queues = &quot;email_queue&quot;)<br>    public void processEmailMessage(EmailDetailDTO emailDetailDTO) throws MessagingException {<br>        String to = emailDetailDTO.getTo();<br>        String subject = emailDetailDTO.getSubject();<br>        String body = generateEmailBody(emailDetailDTO);<br>        sendEmail(to, subject, body);<br>    }<br><br>    public String generateEmailBody(EmailDetailDTO emailDetailDTO) {<br>        String templateName = emailDetailDTO.getTemplateName();<br>        String template = loadEmailTemplate(templateName);<br><br>        String body = template;<br>        if (emailDetailDTO.getDynamicValue() != null) {<br>            for (Map.Entry&lt;String, Object&gt; entry : emailDetailDTO.getDynamicValue().entrySet()) {<br>                body = body.replace(&quot;{{&quot; + entry.getKey() + &quot;}}&quot;, entry.getValue().toString());<br>            }<br>        }<br><br>        return body;<br>    }<br><br>    public String loadEmailTemplate(String templateName) {<br>        ClassPathResource resource = new ClassPathResource(&quot;templates/emails/&quot; + templateName + &quot;.html&quot;);<br>        try {<br>            return StreamUtils.copyToString(resource.getInputStream(), StandardCharsets.UTF_8);<br>        } catch (IOException e) {<br>            throw new RuntimeException(&quot;Error loading email template &quot; + templateName, e);<br>        }<br>    }<br>}</pre><p>This service listens for messages on the email_queue, processes the email details, and sends the email using JavaMailSender.</p><h4>User Service Implementation</h4><p>Implement the user service to handle user registration and send a verification email:</p><pre>@Service<br>@RequiredArgsConstructor<br>public class UserServiceImpl implements UserService {<br>    private final UserRepository userRepository;<br>    private final PasswordEncoder passwordEncoder;<br>    private final RabbitTemplate rabbitTemplate;<br><br>    @Value(&quot;${rabbitmq.exchange.email.name}&quot;)<br>    private String emailExchange;<br><br>    @Value(&quot;${rabbitmq.binding.email.name}&quot;)<br>    private String emailRoutingKey;<br><br>    @Override<br>    @Transactional<br>    public GenericResponseDTO saveUser(CreateUserDTO createUserDTO) {<br>        String verificationToken = TokenGenerator.generateToken(6);<br>        User user = modelMapper.map(createUserDTO, User.class);<br>        GenericResponseDTO responseDTO = new GenericResponseDTO();<br>        user.setVerificationCode(verificationToken);<br>        user.setPassword(passwordEncoder.encode(createUserDTO.getPassword()));<br><br>        try {<br>            User savedUser = userRepository.save(user);<br>            sendEmail(user, verificationToken, &quot;Email Verification&quot;);<br>            responseDTO.setMessage(&quot;User created successfully&quot;);<br>            responseDTO.setStatus(&quot;success&quot;);<br>            return responseDTO;<br>        } catch (Exception e) {<br>            responseDTO.setMessage(&quot;An error occurred: &quot; + e.getMessage());<br>            responseDTO.setStatus(&quot;error&quot;);<br>            responseDTO.setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR.value());<br>            return responseDTO;<br>        }<br>    }<br><br>    private void sendEmail(User user, String token, String subject) {<br>        Map&lt;String, Object&gt; mailData = Map.of(&quot;token&quot;, token, &quot;fullName&quot;, user.getFullName());<br><br>        rabbitTemplate.convertAndSend(emailExchange, emailRoutingKey, EmailDetailDTO.builder()<br>                .to(user.getEmail())<br>                .subject(subject)<br>                .dynamicValue(mailData)<br>                .templateName(&quot;verification&quot;)<br>                .build());<br>    }<br>}</pre><p>The EmailService class facilitates email sending within the application by utilising JavaMailSender for construction and delivery of emails, while also listening for messages on the “email_queue” RabbitMQ queue, processing email details, generating email bodies from templates, and sending emails accordingly.</p><h3><strong>The UserController implementation</strong></h3><p>Here’s the implementation of the UserController, providing a clearer explanation of how it handles user-related operations within the application.</p><pre>@RestController<br>@RequiredArgsConstructor<br>@RequestMapping(&quot;users/&quot;)<br>public class UserController {<br><br>    private final UserService userService;<br>    @PostMapping(&quot;/register&quot;)<br>    public ResponseEntity&lt;GenericResponseDTO&gt; registerUser(@RequestBody CreateUserDTO createUserDTO){<br>        GenericResponseDTO response = userService.saveUser(createUserDTO);<br>        if (response.getStatus().equals(&quot;error&quot;)){<br>            return new ResponseEntity&lt;&gt;(response, HttpStatusCode.valueOf(response.getStatusCode()));<br>        }<br>        return new ResponseEntity&lt;&gt;(response, HttpStatus.CREATED);<br>    }<br>}</pre><p>The UserController class acts as a REST controller, managing user registration via a POST endpoint &quot;/users/register&quot;, utilizing UserService to process user data, and returning appropriate responses, including status and HTTP status codes.</p><p>We’re going to conduct a test on the application to observe the email being sent and the queue being processed. We’ll review screenshots to confirm the successful execution of these actions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QRh61RZ_z8I3DlCKFCQ8Aw.png" /><figcaption>a snapshot if when the queue has not processed any message</figcaption></figure><p>In the above provided snapshot, it’s evident that the “email_queue” has not processed any messages, as indicated by both the “unacked” and “total” counts being 0. This suggests that there are currently no messages awaiting processing within the queue.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3NQtvhvQWoFWsFKnUPLEuA.png" /></figure><p>Take a look at this screenshot. It’s clear that the “email_queue” has processed a message, as indicated by both the “unacked” and “total” counts being 1. This indicates that there are messages currently awaiting processing within the queue.</p><h3>Conclusion</h3><p>In this article, you learned how to set up and use RabbitMQ with Spring Boot to send email notifications asynchronously. We covered the following key points:</p><ol><li><strong>Understanding Asynchronous Programming</strong>: The basics of asynchronous programming and its benefits.</li><li><strong>Setting Up RabbitMQ Using Docker</strong>: How to configure and run RabbitMQ using Docker.</li><li><strong>Integrating RabbitMQ with Spring Boot</strong>: Creating configuration and service classes to enable RabbitMQ messaging.</li><li><strong>Sending Email Notifications</strong>: Implementing a service to send emails using JavaMailSender and processing messages from RabbitMQ.</li></ol><p>By following this tutorial, you now have a working setup for handling email notifications in an efficient and scalable way, leveraging the power of RabbitMQ for message queuing.</p><p>You can find the full code for this here on <a href="https://github.com/horlathunbhosun/springboot-email-rabbitmq">github</a></p><p>Keep learning, and happy coding!</p><p>Let connect on <a href="https://www.linkedin.com/in/olulode-olatunbosun/">LinkedIn </a>and <a href="https://x.com/olaolulode">Twitter</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fc50f6bdb878" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ArrayList and LinkedList Explained]]></title>
            <link>https://olaolulode.medium.com/what-is-arraylist-and-linkedlist-4ddd491c86e5?source=rss-f8cd0ba28757------2</link>
            <guid isPermaLink="false">https://medium.com/p/4ddd491c86e5</guid>
            <category><![CDATA[arraylist]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[linklist]]></category>
            <category><![CDATA[java-tips]]></category>
            <category><![CDATA[java-linked-list]]></category>
            <dc:creator><![CDATA[Olulode Olatunbosun]]></dc:creator>
            <pubDate>Sun, 03 Dec 2023 12:41:58 GMT</pubDate>
            <atom:updated>2023-12-03T13:38:02.345Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*j40HbEgaVfixL6GXz_Cz7Q.jpeg" /><figcaption>source google</figcaption></figure><p>Dealing with arrays can be challenging, particularly when it involves altering their size. Arrays are inherently static in length, prohibiting direct resizing and necessitating the creation of a new array to accommodate changes. This limitation can make the process of updating arrays notably burdensome.</p><pre>int[] numbers = {1, 2, 3};<br>int[] newNumbers = new int[numbers.length + 1];<br><br><br>for (int i = 0; i &lt; numbers.length; i++) {<br>    newNumbers[i] = numbers[i];<br>}<br><br><br>newNumbers[numbers.length] = 4;</pre><p>The above code shows how its stressing to increase the size of array and we were required to generate a fresh array, duplicate the elements from the existing array, and then include the new element. This method isn’t efficient.</p><h3><strong>LET TALK ABOUT ARRAYLIST</strong></h3><p>In programming, <strong>an ArrayList is a dynamic,</strong> resizable data structure that resembles a list and holds components of the same type. Numerous computer languages, including Java, contain it.<br><strong>An ArrayList can dynamically expand and contract in size as elements are added or removed, unlike normal arrays</strong>. This implies that its size does not have to be predetermined; it can grow as required. Convenient ways to add, remove, access, and alter elements of a list are offered by array lists.<br>Consider an ArrayList as a pliable container that can easily adjust its size to accommodate a collection of things as needed. below is the way you can</p><p>A simple snippet of how to write an array list</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/952/1*U30ReiaGP2oR_PojNNblEg.png" /></figure><p>The first code creates and an arrayList to store string</p><pre>List&lt;String&gt; name = new ArrayList&lt;String&gt;();</pre><p>You can use an <strong>add</strong> method to add elements to the ArrayList:</p><pre>name.add(&quot;My Name&quot;);<br>name.add(&quot;Apple&quot;);<br>name.add(&quot;Ajay vajy&quot;);   </pre><p>You can use a <strong>remove</strong> method to remove elements from the ArrayList:</p><pre>name.remove(&quot;My Name&quot;);<br>name.remove(&quot;Apple&quot;);</pre><p>You can use a <strong>.size()</strong> to get the size of an ArrayList:</p><pre>name.size()</pre><p>In summary working with ArrayLists is much simpler than using regular arrays. The <strong>ArrayList</strong> automatically manages the complexities of resizing, adding, and removing elements behind the scenes for you.</p><h3>WORKING WITH LINKEDLIST</h3><p>A LinkedList is a linear data structure in programming that consists of a sequence of elements, where each element is a separate object known as a node. In a LinkedList, each node contains a reference (or pointer) to the next node in the sequence, forming a chain-like structure.</p><p>Unlike arrays, LinkedLists do not store elements in contiguous memory locations. Instead, each node contains data and a reference to the next node, allowing flexibility in inserting or removing elements from the list without the need to shift other elements, as is often required in arrays.</p><p>LinkedLists offer efficient insertion and deletion operations, especially when working with large collections of data, as they require changing only a few pointers to re organize the structure, rather than moving entire blocks of elements in memory. However, LinkedLists may not offer constant-time access to individual elements like arrays do, as accessing elements requires traversing the list from the beginning or end to reach a specific position.</p><p>A simple snippet of how to write an Linked list</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1001/1*C-YS_nHW8Lqt51pE48uBSg.png" /></figure><p>The first code creates and an Linkedlist to store string</p><pre>List&lt;String&gt; name = new LinkedList&lt;String&gt;();</pre><p>You can use an <strong>add</strong> method to add elements to the LinkedList:</p><pre>name.add(&quot;My Name&quot;);<br>name.add(&quot;Apple&quot;);<br>name.add(&quot;Ajay vajy&quot;);</pre><p>You can use a <strong>remove</strong> method to remove elements from the LinkedList:</p><pre>name.remove(&quot;My Name&quot;);<br>name.remove(&quot;Apple&quot;);</pre><p>You can use a <strong>.size()</strong> to get the size of an LinkedList:</p><pre>name.size()</pre><p>Different between ArrayList and LinkedList</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/728/1*RoPvzpwzFqp3D_Qx-4rZRg.png" /></figure><h3><strong>Things to Bear in Mind</strong></h3><p>Here are some crucial things to keep in mind while working with LinkedLists and ArrayLists.</p><p><em>Choose the LinkedList when the rate of addition or removal exceeds the read situations. Conversely, ArrayList supersedes LinkedList when the frequency of read scenarios exceeds the rate of addition or removal.</em></p><p><em>The ArrayList is more cache-friendly than the LinkedList since its elements are stored in a more compact manner relative to the latter. As a result, an ArrayList has a lower likelihood of a cache miss than a LinkedList. A linked list is generally thought to have poor cache-locality.</em></p><p><em>The LinkedList has a higher memory overhead than the ArrayList. The reason for this is that a LinkedList has two extra links (next and prior) since the addresses of the previous and next nodes must be stored, and these linkages take up additional space. An ArrayList does not contain these links.</em></p><p><em>Please thumb up the Deep Dive if you like it! If you have question or remarks, start the conversation here :)</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4ddd491c86e5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Git Exposure To Git Init, Git Add , Git Status, Git Commit, Git Log , Git Branch]]></title>
            <link>https://olaolulode.medium.com/git-exposure-to-git-init-git-add-git-status-git-commit-git-log-git-branch-936b8672247?source=rss-f8cd0ba28757------2</link>
            <guid isPermaLink="false">https://medium.com/p/936b8672247</guid>
            <category><![CDATA[git-pull]]></category>
            <category><![CDATA[git-commands]]></category>
            <category><![CDATA[basic-git-commands]]></category>
            <category><![CDATA[git-init]]></category>
            <category><![CDATA[git]]></category>
            <dc:creator><![CDATA[Olulode Olatunbosun]]></dc:creator>
            <pubDate>Thu, 04 Jun 2020 14:55:54 GMT</pubDate>
            <atom:updated>2020-06-21T13:10:04.548Z</atom:updated>
            <content:encoded><![CDATA[<h3>Git Exposure To Git Init, Git Add , Git Status, Git Commit, Git Log , Git Branch</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*G17X8jdwng6JbRTc61OJCQ.png" /><figcaption>git commands</figcaption></figure><p>We will be talking about basic git commands which are git init, git add , git status, git commit, git log , git branch</p><p>The <strong><em>git init</em></strong> is to start a new repository on github , so it used to initialize the new repository, so inside the new project you are trying to push, you git initialize it .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*Xn0T-CriCFt7_uXgR3j8Gg.png" /><figcaption>git init</figcaption></figure><p><strong><em>Git add [file name] </em></strong>this is used to add the files you have worked on to staging area staging area is a rough area where you can add your files ready for commit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/607/1*sbwmTmoWorA1fuQgvSaQeg.png" /><figcaption>git add [hey.php]</figcaption></figure><p><strong><em>git commit</em></strong> -m this is used to send or record all files to the version history.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/574/1*E70VLu-IUE_k8DUAFgnDlA.png" /><figcaption>git commit -m “hey.php”</figcaption></figure><p><strong><em>git status</em></strong> this is the command to list all files to be added to staging area before been committed to the version history.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*WqzgI6vISSsEeiKKJ9-w2Q.png" /><figcaption>git status</figcaption></figure><p><strong><em>git log</em></strong> this is used to view all version history of the current branch you are working on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*nUjZvYsrd0SeixmITmuxQA.png" /><figcaption>git log</figcaption></figure><p><strong><em>git branch</em></strong> this will list all local branches in the current repository.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/556/1*wXFGjI-sXiMTXZEXNGrqyw.png" /><figcaption>git branch</figcaption></figure><p>I hope these helps you understand some basic git commands. for more about git you can visit git documentation <a href="https://git-scm.com/docs/git/2.7.6">here</a>. Thanks</p><blockquote>kindly follow on twitter <a href="https://twitter.com/olaolulode"><strong>https://twitter.com/olaolulode</strong></a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=936b8672247" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>