<?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 Fajrimoad on Medium]]></title>
        <description><![CDATA[Stories by Fajrimoad on Medium]]></description>
        <link>https://medium.com/@fajrimoad?source=rss-86ce35ae453------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*189c16lS6MLEjHthLNwMag.png</url>
            <title>Stories by Fajrimoad on Medium</title>
            <link>https://medium.com/@fajrimoad?source=rss-86ce35ae453------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 06:20:58 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@fajrimoad/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[Bridging GitHub and AWS CodeCommit with AWS CodeBuild]]></title>
            <link>https://medium.com/@fajrimoad/bridging-github-and-aws-codecommit-with-aws-codebuild-703542d4d019?source=rss-86ce35ae453------2</link>
            <guid isPermaLink="false">https://medium.com/p/703542d4d019</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Fajrimoad]]></dc:creator>
            <pubDate>Mon, 19 Feb 2024 07:31:55 GMT</pubDate>
            <atom:updated>2024-02-19T07:31:55.748Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*C0tgs9jYxSZ4swfI" /><figcaption>Source : Pexels</figcaption></figure><p>Introduction :</p><p>Creating an efficient workflow for software development requires not only a good understanding of coding practices but also a mastery of the tools and services that make development smoother and more streamlined. In this tutorial, we will guide you through the process of mirroring GitHub events to AWS CodeCommit using AWS CodeBuild, a method that can significantly enhance your version control and continuous integration/continuous deployment (CI/CD) strategies.</p><h3>Prerequisites</h3><ul><li>Github repository as source</li><li>Aws CodeCommit repository as destination</li><li>IAM user with the necessary policies attached to it</li></ul><h3>Setting Up AWS CodeBuild</h3><ol><li>go to codeBuild → Create Project</li><li>Choose in the parameters github as source and leave the default amazon linux AMI and sign in using OAuth to your Github account</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wXtgYXJJqDMh2DU3rxFLHA.png" /><figcaption>AWS code build project creation interface</figcaption></figure><p>3.Modify the Yaml of you Buildspec.yaml:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X6SlEZNDvNoEvGtcCniW2g.png" /><figcaption>AWS code build project creation interface</figcaption></figure><p>Insert the following yaml :</p><pre>version: 0.2<br><br>phases:<br>  install:<br>    commands:<br>      # Setup Git to use the AWS credential helper for HTTPS URLs. This is essential for<br>      # authenticating with AWS CodeCommit repositories without embedding AWS credentials.<br>      - git config --global credential.helper &#39;!aws codecommit credential-helper $@&#39;<br>      - git config --global credential.UseHttpPath true<br><br>  pre_build:<br>    commands:<br>      # Optional: Use this phase to set up or configure your environment before the build starts.<br>      # This example simply prints a message, but you can customize it as needed.<br>      - echo &quot;Pre-build phase...&quot;<br><br>  build:<br>    commands:<br>      # Main build phase: Clone the GitHub repository and mirror it to AWS CodeCommit.<br>      # Replace YOUR_GITHUB_REPO_URL with the URL of your GitHub repository and<br>      # YOUR_CODECOMMIT_REPO_URL with your AWS CodeCommit repository URL.<br>      - echo &quot;Cloning GitHub repository and pushing to AWS CodeCommit...&quot;<br>      - git clone --mirror YOUR_GITHUB_REPO_URL<br>      - cd [REPO_NAME].git  # Replace [REPO_NAME] with your repository name<br>      - git remote set-url origin YOUR_CODECOMMIT_REPO_URL<br>      - git push --mirror<br><br>  post_build:<br>    commands:<br>      # Optional: Use this phase for cleanup or other post-build tasks.<br>      - echo &quot;Post-build phase...&quot;</pre><p>This generic buildspec.yml file is designed to guide users through setting up AWS CodeBuild for mirroring a GitHub repository to AWS CodeCommit. By replacing placeholder URLs and repository names with their specific details, readers can easily adapt this configuration for their projects.</p><p>4. Add premission to your CodeBuild Role :</p><p>Copy the role of the aws codeBuild and go to IAM → roles → add permission :</p><p>a. IAM Role selection :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gI-twk7qhQD1Jmugjr3WSQ.png" /><figcaption>AWS IAM</figcaption></figure><p>b.Adding <strong>AWSCodeCommitPowerUser</strong> role</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kHzpSYX_UuDqWK2giVkNJg.png" /><figcaption>AWS IAM</figcaption></figure><p>5.Verify that the Webhook is created in github :</p><p>exemple :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KgPw29y5dNfys_tR3o26FA.png" /><figcaption>Github Settings</figcaption></figure><h3>Conclusion</h3><p>And there you have it, a digital high-five for successfully setting up your GitHub to AWS CodeCommit mirror using AWS CodeBuild! You’ve just performed a coding magic trick, turning complex instructions into a seamless workflow masterpiece. Think of yourself as a tech wizard, with the power to sync repositories with a flick of your command line wand.</p><p>And there you have it, a digital high-five for successfully setting up your GitHub to AWS CodeCommit mirror using AWS CodeBuild! You’ve just performed a coding magic trick, turning complex instructions into a seamless workflow masterpiece. Think of yourself as a tech wizard, with the power to sync repositories with a flick of your command line wand.</p><p>So, take a bow, maybe do a little celebratory keyboard tap dance (quietly, if it’s late), and enjoy the smoother sailing ahead in your development journey. Remember, every great tech adventure is</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=703542d4d019" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Efficient Video Splitting with FFmpeg and JavaCV]]></title>
            <link>https://medium.com/@fajrimoad/efficient-video-splitting-with-ffmpeg-and-javacv-b19692db438d?source=rss-86ce35ae453------2</link>
            <guid isPermaLink="false">https://medium.com/p/b19692db438d</guid>
            <category><![CDATA[ocr-tesseract]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[development]]></category>
            <dc:creator><![CDATA[Fajrimoad]]></dc:creator>
            <pubDate>Thu, 08 Feb 2024 20:59:15 GMT</pubDate>
            <atom:updated>2024-02-08T20:59:15.725Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wflOlQAhMGVDsCEagJFIig.jpeg" /><figcaption>source : pexels</figcaption></figure><p>Splitting videos into smaller segments can be crucial for various applications like video editing, sharing, or processing. This tutorial demonstrates how to leverage the power of FFmpeg and JavaCV to efficiently split videos into multiple segments in Java. We’ll walk you through setting up your environment, understanding the code, and executing the process.</p><h3>Prerequisites</h3><p>- Java Development Kit (JDK): Ensure you have Java 8 or newer installed on your system.<br>- Maven: This project uses Maven to manage dependencies.<br>- FFmpeg: JavaCV utilizes FFmpeg under the hood. Ensure FFmpeg is installed and accessible in your system’s PATH.</p><h4>Step 1: Setting Up Your Project</h4><p>Create a new Maven project and add the following dependencies to your pom.xml file to include JavaCV and FFmpeg libraries:</p><pre>&lt;dependencies&gt;<br>    &lt;dependency&gt;<br>        &lt;groupId&gt;org.bytedeco&lt;/groupId&gt;<br>        &lt;artifactId&gt;javacv&lt;/artifactId&gt;<br>        &lt;version&gt;1.5.7&lt;/version&gt;<br>    &lt;/dependency&gt;<br>    &lt;dependency&gt;<br>        &lt;groupId&gt;org.bytedeco&lt;/groupId&gt;<br>        &lt;artifactId&gt;javacv-platform&lt;/artifactId&gt;<br>        &lt;version&gt;1.5.7&lt;/version&gt;<br>    &lt;/dependency&gt;<br>    &lt;dependency&gt;<br>        &lt;groupId&gt;org.bytedeco&lt;/groupId&gt;<br>        &lt;artifactId&gt;ffmpeg-platform&lt;/artifactId&gt;<br>        &lt;version&gt;4.4-1.5.7&lt;/version&gt;<br>    &lt;/dependency&gt;<br>&lt;/dependencies&gt;</pre><p>First, let’s write a simple program to open a video file and read its basic properties.</p><h3>Create the Segmentor Class</h3><p>In your project, create a class named Segmentor.java. This class will handle the video processing tasks.</p><h3>Initialize FFmpegFrameGrabber</h3><p>Start by writing a method to open a video file using FFmpegFrameGrabber:</p><pre>package com.moviid.vidprocessor.service;<br><br>import org.bytedeco.javacv.FFmpegFrameGrabber;<br><br>public class Segmentor {<br><br>    public static void openVideo(String filePath) {<br>        try (FFmpegFrameGrabber grabber = new FFmpegFrameGrabber(filePath)) {<br>            grabber.start();<br>            System.out.println(&quot;Video opened: &quot; + filePath);<br>            grabber.stop();<br>        } catch (Exception e) {<br>            e.printStackTrace();<br>        }<br>    }<br>}</pre><p>This method attempts to open and start a frame grabber for the specified video file.</p><h3>Step 3: Splitting the Video into Segments</h3><p>Now, let’s extend our Segmentor class to split the video into segments. We&#39;ll add functionality to calculate segment durations and process each segment individually.</p><h3>Calculate Segment Durations</h3><p>Add a method to calculate the duration of each segment based on the total video length:</p><pre>private static final int TOTAL_SEGMENTS = 5; // Example segment count<br><br>private static void splitVideo(String filePath) {<br>    try (FFmpegFrameGrabber grabber = new FFmpegFrameGrabber(filePath)) {<br>        grabber.start();<br>        <br>        long totalDuration = grabber.getLengthInTime(); // Total video duration in microseconds<br>        long segmentDuration = totalDuration / TOTAL_SEGMENTS;<br>        <br>        System.out.println(&quot;Each segment duration: &quot; + segmentDuration + &quot; microseconds&quot;);<br>        grabber.stop();<br>    } catch (Exception e) {<br>        e.printStackTrace();<br>    }<br>}</pre><p>This method divides the video into equal-length segments, preparing us for the actual splitting process.</p><h3>Process Each Segment</h3><p>Next, we implement logic to extract and save each segment as a separate video file:</p><ol><li>Modify splitVideo Method: Enhance splitVideo to loop through each segment, calculating start and end times.</li><li>Extract Segments: Use FFmpegFrameGrabber to read and FFmpegFrameRecorder to write each segment.</li></ol><p>Due to space constraints, I’ll outline the conceptual steps for processing segments:</p><ul><li>Loop through the total number of segments.</li><li>For each segment, calculate the start and end timestamps.</li><li>Use a FFmpegFrameGrabber to read frames from the start timestamp.</li><li>Initialize a FFmpegFrameRecorder to write frames to a new file until the end timestamp is reached.</li></ul><pre>private static final int TOTAL_SEGMENTS = 5; // Example: Split video into 5 segments<br><br>private static void splitVideo(String filePath, ExecutorService executor) {<br>    try (FFmpegFrameGrabber grabber = new FFmpegFrameGrabber(filePath)) {<br>        grabber.start();<br><br>        long totalDuration = grabber.getLengthInTime(); // Total video duration in microseconds<br>        long segmentDuration = totalDuration / TOTAL_SEGMENTS; // Duration of each segment<br><br>        for (int segment = 0; segment &lt; TOTAL_SEGMENTS; segment++) {<br>            final long startTimestamp = segment * segmentDuration; // Start timestamp for this segment<br>            final long endTimestamp = (segment + 1) * segmentDuration; // End timestamp for this segment<br>            // Last segment goes to the end of the video<br>            if (segment == TOTAL_SEGMENTS - 1) {<br>                endTimestamp = totalDuration;<br>            }<br><br>            // Submit each segment processing task to the executor<br>            executor.submit(() -&gt; {<br>                try {<br>                    processSegment(filePath, segment, startTimestamp, endTimestamp);<br>                } catch (Exception e) {<br>                    e.printStackTrace();<br>                }<br>            });<br>        }<br><br>        grabber.stop();<br>    } catch (Exception e) {<br>        e.printStackTrace();<br>    }<br>}</pre><h3>Processing Each Segment</h3><p>The processSegment method reads frames from the specified start timestamp and writes them to a new file until the end timestamp is reached. This method demonstrates how to use both FFmpegFrameGrabber and FFmpegFrameRecorder:</p><pre>private static void processSegment(String filePath, int segmentNumber, long startTimestamp, long endTimestamp) {<br>    String outputFileName = &quot;output/segment_&quot; + segmentNumber + &quot;.mp4&quot;; // Define output file name pattern<br><br>    try (FFmpegFrameGrabber grabber = new FFmpegFrameGrabber(filePath);<br>         FFmpegFrameRecorder recorder = new FFmpegFrameRecorder(outputFileName, grabber.getImageWidth(), grabber.getImageHeight())) {<br><br>        grabber.start();<br>        grabber.setTimestamp(startTimestamp); // Seek to start timestamp<br><br>        // Configure recorder settings based on grabber<br>        configureRecorder(recorder, grabber);<br>        recorder.start();<br><br>        Frame frame;<br>        while ((frame = grabber.grabFrame()) != null &amp;&amp; grabber.getTimestamp() &lt; endTimestamp) {<br>            recorder.record(frame); // Record frame to output file<br>        }<br><br>        recorder.stop();<br>        grabber.stop();<br>    } catch (Exception e) {<br>        e.printStackTrace();<br>    }<br>}</pre><h3>Configuring the Recorder</h3><p>The configureRecorder method applies the video and audio settings from the grabber to the recorder to ensure consistency:</p><pre>private static void configureRecorder(FFmpegFrameRecorder recorder, FFmpegFrameGrabber grabber) {<br>    recorder.setFormat(&quot;mp4&quot;);<br>    recorder.setFrameRate(grabber.getFrameRate());<br>    recorder.setVideoBitrate(grabber.getVideoBitrate());<br>    recorder.setVideoCodec(avcodec.AV_CODEC_ID_H264);<br>    recorder.setPixelFormat(avutil.AV_PIX_FMT_YUV420P);<br>    recorder.setAudioChannels(grabber.getAudioChannels());<br>    recorder.setSampleRate(grabber.getSampleRate());<br>    recorder.setAudioBitrate(grabber.getAudioBitrate());<br>    recorder.setAudioCodec(grabber.getAudioCodec());<br>}</pre><h3>Main Method</h3><p>Finally, adjust the main method to initialize the ExecutorService and wait for all tasks to complete:</p><pre>public static void main(String[] args) {<br>    ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());<br>    String videoFilePath = &quot;path/to/your/video.mp4&quot;; // Adjust this to your video file path<br><br>    splitVideo(videoFilePath, executor);<br><br>    executor.shutdown();<br>    try {<br>        executor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);<br>    } catch (InterruptedException e) {<br>        e.printStackTrace();<br>    }<br>}</pre><h3>Step 4: Multithreading for Efficiency</h3><p>Multithreading can significantly speed up the process of video segmentation by allowing multiple segments of the video to be processed simultaneously. Given that video processing is both CPU and I/O intensive, taking advantage of concurrent execution can lead to substantial performance improvements, especially on modern multi-core processors. Here’s how to integrate multithreading into your video segmentation process with JavaCV and FFmpeg:</p><h4>Understanding the ExecutorService</h4><p>Java’s ExecutorService provides a framework for managing a pool of threads and executing tasks asynchronously. By using an ExecutorService, you can submit tasks to be executed by a thread pool without having to manage the lifecycle of threads manually. This is particularly useful for our video segmentation task, where each segment can be processed independently of the others.</p><h4>Implementing Multithreading in Video Segmentation</h4><ol><li>Initialize the ExecutorService:</li></ol><p>Choose a fixed thread pool size that matches your system’s capabilities. Using Runtime.getRuntime().availableProcessors() gives you a pool size equal to the number of available CPU cores, which is a good starting point.</p><pre>ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());</pre><p>Submit Tasks for Each Segment:</p><p>Divide the total video duration by the desired number of segments to calculate the duration of each segment. Then, for each segment, submit a task to the ExecutorService that processes the video frames for that segment. This involves setting the start time for the FFmpegFrameGrabber, grabbing frames until the segment&#39;s end time is reached, and using an FFmpegFrameRecorder to write those frames to a new file.</p><pre>for (int segment = 0; segment &lt; TOTAL_SEGMENTS; segment++) {<br>    final long startTimestamp = segment * segmentDuration;<br>    final long endTimestamp = (segment + 1) * segmentDuration;<br>    <br>    executor.submit(() -&gt; {<br>        processSegment(filePath, segment, startTimestamp, endTimestamp);<br>        return null; // Callable must return something, so return null for void methods<br>    });<br>}</pre><p>Wait for All Tasks to Complete:</p><p>After submitting all segment processing tasks, use executor.shutdown() to prevent new tasks from being submitted and executor.awaitTermination() to wait for all tasks to finish. This ensures that your application does not proceed until all video segments have been processed.</p><pre>executor.shutdown();<br>executor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS); // Wait indefinitely for all tasks to complete</pre><h4>Considerations for Multithreading</h4><ul><li>I/O Bound vs. CPU Bound: If your processing is more I/O bound (e.g., reading and writing large files), increasing the number of threads beyond the number of CPU cores might improve performance. Conversely, for CPU-bound tasks, sticking to the number of cores as the pool size is usually optimal.</li><li>Resource Management: Ensure that resources like FFmpegFrameGrabber and FFmpegFrameRecorder instances are properly managed within each task, using try-with-resources or similar constructs to guarantee that resources are released.</li><li>Error Handling: Implement proper error handling within each task to manage exceptions without crashing the entire application. Consider using futures to retrieve task outcomes and handle exceptions.</li><li>Performance Tuning: The optimal number of threads and the size of video segments for processing can vary based on the specific characteristics of the video files and the hardware. Experiment with different configurations to find the best balance for your needs.</li></ul><p>By applying multithreading to video segmentation, you can significantly reduce processing time, making your application more efficient and responsive, especially when dealing with large video files or high volumes of video content.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b19692db438d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to use AWS SES  to receive emails from your website (Lambda , ApiGateway)]]></title>
            <link>https://medium.com/@fajrimoad/how-to-use-aws-ses-to-receive-emails-from-your-website-lambda-apigateway-efb5a73267ed?source=rss-86ce35ae453------2</link>
            <guid isPermaLink="false">https://medium.com/p/efb5a73267ed</guid>
            <category><![CDATA[api-getway]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Fajrimoad]]></dc:creator>
            <pubDate>Sun, 05 Nov 2023 12:52:43 GMT</pubDate>
            <atom:updated>2023-11-05T12:52:43.944Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to use AWS SES to receive emails from your website (Lambda , ApiGateway)</h3><p>Sometimes when we build a website we need to receive emails in a contact form so we give the user the possibility to send us a mail from the website , in this tutorial we will see how to do that , here the process that we will implement :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/820/1*snhCFX4Jf-lLf1KwKeqIMg.png" /><figcaption>Sending a mail from Website to a 3rd party email</figcaption></figure><p>First of all you must create a domain in Route53 domain if you want to use a ses email sender that is linked to your domain if that is not the case you can use directly another configuration for the email sended as e will see later.</p><p>After the creation and the validation of your domain that can take some time you can then create then verify your domain</p><h3>Verifications in AWS SES :</h3><h4>Go to verified identities in the left menu</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QD8cJrb_9KdWq2SWNlbs2Q.png" /></figure><h4>Verify the domain by adding to your route53 the right dns entries :</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sAOCnQrkbZLhJCgxYuosjg.png" /></figure><h4>Verify your email address that is your destination</h4><p>you will receive a link to activate your email once you verify in the aws console.</p><h3>Create your back end Lambda function with this code as exemple :</h3><pre>import boto3<br>import json<br>import logging<br><br># Configure logging<br>logger = logging.getLogger()<br>logger.setLevel(logging.INFO)<br><br>def send_email(event, context):<br>    ses = boto3.client(&#39;ses&#39;, region_name=&#39;ap-south-1&#39;)<br><br>    # Check if the &#39;body&#39; attribute exists in the event<br>    if &#39;body&#39; in event:<br>        request_body = json.loads(event[&#39;body&#39;])<br>        <br>        # Log the parsed request body<br>        logger.info(f&#39;Parsed request body: {request_body}&#39;)<br><br>        # Extract values from the request body<br>        name = request_body.get(&#39;name&#39;, &#39;Name not provided&#39;)<br>        email = request_body.get(&#39;email&#39;, &#39;Email not provided&#39;)<br>        message = request_body.get(&#39;message&#39;, &#39;Message not provided&#39;)<br><br>        # Construct the HTML email body with the extracted information<br>        email_body = f&#39;&lt;p&gt;&lt;strong&gt;Name:&lt;/strong&gt; {name}&lt;/p&gt;&#39;<br>        email_body += f&#39;&lt;p&gt;&lt;strong&gt;Email:&lt;/strong&gt; {email}&lt;/p&gt;&#39;<br>        email_body += f&#39;&lt;p&gt;&lt;strong&gt;Message:&lt;/strong&gt; {message}&lt;/p&gt;&#39;<br><br>        # Update the email subject<br>        email_subject = f&#39;Demande devis - {name}&#39;<br><br>        source_email = &#39;your_source_email@example.com&#39;  # Replace with your source email<br>        destination_email = &#39;your_destination_email@example.com&#39;  # Replace with your destination email<br><br>        response = ses.send_email(<br>            Source=source_email,<br>            Destination={<br>                &#39;ToAddresses&#39;: [destination_email]<br>            },<br>            Message={<br>                &#39;Subject&#39;: {<br>                    &#39;Data&#39;: email_subject<br>                },<br>                &#39;Body&#39;: {<br>                    &#39;Html&#39;: {<br>                        &#39;Data&#39;: email_body<br>                    }<br>                }<br>            }<br>        )<br><br>        # Create the response with CORS headers, including &#39;Access-Control-Allow-Credentials&#39;<br>        response_headers = {<br>            &#39;Access-Control-Allow-Origin&#39;: &#39;*&#39;,  # Replace with your allowed origin(s)<br>            &#39;Access-Control-Allow-Credentials&#39;: &#39;true&#39;<br>        }<br><br>        return {<br>            &#39;statusCode&#39;: 200,<br>            &#39;headers&#39;: response_headers,<br>            &#39;body&#39;: &#39;Email sent: &#39; + response[&#39;MessageId&#39;]<br>        }<br>    else:<br>        return {<br>            &#39;statusCode&#39;: 400,<br>            &#39;body&#39;: &#39;Bad request: Request body missing or empty&#39;<br>        }</pre><h3>Create A ApiGateway that will route you’re requests and</h3><h4>choose the Integration with LAMBDA :</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bs-lMkto587yAAFEBcKIUQ.png" /></figure><p>This code is an AWS Lambda function that sends an email using Amazon SES (Simple Email Service). It extracts data from an HTTP request’s JSON body, constructs an email with the extracted data, and sends it to a specified destination email address. The Lambda function responds with a message indicating whether the email was successfully sent or if the request body was missing or empty.</p><h4>enable CORS and add the domain that you allow :</h4><h4>add the origins that you accept requests from :</h4><blockquote>exemple : https:// → means all the website with ssl can call the api</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PdKQbTB8QAq7vvm7BzmRWQ.png" /></figure><p>In conclusion, using AWS SES for receiving emails from your website, along with Lambda and API Gateway, is like having a tech-savvy assistant who takes care of your incoming messages. With a little DNS magic, you can validate your domain, and after setting up your Lambda function and API Gateway, you’re all set to handle incoming emails like a pro. And remember, when it comes to CORS, it’s like opening the door to your virtual mailbox and inviting only the friendly websites inside. So, go ahead and embrace the power of AWS SES to keep your website’s inbox organized and your tech-savvy assistant happy!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=efb5a73267ed" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Think and Solve Algorithms & Problems]]></title>
            <link>https://medium.com/@fajrimoad/how-to-think-and-solve-algorithms-problems-1312319b6054?source=rss-86ce35ae453------2</link>
            <guid isPermaLink="false">https://medium.com/p/1312319b6054</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[medium]]></category>
            <dc:creator><![CDATA[Fajrimoad]]></dc:creator>
            <pubDate>Sat, 01 Jul 2023 12:28:12 GMT</pubDate>
            <atom:updated>2023-07-01T12:28:12.766Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iy57ihQJwcbm_uuEy6FFtQ.jpeg" /><figcaption>taken from Pexels</figcaption></figure><p>Sometimes we can feel blocked by the complexity of an algorithm or a problem, especially when we don’t give ourselves enough time to understand the problem and plan our approach. Below are some essential questions and steps we should consider when solving a problem, whether it’s an algorithm or a general issue.</p><p>Understand the problem</p><p>Taking the time to thoroughly understand all aspects of the problem is crucial. In the past, I made the mistake of rushing through this step, which led to missing important details. Complex problems require adequate time for comprehension.</p><p>starting directly can make us consume more time then needed because let’s face some problems are hard to resolve and the demand some time of comprehension.</p><p>Plan the algorithm</p><p>The more complex the problem, the more important it is to break it down into smaller, manageable pieces. Rushing to code without a clear plan can be counterproductive. Instead, we should abstract the solution and use our imagination. Ask yourself these questions:</p><ul><li>What is the core problem we need to solve?</li><li>What makes this problem challenging or complex?</li><li>How can we break down the complex part into smaller subproblems?</li></ul><p>By identifying complexities and breaking them down, we can simplify the problem and develop a clearer plan of action.</p><p>1 — What is the problem :</p><p>sometimes we must see if we respond to the real problem.</p><p>2 — What is complicated in this problem :</p><p>Knowing where the complexity resides makes our brain make more effort on the hard part and simplifies the job for us</p><p>3 — how can i break down the hard part to pieces</p><p>Yes sometimes you can also break down the hard part to parts of the problem , imaginr you are creating a algorithm on score prediction you don’t want to spend time first on where to get real data and other thing but you rather look for that mathematical tool and find tha probability formulas that you will use and know the different case using samples of data.</p><p>4 — Implement the code</p><p>Once we have a well-defined plan and a list of smaller subproblems, we can proceed to implement the code. This approach helps us transform our initial blurred vision into a clear and actionable solution.</p><p>It’s important to remember that effective problem-solving requires patience and a systematic approach. By following these steps, dedicating sufficient time to understanding the problem, and planning our approach, we can improve our chances of finding successful solutions.</p><p>In conclusion, tackling complex problems and algorithms requires a thoughtful and systematic approach. Rushing into coding without fully understanding the problem can lead to wasted time and ineffective solutions. By taking the time to understand the problem, break it down into manageable parts, and plan our approach, we can navigate through the complexities more efficiently. It is essential to ask the right questions, abstract the solution, and use our imagination to devise a clear plan of action. By following these steps and dedicating the necessary time, we increase our chances of finding successful and optimized solutions. Remember, effective problem-solving requires patience, perseverance, and a structured mindset.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1312319b6054" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How To Migrate Your Spring Repositories to Reactive R2DBC Repositories (Mysql DB)]]></title>
            <link>https://medium.com/@fajrimoad/how-to-migrate-your-spring-repositories-to-reactive-r2dbc-repositories-mysql-db-fb961445de6c?source=rss-86ce35ae453------2</link>
            <guid isPermaLink="false">https://medium.com/p/fb961445de6c</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[spring]]></category>
            <dc:creator><![CDATA[Fajrimoad]]></dc:creator>
            <pubDate>Mon, 22 May 2023 09:52:02 GMT</pubDate>
            <atom:updated>2023-05-22T09:53:36.864Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_WAaLRqh4QhANRcuL8HJYw.jpeg" /><figcaption>Photo Of Man Writing On Paper by Vanessa Garcia on Pexels</figcaption></figure><p>We will talk about how to use a reactive repository instead of a normal JPA repository.</p><p>The reactive programming is starting to take a real place in the Java back end frameworks specially in the spring ecosystem , having a back end with a blocking api can cause a lot of latency for a front end application.</p><p>In the process of the refactoring of a spring application the JPA repositories should be replaced with R2DBC repositories in order to have a non-blocking application treatments.</p><p>Here below the database related entity in MySQL 8:</p><p>the entity concerned by the change :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0DvJJQIZXr0Q34sGHk2oag.png" /></figure><p>Post entity</p><p><strong>Spring Version</strong> : Framework 5.x</p><h3>A ) <strong><em>Add the following maven dependencies :</em></strong></h3><pre>        &lt;dependency&gt;<br>            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>            &lt;artifactId&gt;spring-boot-starter-webflux&lt;/artifactId&gt;<br>        &lt;/dependency&gt;<br>  <br>        &lt;dependency&gt;<br>            &lt;groupId&gt;dev.miku&lt;/groupId&gt;<br>            &lt;artifactId&gt;r2dbc-mysql&lt;/artifactId&gt;<br>            &lt;version&gt;0.8.2.RELEASE&lt;/version&gt;<br>        &lt;/dependency&gt;<br><br>        &lt;dependency&gt;<br>         &lt;groupId&gt;io.projectreactor&lt;/groupId&gt;<br>         &lt;artifactId&gt;reactor-core&lt;/artifactId&gt;<br>         &lt;version&gt;3.4.0&lt;/version&gt;<br>        &lt;/dependency&gt;<br></pre><ol><li><strong>spring-boot-starter-webflux</strong>: This is a starter dependency for building reactive web applications using Spring WebFlux. It includes all the necessary components and libraries to develop and run a web</li><li><strong>application with reactive capabilities : </strong>This is an implementation of the R2DBC (Reactive Relational Database Connectivity) driver for MySQL databases. R2DBC is a reactive database access API that allows you to interact with relational databases in a non-blocking and reactive manner. The r2dbc-mysql library provides the necessary components to establish a reactive connection with a MySQL database and perform reactive database operations. It integrates well with Spring Data R2DBC and other reactive frameworks to build scalable and efficient applications.</li><li><strong>reactor-core</strong>: This is the core module of Project Reactor, which is a popular reactive programming library for building non-blocking applications. It provides a set of powerful tools and abstractions for working with reactive streams, such as Flux and Mono, which enable developers to write asynchronous, event-driven, and reactive code. Reactor Core is often used in conjunction with Spring WebFlux to build reactive applications.</li></ol><h3>B ) Transformation of CRUD repositories:</h3><p>In the first part we will remplace the normal Crud (create , update , delete) repositories with the reactive one and later on we will see how to use reactive database client provided by r2dbc-mysql to make some more personalised query functions</p><ol><li><em>Old repository</em></li></ol><pre>package org.sid.repositories;<br><br>import org.sid.entities.Post;<br>import org.springframework.data.jpa.repository.JpaRepository;<br>import org.springframework.stereotype.Repository;<br><br>@Repository<br>public interface PostsRepository extends JpaRepository&lt;Post, Integer&gt; {<br>}</pre><p>2) <em>New r2db repository</em></p><pre>package org.sid.services.repositories;<br><br>import org.sid.services.entities.Post;<br>import org.springframework.data.r2dbc.repository.R2dbcRepository;<br><br>public interface PostsRepository extends R2dbcRepository&lt;Post, Long&gt; {<br>}</pre><p>lets have look of some R2dbcRepository methode :</p><p>The R2dbcRepository interface provides several methods for performing common database operations. Here are some of the most commonly used methods along with their return types:</p><p>Mono&lt;T&gt; findById(ID id) - Retrieves an entity by its ID. Returns a Mono emitting the found entity or an empty Mono if none is found.</p><p>Flux&lt;T&gt; findAll() - Retrieves all entities of the given type. Returns a Flux emitting all the entities.</p><p>Mono&lt;T&gt; save(T entity) - Saves the given entity. Returns a Mono emitting the saved entity.</p><p>Flux&lt;T&gt; saveAll(Iterable&lt;S&gt; entities) - Saves all the given entities. Returns a Flux emitting the saved entities.</p><p>Mono&lt;Long&gt; count() - Returns the number of entities of the given type. Returns a Mono emitting the count.</p><p>3) <em>example of subsription to a returned value </em>:</p><pre>public void getPostById(Long postId) {<br>        Mono&lt;Post&gt; userMono = userRepository.findById(userId);<br>        postMono.subscribe(post -&gt; {<br>            // Process the retrieved user<br>            System.out.println(&quot;post: &quot; + post);<br>        });<br>    }</pre><h3>C ) Using the Database Client to create more complex queries :</h3><p>Given that we have also this entity in our database :</p><pre>package org.sid.services.entities;<br><br>import lombok.*;<br><br>import jakarta.persistence.*;<br>import org.sid.services.enumeration.InteractionType;<br><br><br>@NoArgsConstructor<br>@AllArgsConstructor<br>@Getter<br>@Setter<br>@Builder<br>@Entity<br>@Table(name=&quot;postinteraction&quot;)<br>public class PostInteraction {<br><br>    @Id<br>    @GeneratedValue<br>    public Integer id;<br>    @ManyToOne(targetEntity = Post.class)<br>    @JoinColumn(name = &quot;post_id&quot;, foreignKey = @ForeignKey(name = &quot;postinteraction_post_fk&quot;))<br>    private Post post;<br>    @ManyToOne(targetEntity = User.class)<br>    @JoinColumn(name = &quot;user_id&quot;, foreignKey = @ForeignKey(name = &quot;postinteraction_user_fk&quot;))<br>    private User user;<br>    @Column(name = &quot;interactionType&quot;)<br>    public InteractionType interactionType;<br>    public String comment;<br><br>}</pre><p>we can create the following class where we will inject our clientDatabase to do more fancy stuff :</p><pre>package org.sid.services.repositories.reactive;<br>import io.r2dbc.spi.Row;<br><br><br>import org.sid.services.entities.Post;<br>import org.sid.services.entities.PostInteraction;<br>import org.sid.services.entities.User;<br>import org.sid.services.enumeration.InteractionType;<br>import org.springframework.beans.factory.annotation.Autowired;<br>import org.springframework.r2dbc.core.DatabaseClient;<br>import org.springframework.stereotype.Repository;<br>import reactor.core.publisher.Flux;<br><br>@Repository<br>public class PostInteractionReactiveRepository {<br><br>    private final DatabaseClient databaseClient;<br><br>    @Autowired<br>    public PostInteractionReactiveRepository(DatabaseClient databaseClient) {<br>        this.databaseClient = databaseClient;<br>    }<br><br>    public Flux&lt;PostInteraction&gt; getLikePostInteractionWithUserId(Integer postId, Integer userId) {<br>        return databaseClient.sql(&quot;SELECT * FROM postinteraction WHERE post_id = :post_id &quot; +<br>                        &quot;AND user_id = :user_id AND (interaction_type = 0 OR interaction_type = 1)&quot;)<br>                .bind(&quot;post_id&quot;, postId)<br>                .bind(&quot;user_id&quot;, userId)<br>                .map((row, rowMetadata) -&gt; mapRowToPostInteraction(row))<br>                .all();<br>    }<br><br>    private PostInteraction mapRowToPostInteraction(Row row) {<br>        // Map the row data to a PostInteraction object<br>        // Example:<br>        return PostInteraction.builder()<br>                .id(row.get(&quot;id&quot;, Integer.class))<br>                .post(row.get(&quot;post&quot;, Post.class))<br>                .user(row.get(&quot;user&quot;, User.class))<br>                .interactionType(row.get(&quot;interactionType&quot;, InteractionType.class))<br>                .comment(row.get(&quot;comment&quot;, String.class))<br>                // Map other columns as needed<br>                .build();<br>    }<br>}</pre><p>This class is a Spring @Repository component called PostInteractionReactiveRepository. It uses the DatabaseClient from r2dbc.core for executing SQL queries and mapping the results to PostInteraction objects.</p><ol><li>The PostInteractionReactiveRepository class is annotated with @Repository to indicate that it is a repository component.</li><li>It has a constructor that receives a DatabaseClient instance, which is autowired for dependency injection.</li><li>The getLikePostInteractionWithUserId method executes a SQL query using databaseClient.sql to retrieve post interactions based on a specific postId and userId.</li><li>The retrieved rows are mapped to PostInteraction objects using the mapRowToPostInteraction method, which creates a PostInteraction object by extracting values from the row.</li></ol><p>By using DatabaseClient, you can perform more complex database operations by writing custom SQL queries and mapping the results to your desired objects. It provides a low-level API for interacting with the database, allowing you to have fine-grained control over the queries and result mapping.</p><h3><strong>Conclusion</strong></h3><p>In conclusion, migrating your Spring repositories to Reactive R2DBC repositories for a MySQL database can bring significant benefits to your application. By embracing reactive programming and leveraging the power of R2DBC, you can achieve better scalability, improved performance, and enhanced responsiveness.</p><p>The migration process involves updating your repository interfaces to extend R2dbcRepository instead of JpaRepository, allowing you to take advantage of reactive capabilities. You&#39;ll also need to modify your database configuration to use R2DBC and ensure the necessary dependencies are included in your project.</p><p>With Reactive R2DBC repositories, you can leverage non-blocking I/O and reactive streams to handle database interactions efficiently, resulting in better resource utilization and reduced latency. This is particularly advantageous in scenarios where high concurrency and real-time responsiveness are crucial.</p><p>Furthermore, the use of DatabaseClient provided by R2DBC allows for more flexibility in executing custom SQL queries and mapping the results to domain objects. This empowers developers to tackle complex database operations and optimize performance based on specific application requirements.</p><p>Migrating to Reactive R2DBC repositories may require some effort and adjustments, but the benefits it brings in terms of scalability, performance, and responsiveness make it a worthwhile investment. Embracing reactive programming and leveraging the capabilities of R2DBC can pave the way for building highly responsive and scalable applications in the Spring ecosystem.</p><p>#Scalability #PerformanceOptimization #ResponsiveApplications #Spring #Web</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fb961445de6c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>