<?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 Prashant Gangwar on Medium]]></title>
        <description><![CDATA[Stories by Prashant Gangwar on Medium]]></description>
        <link>https://medium.com/@prashant007?source=rss-8cbab4b93379------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*WVvnOe-5axCV_4pXyqzBTg@2x.jpeg</url>
            <title>Stories by Prashant Gangwar on Medium</title>
            <link>https://medium.com/@prashant007?source=rss-8cbab4b93379------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 05:48:05 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@prashant007/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How I Passed the HashiCorp Terraform Associate (004) Exam in 3 Weeks]]></title>
            <link>https://prashant007.medium.com/how-i-passed-the-hashicorp-terraform-associate-004-exam-in-3-weeks-e61bf32eee96?source=rss-8cbab4b93379------2</link>
            <guid isPermaLink="false">https://medium.com/p/e61bf32eee96</guid>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[hashicorp]]></category>
            <category><![CDATA[certification]]></category>
            <category><![CDATA[ibm]]></category>
            <dc:creator><![CDATA[Prashant Gangwar]]></dc:creator>
            <pubDate>Tue, 06 Oct 2026 19:57:52 GMT</pubDate>
            <atom:updated>2026-10-06T19:57:52.770Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A step-by-step preparation guide covering theory, hands-on AWS practice, high-yield HCP Terraform topics, and what to expect on exam day.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dl_BT8IyuaU7v-jrN3eLdw.png" /></figure><h3>🏆 Verified Credly Badge</h3><p>You can verify my official <strong>HashiCorp Certified: Terraform Associate (004)</strong> certification on Credly below:</p><p>👉 <a href="https://www.credly.com/badges/f3c6d5e7-3144-4520-803e-b1fc1d056935"><strong>View My Verified Credly Badge</strong></a></p><p>Passing the <strong>HashiCorp Certified: Terraform Associate (004)</strong> exam doesn’t require years of multi-cloud experience. With a structured 3-week plan, a focus on hands-on labs, and attention to key exam objectives, you can earn your badge on the first attempt.</p><p>Here is the exact playbook I used to go from basic Infrastructure as Code (IaC) concepts to certified in 21 days.</p><p><strong>My 3-Week Study Roadmap</strong></p><p><strong>Week 1: Core Concepts &amp; Setting Up the AWS Lab</strong></p><ul><li><strong>Theory:</strong> Understand IaC principles, declarative vs. imperative approaches, provider architecture, and the basic Terraform workflow (init, plan, apply, destroy).</li><li><strong>Practical Setup:</strong> Sign up for an <strong>AWS Free Tier account</strong>. Install the Terraform CLI locally and configure AWS credentials using aws configure.</li><li><strong>Hands-on:</strong> Practice writing simple HCL configurations to launch EC2 instances, S3 buckets, and security groups. Experimenting with real infrastructure makes concepts like state tracking and resource dependencies click immediately.</li></ul><p><strong>Week 2: Deep Dive into Modules, State, and Variables</strong></p><ul><li><strong>Modules:</strong> Master module inputs, outputs, local vs. remote sourcing, and version pinning.</li><li><strong>State Management:</strong> Learn how Terraform state works, backend configuration (e.g., S3 + DynamoDB for state locking), state migration, and CLI state commands (terraform state list, terraform state show).</li><li><strong>Variables &amp; Data Sources:</strong> Practice working with complex variable types (map, list, object), dynamic blocks, local values, and fetching external data via data blocks.</li></ul><p><strong>Week 3: HCP Terraform Focus &amp; Practice Exams</strong></p><ul><li><strong>HCP Terraform (High-Yield Topic):</strong> The 004 exam places significant emphasis on <strong>HCP Terraform (formerly Terraform Cloud)</strong>. Focus on:</li><li>Workspaces vs. Projects structure.</li><li>Sentinel and OPA policy enforcement (spec compliance vs. cost guardrails).</li><li>VCS integrations, remote runs, and variable sets.</li><li>Difference between HCP Terraform and Terraform Enterprise.</li><li><strong>Practice Practice Practice:</strong> Take timed practice exams to get comfortable with question formats (multiple-choice, multiple-select, true/false).</li></ul><p><strong>Key Recommendations &amp; Lessons Learned</strong></p><ol><li><strong>Prioritize Hands-on Over Pure Reading:</strong> Do not rely solely on video courses or documentation. Creating resources, encountering errors, and inspecting terraform.tfstate manually solidifies your understanding far better than memorizing syntax.</li><li><strong>Master HCP Terraform:</strong> Do not skip this section. It makes up a substantial portion of the exam questions. Set up a free HCP Terraform account and connect a GitHub repository to trigger a remote run.</li><li><strong>Course Resources:</strong></li></ol><ul><li>Official HashiCorp Learn Tutorials (Terraform Associate 004 Study Guide).</li><li>Video Courses on <a href="https://www.udemy.com/course/hashicorp-certified-terraform-associate-004">Udemy</a> or YouTube (e.g., Bryan Krausen or Zeal Vora).</li></ul><p><strong>How to Book the Exam</strong></p><ol><li>Visit the <a href="https://developer.hashicorp.com/certifications"><strong>HashiCorp Portal</strong></a></li><li>Select <strong>Terraform Associate (004)</strong> and click to schedule.</li><li>Create or log in to your account on the testing platform (Certiverse).</li><li>Choose an online proctored slot, complete the system check, and submit payment ($70.50 USD).</li><li>After payment you will get a email with the confirmation of the slot for the scheduled day of exam.</li></ol><p><strong>The Exam Day Experience-</strong></p><p>You should join the exam before 15 mins of the schedule time, from the email you can get the link or login to certiverse, select exam and start the exam (button will be enabled just before 15 mins).</p><p>Make sure you don’t have any electronic devices in room like — mobile, earphones, smart watch etc.</p><p>Laptop should’ve camera, audio, mic and supported brower to make process of exam smoother.</p><p>Clean your desk as much you can above and under both places.</p><ul><li><strong>Format:</strong> Online proctored, 60 minutes.</li><li><strong>Navigation Feature:</strong> You can <strong>flag questions for review</strong>. If a question seems tricky or time-consuming, flag it and move on. Complete all clear questions first, then review flagged ones before submitting.</li><li><strong>Submission &amp; Instant Feedback:</strong> Once you hit submit, you will be prompted to complete a brief feedback survey about the exam experience.</li><li><strong>Immediate Result:</strong> Right after the survey, your <strong>Pass/Fail</strong> status displays on the screen.</li><li><strong>Post-Exam:</strong> Within 24–48 hours, you’ll receive a detailed performance breakdown report by email, alongside an official digital badge issued by <strong>Credly</strong>, ready to share on LinkedIn and Twitter.</li></ul><p>In this whole process of registering and starting the exam, I would suggest to use same email/account everywhere, otherwise sometime detailed report for the result gets delayed and you may need to raise an ticket to terraform team to merge your accounts and than only you will get the details report.</p><p>Here’s my creds — <a href="https://www.credly.com/users/prashant.gangwar/badges/credly">https://www.credly.com/users/prashant.gangwar/badges/credly</a></p><p>Thank you so much for taking the time to read through this guide! I hope this study roadmap and tips give you a clear direction for your preparation.</p><p>If you have any questions, need clarification on specific topics, or want help with your study plan, <strong>please feel free to drop a comment below</strong> — I’d love to help out and answer your queries!</p><p>Best of luck with your preparation and your exam. You’ve got this — go earn that HashiCorp badge! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e61bf32eee96" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AWS S3 Files Explained — Did It Just Replace EFS?]]></title>
            <link>https://prashant007.medium.com/s3-just-killed-efs-everything-you-need-to-know-about-the-new-s3-files-4e11751dedb6?source=rss-8cbab4b93379------2</link>
            <guid isPermaLink="false">https://medium.com/p/4e11751dedb6</guid>
            <category><![CDATA[aws-s3]]></category>
            <category><![CDATA[cloud]]></category>
            <category><![CDATA[aws-s3-files]]></category>
            <category><![CDATA[amazon-web-services]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Prashant Gangwar]]></dc:creator>
            <pubDate>Thu, 09 Apr 2026 09:44:55 GMT</pubDate>
            <atom:updated>2026-04-10T06:49:12.476Z</atom:updated>
            <content:encoded><![CDATA[<h3>AWS S3 Files Explained – Did It Just Replace EFS?</h3><p>For years, developers had to choose:</p><p>cheap storage (S3) or a real file system (EFS).</p><p>AWS just removed that tradeoff.</p><p><strong>What is AWS S3 files?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/696/1*OilckLWC605GvtIq9VxwVw.png" /><figcaption>AWS S3 Files Architecture</figcaption></figure><p>S3 Files is a shared file system that connects any AWS compute directly with your data in Amazon S3. It provides fast, direct access to all of your S3 data as files with full file system semantics and low-latency performance, without your data ever leaving S3. That means file-based applications, agents, and teams can now access and work with S3 data as a file system using the tools they already depend on. You no longer need to duplicate your data or cycle it between object storage and file system storage. Now, file-based tools and applications across your organization can work with your S3 data directly from any compute instance, container, and function using the tools your teams and agents already depend on.</p><p>Amazon S3 is the first and only cloud object store that provides fully-featured, <em>high-performance </em>file system access to your data. S3 Files gives you the performance and simplicity of a file system with the scalability, durability, and cost-effectiveness of S3. There are no data silos, no synchronization complexities, and no tradeoffs. File and object storage, together in one place without compromise.</p><p><strong>How does S3 File work?</strong></p><p>Think of S3 files as “Smart Bridge” that makes a standard bucket act like a regular folder on your computer. It gives you the best of both worlds: the massive storage of s3 and the high speed of a local hard drive.</p><ol><li><strong>The “Magic Mirror” (Mounting)<br></strong>When you “mount” S3 Files to your server (like an EC2 instance), it creates a window into your bucket. You can browse through folders and files just like they were actually sitting on your server’s hard drive, even if they are still technically stored in S3.</li><li><strong>The “Fast Lane” (High performance Storage)<br></strong>S3 file doesn’t download whole directory at once Instead: <br><strong><em>On Demand Loading:</em></strong> When you open a file, it quickly pulls a copy into special high performance storage(a super-fast cache).<br><strong><em>The 128KB rule: </em></strong>It handles small files differently than big ones. Small files(&lt;128 KB) stay in fast cache because they need to open instantly. Files(&gt;128 KB) these are streamed directly from S3.</li><li><strong>Writing and syncing<br></strong>When you save a new file or edit an old one:</li></ol><ul><li>You save it directly to the <strong>fast storage</strong> (so it feels instant).</li><li>In the background, S3 Files <strong>automatically uploads</strong> it back to your S3 bucket.</li><li>It handles the “translation” for you — turning your computer’s “Save” command into an S3 “Upload” command.</li></ul><p><strong>4. Automatic Cleanup:<br></strong>If you haven’t touched a file in a while (default 30 Days), it deletes the copy from the fast storage. The “master copy” is always safe in your s3 bucket, if you ever need it again, it just pulls it back into the fast lane.</p><blockquote>S3 Files is like having a huge warehouse (S3) and a small, fast delivery van (the file system). The van only brings the items you currently need to your front door. If you stop using an item, the van takes it back to the warehouse to keep your driveway clear.</blockquote><p><strong>What’s new ?</strong></p><p>S3 is no longer just a passive bucket, it’s now a high-performance file system and an AI engine.</p><ul><li><strong>Amazon S3 Files (Launched April 8, 2026):</strong> It allows compute resources (EC2, Lambda, Containers) to mount S3 buckets as native file systems (NFS v4.1). No more copying data between EBS/EFS and S3.</li><li><strong>S3 Vectors (General Availability):</strong> S3 now natively supports vector embeddings (up to 1 billion). This allows developers to build RAG (Retrieval-Augmented Generation) systems directly on S3 data without a separate vector database like Pinecone or weaviate.</li><li><strong>The End of Global Uniqueness: </strong>In a massive legacy shift, AWS introduced Account Regional Namespaces. You can now name a bucket my-app-data even if another user globally has that same name, as long as it’s unique within your account and region.</li><li><strong>50 TB Object Limit: </strong>The maximum size for a single object has jumped from 5 TB to 50 TB, specifically to handle massive AI training datasets.</li></ul><p><strong>Working with S3 Files:</strong></p><p>Prerequisite -</p><ul><li>You’ve an AWS Account.</li><li>You’ve a compute resource and an S3 general purpose bucket in your desired AWS Region where you want to create your file system.</li><li>Your S3 bucket has versioning enabled. S3 Files requires S3 Versioning to synchronize changes between your file system and your S3 bucket. For more information, see Enabling versioning on buckets.</li><li>Your S3 bucket must use one of the following encryption types: Server-side encryption with Amazon S3 managed keys (SSE-S3) or Server-side encryption with AWS Key Management Service (AWS KMS) keys (SSE-KMS).</li></ul><p><strong>Steps to Create S3 Files from Amazon Console —</strong></p><ol><li>Login to AWS Console, search for S3 than on the left panel you will see S3 Files ( Different view may contain in another place too).</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/310/1*nvOf9sOWxenFH83MuMQCaQ.png" /></figure><p>2. When you click on S3 Files you will see the below view —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WudfR9BN7X4Kj-OgPw9jXA.jpeg" /><figcaption>S3 Files View in AWS Console</figcaption></figure><p>3. You can create S3 file system by clicking “Create File System” which will be later shown to the grid available here. When you will create the file system it will create Mount Target also in all Availability Zones for the region.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r0uROzwCx-VCaqWF_xLwPQ.jpeg" /><figcaption>Create File System</figcaption></figure><p>4. Once all Mount Targets are available you will see the attach Option in Compute Resources (EC2, Lambda and ECS Tasks)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PdeFIM73KNnBbf6R3x8BvA.jpeg" /></figure><p>To use S3 Files with Amazon EC2, you must install the client amazon-efs-utils, a shared opensource collection of tools for Amazon EFS and Amazon S3 Files. To work with S3 Files, you need amazon-efs-utils version 3.0.0 or above. The client includes a mount helper program that simplifies mounting S3 file systems and enables Amazon CloudWatch metrics for monitoring your file system’s mount status.</p><pre>sudo yum -y install amazon-efs-utils<br><br>Or<br><br>curl https://amazon-efs-utils.aws.com/efs-utils-installer.sh | sudo sh -s -- --install</pre><p><em>Switch to S3 Files if you’re currently wasting money on EFS for read-heavy ML workloads, and to adopt Account Regional Namespaces for all new Infrastructure-as-Code (Terraform/CDK) projects to avoid naming collisions.</em></p><p><strong>Official Documentation —</strong></p><p><a href="https://docs.aws.amazon.com/pdfs/AmazonS3/latest/userguide/s3-userguide.pdf#s3-files-prereq-policies">https://docs.aws.amazon.com/pdfs/AmazonS3/latest/userguide/s3-userguide.pdf#s3-files-prereq-policies</a></p><p>Thank you very much for giving your precious time on this article, Let me know if you’ve any questions about this article. Do Clap if you like the article!</p><p>Follow me more such articles! Happy Learning and coding!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4e11751dedb6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why GPUs Power AI( And why your CPU can’t keep up)]]></title>
            <link>https://prashant007.medium.com/why-gpus-power-ai-and-why-your-cpu-cant-keep-up-02628ef44d15?source=rss-8cbab4b93379------2</link>
            <guid isPermaLink="false">https://medium.com/p/02628ef44d15</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[gpu]]></category>
            <category><![CDATA[cpu-vs-gpu]]></category>
            <dc:creator><![CDATA[Prashant Gangwar]]></dc:creator>
            <pubDate>Tue, 07 Apr 2026 05:55:17 GMT</pubDate>
            <atom:updated>2026-04-07T05:55:17.638Z</atom:updated>
            <content:encoded><![CDATA[<p>Your CPU is powerful — so Why can’t it run AI?</p><p>When people hear about Artificial Intelligence breakthroughs — from Chat GPT to self-driving cars — there’s one silent hero behind the scene: the GPU.<br>But what exactly is a GPU, and why is it suddenly so important?</p><p>💻 CPU vs GPU: The Real Difference</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ms6kA1ZIJQSaC-xY7DxO6Q.png" /><figcaption>CPU vs GPU</figcaption></figure><p>Think of a <strong>CPU (Central Processing Unit)</strong> as a highly skilled manager.</p><ul><li>It handles tasks one at a time</li><li>It’s great at decision-making</li><li>It’s optimized for flexibility and control</li></ul><p>Now imagine a <strong>GPU (Graphics Processing Unit)</strong> as a massive team of workers.</p><ul><li>Thousands of smaller cores</li><li>Can handle many tasks at the same time</li><li>Built for doing repetitive work <em>very fast</em></li></ul><p>👉 In short:</p><ul><li>CPU = Few powerful brains</li><li>GPU = Thousands of small brains working together</li></ul><p><strong>Why CPUs become a bottleneck in AI?</strong></p><p>Even with more cores, CPUs hits the limit.</p><p>❌ 1. Not Built for Repetition<br>AI training repeats the same math millions of times.<br>CPU:</p><ul><li>Optimized for flexibility</li><li>Wastes cycles on control logic</li></ul><h3>❌ 2. Limited Parallelism</h3><p>Even high-end CPUs:<br> Max out at a few dozen cores<br>GPUs:<br> Thousands of cores working together</p><h3>❌ 3. Memory Bottleneck (Critical)</h3><p>AI needs constant data movement.</p><p>CPU:<br>Slower memory access</p><p>GPU:<br>High Bandwidth Memory (HBM)<br>Feeds data extremely fast</p><p>Understanding a GPU with real example —</p><p>Imagine you’re building a simple AI feature: <br>A model that can tell whether an image contains a cat or dog.<br>Sounds simple, right?<br>But this is where GPU shines.</p><p><strong>Step 1 — The Problem</strong></p><p>You have:</p><ul><li>1 million images</li><li>Each image thousand pixels</li><li>Each Pixel — A number</li></ul><p>Your model needs to:</p><ul><li>Look at every image</li><li>Perform Calculations</li><li>Adjust itself( learn)</li><li>Repeat the process thousands of times</li></ul><p>If you use CPU —</p><ul><li>CPU picks one image (or few)</li><li>Processes it step by step</li><li>Moves to the next</li></ul><p>Even with multiple cores you’re limited, processing is still slow, Training might take days or even weeks.</p><p>If you use GPU</p><p>Now the same task on a GPU:</p><ul><li>Instead of 1 image → process <strong>hundreds at once</strong></li><li>Instead of sequential → <strong>parallel computation</strong></li><li>Thousands of cores working together</li></ul><p>👉 Result:<br> Training completes in <strong>hours</strong></p><h3>What’s Actually Happening?</h3><p>Every time the model learns, it performs:</p><ul><li>Matrix multiplications</li><li>Vector operations</li><li>Repetitive math</li></ul><p>This is exactly what GPUs are designed for.</p><p>Modern GPUs like the NVIDIA A100 are optimized to:</p><ul><li>Handle massive matrix operations</li><li>Keep data flowing quickly</li><li>Run thousands of operations simultaneously</li></ul><p>At its core, the difference is simple:</p><ul><li>CPUs are built for <strong>versatility</strong></li><li>GPUs are built for <strong>throughput</strong></li></ul><p>AI doesn’t need:</p><ul><li>A few smart decisions</li></ul><p>It needs:</p><ul><li>Millions of fast, repetitive calculations</li></ul><p>AI didn’t suddenly become intelligent. It became computationally possible. And GPUs are the reason why.</p><p>Modern AI isn’t limited by algorithms — it’s limited by compute.<br>And CPUs, despite their sophistication, simply aren’t built for the kind of parallelism AI demands.</p><p>“The future of AI isn’t just about better models — it’s about better machines to run them.”</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=02628ef44d15" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Configure and build angular application for multiple environments?]]></title>
            <link>https://prashant007.medium.com/how-to-configure-and-build-angular-application-for-multiple-environments-83a4be4c84e3?source=rss-8cbab4b93379------2</link>
            <guid isPermaLink="false">https://medium.com/p/83a4be4c84e3</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[angular-build]]></category>
            <category><![CDATA[angularcustomenvironment]]></category>
            <category><![CDATA[multi-environment]]></category>
            <dc:creator><![CDATA[Prashant Gangwar]]></dc:creator>
            <pubDate>Thu, 16 Jun 2022 15:54:44 GMT</pubDate>
            <atom:updated>2022-06-16T15:54:44.367Z</atom:updated>
            <content:encoded><![CDATA[<p>To start with this topic, I assume you already have one running angular application in which you need to work to setup for multiple environments. If you don’t have already, you can follow one of my article to setup angular application by <a href="https://prashant007.medium.com/create-your-first-angular-app-608a224037c1">click here</a>.</p><p>By default angular app comes with production and development environment setup, you can build for these both environment by running the following command.</p><pre>ng build --prod</pre><p>When you run the above command, content of environments/environment.ts will be replaced by environments/environment.prod.ts this will generate the following structure in your directory dist/{PROJECT_NAME} with some other resources file ex- font files, images etc., content inside the directory is your final build content.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/625/1*fpz-H2HR-3utB0p88CyReA.png" /><figcaption>Generated content by ng build.</figcaption></figure><p><strong>Custom Environments</strong></p><p>Generally enterprise applications contains more environments not just development and production. It might have staging, QA, Release and dev1, dev2, test1, test2 etc. based on your business requirements.</p><p>you can configure ng build command to pick your target environments.</p><p><strong>Creating custom environments</strong></p><p><strong>Custom environment file</strong></p><p>You need to create custom environment files in app environments directory for each environment you need to configure. Lets assume we will create qa, staging, dev1, dev2 and release environment for our application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*MRyi1UjQIN9BsUxMqFyYcQ.png" /><figcaption>Custom Environments Files</figcaption></figure><p>You can put environment specific settings in their respective files. Now you need to configure those environments in angular.json file present in root directory for your project.</p><p><strong>Configuration in </strong><strong>angular.json</strong></p><p>When you open angular.json, you will find “configurations” inside projects/architect/build, this section comes with default configuration for production and development, if you do not see this section, you can add that yourself.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/835/1*0_Vqv6_c4np5MNlqEByjcA.png" /><figcaption>Multi environment in angular.json</figcaption></figure><p><strong>How to use environment specific settings in your code?</strong></p><p>To use environment specific settings , you need to import environment from src/environments/environment in your app.component.ts file, and then you can use environment to get the correct field.</p><pre>import { environment } from &#39;src/environments/environment&#39;;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/659/1*ZQZE4f2XtO-_3_PLmit5sQ.png" /><figcaption>app.component.ts</figcaption></figure><p><strong>Build application for custom environment</strong></p><p>After all configuration you can build your application with custom environment by passing--configuration parameter in ng build command as below-</p><pre>ng build --configuration qa</pre><p>and dist folder will contain your generated application files which you can use for deployment.</p><p><strong>Build application and serve using node server locally</strong></p><p>To serve your application locally on node server, you need more configuration to angular.json under projects/architect/serve, so that it can be run for specific environments.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/821/1*fYrPERDU99RkkkETxPXDmA.png" /><figcaption>ng serve locally for custom environments</figcaption></figure><p>For example I’ve given the setting for “dev1” in “serve” section, to run your application with “dev1” environment, you need to run the following command-</p><pre>ng serve --configuration dev1</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*vEDtnS9kdB8l8UMD55VnTA.png" /><figcaption>Running application result</figcaption></figure><p><strong>Set up scripts in </strong><strong>package.json</strong></p><p>You can set custom scripts in package.json for custom environments for build the application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/823/1*PEgOCJPHv4HG0fc9TohxOw.png" /></figure><p>Now you can run npm run build-qa to build application for qa environment.</p><p>You can download the source code from <a href="https://github.com/pacific007/multi-env-angular">GitHub </a>repository, to download <a href="https://github.com/pacific007/multi-env-angular">click here.</a></p><p><a href="https://github.com/pacific007/multi-env-angular">GitHub - pacific007/multi-env-angular: Set up for multiple environments in Angular Application</a></p><p>Thank you very much for giving your precious time on this article, Let me know if you’ve any questions about this article.</p><p>Please follow me for more such articles. Happy Learning!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=83a4be4c84e3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create your first Angular APP]]></title>
            <link>https://prashant007.medium.com/create-your-first-angular-app-608a224037c1?source=rss-8cbab4b93379------2</link>
            <guid isPermaLink="false">https://medium.com/p/608a224037c1</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[angular-app-development]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Prashant Gangwar]]></dc:creator>
            <pubDate>Thu, 19 May 2022 07:59:23 GMT</pubDate>
            <atom:updated>2022-05-19T07:59:23.137Z</atom:updated>
            <content:encoded><![CDATA[<p>In this tutorial, we’re going to create our first angular application. Before setting up the angular application, we can discuss about some basics and history of AngularJS and Angular framework.</p><p><strong>What is AngularJS?</strong></p><p>AngularJS is a toolset for building the framework most suited to your application development. It is fully extensible and works well with other libraries. Every feature can be modified or replaced to suit your unique development workflow and feature needs.</p><p>AngularJS was a JavaScript-based open-source front-end web framework for developing single-page applications. It was maintained mainly by Google and a community of individuals and corporations. It was initially released in October, 2010 by Google.</p><p><em>AngularJS support has officially ended as of January 2022.</em></p><p>The Angular team recommends upgrading to <a href="https://en.wikipedia.org/wiki/Angular_(web_framework)">Angular (v2+)</a> as the best path forward.</p><p><strong>Angular (v2+)</strong></p><p>Angular (commonly referred to as “Angular 2+” or “Angular CLI”) is a TypeScript-based free and open-source web application framework led by the Angular Team at Google and by a community of individuals and corporations. Angular is a complete rewrite from the same team that built AngularJS. Initial version of Angular was released on September, 2016.</p><p><strong>Angular Versioning</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/848/1*J127-nflmbODatRtP4LMnQ.png" /><figcaption>Angular Versions History</figcaption></figure><p>Enough theory now, lets start with setting up the environment for angular and create your first application.</p><p>To create your angular application we need to install NodeJS server first.</p><p><strong>Installing NodeJS</strong></p><p>Node.js is an open-source and cross-platform JavaScript runtime environment. It is a popular tool for almost any kind of project! Node.js runs the V8 JavaScript engine, the core of Google Chrome, outside of the browser. This allows Node.js to be very performant.</p><p>You can download the NodeJS by <a href="https://nodejs.org/en/download/">click here</a>, download your respective OS version installer. Installers are available for windows, Linux and MacOS.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/980/1*s2bcNnw21eIccYISGQP-BA.png" /><figcaption>NodeJS installers</figcaption></figure><p>NodeJS comes with NPM (Node Package Manager) also, which is very useful for Angular Application. NPM is separate package which updates very frequently, so you can update the package by running the following command from your command prompt.</p><pre>npm install –g npm@latest</pre><p>You can check the version of NodeJS and NPM by the following commands after installing.</p><pre>node -v<br>npm -v</pre><p>After installing NodeJS and NPM, you can also install Angular CLI which is also very useful package for Angular Application.</p><pre>npm install -g <a href="http://twitter.com/angular/cli">@angular/cli</a></pre><p><strong>Create First Angular Application-</strong></p><p>As we’ve installed all required software for creating app, we can start creating the app now.</p><p>1- Create directory for your project ( ex — mkdir angular-demo )</p><p>2- Go inside the directory that you created ( cd angular-demo )</p><p>3- Open the command prompt in current directory then run <strong>ng new my-first-app, </strong>this will create the following project structure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/272/1*R93i03TK5P_4O2gXOxq6Tg.png" /><figcaption>Angular Project Structure</figcaption></figure><p>4- Now go inside the project directory ( cd my-first-app) and run <strong>ng serve</strong> to run your application on your browser — by default it will run on port 4200, if you want to run it on different port then you can use the following command-</p><pre>ng serve --port 4401 </pre><p>After running the above command, you can go to browser and hit the <a href="http://localhost:4401,">http://localhost:4401,</a> if you’ve given custom port while running ng serve command. You should see similar page in the UI from your Angular App. Look and feel of the page can be different based on the version you’re using, so don’t worry on that part.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5qKe3SVyMhEx6ieoRYS41w.png" /><figcaption>AngularApp Running</figcaption></figure><p>Congratulations , you’ve successfully created your first working Angular Application.</p><p><em>You can use any of the IDE from Visual Studio Code, WebStorm, Atom, Sublime Text and any other by your choice, I’m using Visual Studio Code which is free also.</em></p><p>Happy Coding and Keep Learning!!!</p><p>Drop your comments if you’re having any issues or any question.</p><p>Thank you so much for reading this article, Hope this helps you a bit at least.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=608a224037c1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Auditing Request and Response Spring RestTemplate]]></title>
            <link>https://prashant007.medium.com/auditing-request-and-response-spring-resttemplate-48ae4fde39d?source=rss-8cbab4b93379------2</link>
            <guid isPermaLink="false">https://medium.com/p/48ae4fde39d</guid>
            <category><![CDATA[resttemplate]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[interceptors]]></category>
            <category><![CDATA[spring]]></category>
            <dc:creator><![CDATA[Prashant Gangwar]]></dc:creator>
            <pubDate>Wed, 27 Apr 2022 17:54:48 GMT</pubDate>
            <atom:updated>2022-04-27T17:54:48.283Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/648/1*0DJTBE0kDDMJrzIXUI7lPg.png" /><figcaption>Interceptor to log request/response for RestTemplate</figcaption></figure><p>In this tutorial we’re going to learn how can we implement audit of request and response data of services calls exchanged between two servers. We can use interceptor to audit before and after the remote call.</p><p>Following are the steps to add interceptor.</p><p>1- Create an Interceptor<br>2- Configure RestTemplate</p><p><strong>Create an Interceptor</strong></p><p>You’ll need to create one interceptor by implementing the interface <strong><em>ClientHttpRequestInterceptor </em></strong>and implement the <strong><em>intercept </em></strong>method. In the intercept method we will call <strong><em>execute </em></strong>method on ClientHttpRequestExecution to continue the service call and later we will call our AuditService to audit the request/response.</p><pre>@Component<br>public class AuditInterceptor implements ClientHttpRequestInterceptor {</pre><pre>@Autowired<br>public AuditService auditService;</pre><pre>@Override<br>public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {</pre><pre>ClientHttpResponse response = execution.execute(request, body);<br>auditService.auditRequest(request, response, body);</pre><pre>return response;</pre><pre>}</pre><pre>}</pre><p>We’ve Created one service class which will audit the request/response data from service call, in this class you use any mechanism to audit the data. In our class we’ve just logged all data to log file named as <strong>audit.log</strong></p><pre>@Service<br>public class AuditService {</pre><pre>private final Logger log = LoggerFactory.getLogger(AuditService.class);</pre><pre>public void auditRequest(HttpRequest request, ClientHttpResponse response, byte[] body) throws IOException {</pre><pre>log.debug(&quot;========Audit started for request and response from rest Template calls======&quot;);<br>log.debug(&quot;Service URI : {}&quot;, request.getURI());<br>log.debug(&quot;Request Method : {}&quot;, request.getMethod());<br>log.debug(&quot;Headers: {}&quot;, request.getHeaders());<br>log.debug(&quot;Request body: {}&quot;, new String(body, &quot;UTF-8&quot;));</pre><pre>log.debug(&quot;Response Status code: {}&quot;, response.getStatusCode());<br>log.debug(&quot;Response Status text: {}&quot;, response.getStatusText());<br>log.debug(&quot;Response body: {}&quot;, StreamUtils.copyToString(response.getBody(),Charset.defaultCharset()));</pre><pre>log.debug(&quot;========End of request and response audit======&quot;);</pre><pre>}</pre><pre>}</pre><p><strong>Configure RestTemplate</strong></p><p>In this step, we need to register the interceptor to RestTemplate that we created. You can add as many interceptors and spring will chain them together at run time.</p><p>while configuring interceptor we need to ensure that we’ve used correct Request Factory to RestTemplate. <em>Otherwise there would be issue on getting the response body, which you can get only once, so if you get that while auditing the response then you can not get it in actual service from where it is called.</em></p><pre>@Configuration<br>public class ResttemplateConfig {</pre><pre>@Autowired<br>public AuditInterceptor auditInterceptor;</pre><pre>@Bean<br>public RestTemplate restTemplate() {</pre><pre>RestTemplate restTemplate = new RestTemplate();<br>ClientHttpRequestFactory requestFactory = new BufferingClientHttpRequestFactory(new SimpleClientHttpRequestFactory());</pre><pre>restTemplate.setRequestFactory(requestFactory);<br>restTemplate.getInterceptors().add(auditInterceptor);</pre><pre>return restTemplate;</pre><pre>}<br>}</pre><p>You can get the complete source code from GitHub by this <a href="https://github.com/pacific007/spring-resttemplate-interceptor/">link</a>.</p><p>If you have any questions, you can drop comments on the article.</p><p>If this article helps you, Please do like and follow me for more article!!!</p><p><strong><em>Happy Coding and Keep Learning!!!</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=48ae4fde39d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kraft: How to Install Kafka without zookeeper?]]></title>
            <link>https://prashant007.medium.com/kraft-how-to-install-kafka-without-zookeeper-b00eaf5f0f1e?source=rss-8cbab4b93379------2</link>
            <guid isPermaLink="false">https://medium.com/p/b00eaf5f0f1e</guid>
            <category><![CDATA[kafkainstalltion]]></category>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[zookeeper]]></category>
            <category><![CDATA[kafkawithoutzookeeper]]></category>
            <category><![CDATA[kraft-mode]]></category>
            <dc:creator><![CDATA[Prashant Gangwar]]></dc:creator>
            <pubDate>Wed, 30 Mar 2022 19:20:20 GMT</pubDate>
            <atom:updated>2022-03-30T19:20:20.669Z</atom:updated>
            <content:encoded><![CDATA[<p>It is now possible to run Kafka without Apache zookeeper and is called as Kafka Raft metadata mode. It is currently in preview and <strong>should not be used in production environment</strong>. Its available for testing in Kafka release 2.8 and in this tutorial we are using Release 3.1 Kafka.</p><p>When the Kafka cluster is in KRaft mode, it does not store its metadata in zookeeper. In fact, you do not have to run zookeeper at all, because it stores its metadata in a KRaft quorum of controller nodes.</p><blockquote>There may be bugs, including serious ones. You should <em>assume that your data could be lost at any time</em> if you try the preview release of KRaft mode.</blockquote><p>Here are the steps to install and run Kafka without zookeeper :</p><p>1- Install WSL 2 (Windows subsystem for Linux)<br>2- Install Java JDK version 11<br>3- Download Apache Kafka from <a href="https://kafka.apache.org/downloads">https://kafka.apache.org/downloads</a><br>4- Generate a cluster ID and format the storage using <strong>kafka-storage.sh </strong><br>5- Start Kafka using the binaries in another process in WSL 2</p><p><strong>1- Install WSL 2</strong></p><p>WSL 2 is Windows Subsystem for Linux 2 and provides a Linux environment for your Windows computer that does not require a virtual machine.</p><p>To install WSL 2, make sure you’re on Windows 10 version 2004 and higher or window 11, you can check your windows version by running the command <strong>winver </strong>in Command Prompt</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/458/1*CahAXzGNXDWwG194ReCd5g.png" /></figure><p>You can now install everything you need to run Windows Subsystem for Linux (WSL) by entering this command in an administrator PowerShell or Windows Command Prompt and then restarting your machine.</p><blockquote>wsl --install -d Ubuntu</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/983/1*W-H71kQ_6WDhuYvBeJlNIg.png" /><figcaption>WSL command Installed Ubuntu</figcaption></figure><p>After running this command , it will take some time to download and install WSL on your system. After Installing it will ask for setting up the username and password, you can write any username/password, this is not necessary to match it up with your current windows password.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K36sT2-VdG2ASCiHxudl_A.png" /></figure><p><strong>2- Install Java JDK 11 on WSL</strong></p><ul><li>wget -O- https://apt.corretto.aws/corretto.key | sudo apt-key add —</li><li>sudo add-apt-repository ‘deb https://apt.corretto.aws stable main’</li><li>sudo apt-get update; sudo apt-get install -y java-11-amazon-corretto-jd</li></ul><p>After running these commands you can run the <strong>java -version </strong>to check the installed version.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/757/1*SJNJ5_V_ejs9d-uqPrifkA.png" /></figure><p><strong>3- Download Apache Kafka</strong></p><p>wget <a href="https://dlcdn.apache.org/kafka/3.1.0/kafka-3.1.0-src.tgz">https://dlcdn.apache.org/kafka/3.1.0/kafka-3.1.0-src.tgz</a><br>tar -xzf kafka-3.1.0-src.tgz</p><p>Kafka download will be expanded to kafka-3.1.0-src directory .</p><p><strong>4- Generate a cluster ID</strong></p><p>You need to generate an ID for your new cluster, using the Kafka storage tool:</p><pre> cd kafka-3.1.0-src/bin<br>./kafka-storage.sh random-uuid</pre><p>This returns a UUID for example , eOwRQ-yMThaVuEslgP4CAA</p><p>You might encounter the following error while running above command to get the cluster ID.</p><pre>Classpath is empty. Please build the project first e.g. by running &#39;./gradlew jar -PscalaVersion=2.13.6&#39;</pre><p>To fix this error we need to run the following commands —</p><pre>cd kafka-3.1.0-src<br>./gradlew jar -PscalaVersion=2.13.6</pre><p>Next format your storage directory by the following command-</p><pre>./kafka-storage.sh format -t &lt;&lt;REPLACE_WITH_UUID&gt;&gt; -c ../config/kraft/server.properties</pre><p><strong>5- Start Kafka</strong></p><pre>cd kafka-3.1.0-src/bin<br>./kafka-server-start.sh ../config/kraft/server.properties</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GmlnTvSmiHzrsWSlGVJPWQ.png" /></figure><p>Don’t close this window as it will shutdown the broker. ( Default port is 9092)</p><p><strong>Congratulation, the Kafka broker is now running without zookeeper in Kraft mode!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b00eaf5f0f1e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is ObjectId in MongoDB?]]></title>
            <link>https://prashant007.medium.com/what-is-objectid-in-mongodb-2eaf7fae0d7?source=rss-8cbab4b93379------2</link>
            <guid isPermaLink="false">https://medium.com/p/2eaf7fae0d7</guid>
            <category><![CDATA[nosql]]></category>
            <category><![CDATA[unique]]></category>
            <category><![CDATA[objectid]]></category>
            <category><![CDATA[nosql-database]]></category>
            <category><![CDATA[mongodb]]></category>
            <dc:creator><![CDATA[Prashant Gangwar]]></dc:creator>
            <pubDate>Mon, 18 Oct 2021 12:33:21 GMT</pubDate>
            <atom:updated>2021-10-18T12:33:21.656Z</atom:updated>
            <content:encoded><![CDATA[<p>ObjectIds are small, likely unique, fast to generate, and ordered.</p><p>In MongoDB, each document stored in a collection requires a unique _id field that acts as a primary key. If an inserted document omits the _id field, the MongoDB driver automatically generates an ObjectId for the _id field.</p><p>It can be of length 24 byte hex string, 12 byte binary string.</p><p><strong>How ObjectId calculated in MongoDB?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CQgMf8_N5MmW6D7Dl71Ebw.jpeg" /></figure><p>ObjectId values are 12 bytes in length, MongoDB driver generates ObjectId automatically if omit from document data which consist of the following :</p><ul><li>a 4-byte <em>timestamp value</em>, representing the ObjectId’s creation, measured in seconds since the Unix epoch(which will not run out of seconds until the year 2106)</li><li>a 5-byte <em>random value</em> generated once per process. This random value is unique to the machine and process. ( consist of 3 byte machine id — usually derived by MAC address and 2 byte process id)</li><li>a 3-byte <em>incrementing counter</em>, initialized to a random value</li></ul><p>While the BSON format itself is little-endian, the <em>timestamp</em> and <em>counter</em> values are big-endian, with the most significant bytes appearing first in the byte sequence.</p><p><strong>How to get the timestamp from ObjectID?</strong></p><p>ObjectId(“507c7f79bcf86cd7994f6c0e”).getTimestamp() this will return the following output:<br> ISODate(&quot;2012-10-15T21:26:17Z&quot;)</p><p>You can refer official MongoDB article about ObjectId by the following link:</p><p><a href="https://docs.mongodb.com/manual/reference/method/ObjectId/#mongodb-method-ObjectId">https://docs.mongodb.com/manual/reference/method/ObjectId/#mongodb-method-ObjectId</a></p><p>Hope this articles helped you to understand the MongoDB ObjectId.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2eaf7fae0d7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cloning in JAVA]]></title>
            <link>https://prashant007.medium.com/cloning-in-java-8fd503e85040?source=rss-8cbab4b93379------2</link>
            <guid isPermaLink="false">https://medium.com/p/8fd503e85040</guid>
            <category><![CDATA[shallow-copy]]></category>
            <category><![CDATA[cloning]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[cloneable]]></category>
            <category><![CDATA[deep-copy]]></category>
            <dc:creator><![CDATA[Prashant Gangwar]]></dc:creator>
            <pubDate>Mon, 11 Oct 2021 19:54:33 GMT</pubDate>
            <atom:updated>2021-10-12T09:03:58.549Z</atom:updated>
            <content:encoded><![CDATA[<p>Cloning is a way to create exact copy of the object. It creates a new instance of object with all fields from the original object, and there is no operator for copying an object in JAVA — the assignment operator duplicates the reference, not the object. The clone() method provides the missing functionality.<br><em>By default java cloning is ‘field by field copy’ or shallow copy of object.</em></p><p><strong>Java Cloneable Interface and clone() method-</strong></p><p>1- You must implement Cloneable interface <br>2- you must override clone() method from object class.</p><pre>protected Object clone() throws CloneNotSupportedException</pre><p>The class Object does not itself implement the interface Cloneable, so calling the clone method on an object whose class is Object will result in throwing an exception at run time.</p><p><strong>Code Example of Cloning —</strong></p><pre>class CloneTesting implements Cloneable {<br>      int objectId;<br>      String objectName;<br>      <br>      CloneTesting(int id, String name) {<br>         this.objectId = id;<br>         this.objectName = name;<br>      }<br>      <br>      @Override<br>      protected Object clone() throws CloneNotSupportedException    <br>      {<br>         return super.clone();<br>      }</pre><pre>public static void main(String[] args) {</pre><pre>try {</pre><pre>CloneTesting object = new CloneTesting(1, &quot;Object A&quot;);</pre><pre>CloneTesting clonedObject = (CloneTesting) object.clone();</pre><pre>CloneTesting referenceObject = object;</pre><pre>// object and referenceObject are pointing to same object</pre><pre>System.out.println(&quot;Reference equality : &quot; + (object.equals(referenceObject)));</pre><pre>// object and referenceObject are pointing to same object (compared by hashCode() method)</pre><pre>System.out.println(&quot;Hashcode of Original Object   : &quot; + object.hashCode());</pre><pre>System.out.println(&quot;Hashcode of referenced Object : &quot; + referenceObject.hashCode());</pre><pre>System.out.println(</pre><pre>&quot;Assigning object equality test result : &quot; + (object.hashCode() == referenceObject.hashCode()));</pre><pre>System.out.println(&quot;-----------------Cloning---------------------&quot;);</pre><pre>// object and clonedObject are two different object (created by java cloning)</pre><pre>System.out.println(&quot;Hashcode of Original Object   : &quot; + object.hashCode());</pre><pre>System.out.println(&quot;Hashcode of cloned Object : &quot; + clonedObject.hashCode());</pre><pre>System.out.println(&quot;Cloned object equality test result : &quot; + (object.hashCode() == clonedObject.hashCode()));</pre><pre>} catch (CloneNotSupportedException e) {</pre><pre>e.printStackTrace();</pre><pre>}</pre><pre>}</pre><pre>}</pre><p><strong>Output </strong>—</p><pre>Reference equality : true<br>Hashcode of Original Object   : 1829164700<br>Hashcode of referenced Object : 1829164700<br>Assigning object equality test result : true<br>-----------------Cloning---------------------<br>Hashcode of Original Object   : 1829164700<br>Hashcode of cloned Object : 2018699554<br>Cloned object equality test result : false</pre><p><strong>Types of Cloning —</strong></p><p>1- Shallow Copy (default in JAVA)<br>2- Deep Copy</p><p><strong>Shallow Copy-</strong></p><p>Shallow clone is default implementation of JAVA. If you’re not cloning all the object types, then you’re making a shallow copy of the object. In this above example we’ve created a shallow copy of object.</p><pre>class Mercedes implements Cloneable {</pre><pre>String model;</pre><pre>Owner owner;</pre><pre>public Mercedes(String model, Owner owner) {</pre><pre>this.model = model;</pre><pre>this.owner = owner;</pre><pre>}</pre><pre>/**</pre><pre>* @return the model</pre><pre>*/</pre><pre>public String getModel() {</pre><pre>return model;</pre><pre>}</pre><pre>/**</pre><pre>* @return the owner</pre><pre>*/</pre><pre>public Owner getOwner() {</pre><pre>return owner;</pre><pre>}<br>/**</pre><pre>* @param owner the owner to set</pre><pre>*/</pre><pre>public void setOwner(Owner owner) {</pre><pre>this.owner = owner;</pre><pre>}</pre><pre>@Override</pre><pre>protected Object clone() throws CloneNotSupportedException {</pre><pre>return super.clone();</pre><pre>}</pre><pre>public static void main(String[] args) {</pre><pre>Owner owner = new Owner(&quot;ABC&quot;);</pre><pre>Mercedes mercedes1 = new Mercedes(&quot;Benz&quot;, owner);</pre><pre>// Now we will create clone of this object</pre><pre>try {</pre><pre>Mercedes mercedes2 = (Mercedes) mercedes1.clone();</pre><pre>// mercedes1 and mercedes2 are now two different object</pre><pre>System.out.println(&quot;Mercedes1 Object Owner Name : &quot; + mercedes1.getOwner().getName());</pre><pre>System.out.println(&quot;Mercedes2 Object Owner Name : &quot; + mercedes2.getOwner().getName());</pre><pre>/*</pre><pre>* But now if we change the owner name in first object, it would be reflected in</pre><pre>* second object also because its a shallow copy and it will just have reference</pre><pre>* of object not new object itself.</pre><pre>*/</pre><pre>mercedes1.getOwner().setName(&quot;Updated Name&quot;);<br>System.out.println(&quot;Names after update in owner of first object.&quot;);<br>System.out.println(&quot;Mercedes1 Object Owner Name : &quot; + mercedes1.getOwner().getName());</pre><pre>System.out.println(&quot;Mercedes2 Object Owner Name : &quot; + mercedes2.getOwner().getName());</pre><pre>} catch (CloneNotSupportedException e) {</pre><pre>e.printStackTrace();</pre><pre>}</pre><pre>}</pre><pre>}</pre><pre><strong>Owner.java</strong></pre><pre>public class Owner {</pre><pre>private String name;</pre><pre>public Owner(String owner) {</pre><pre>this.name = owner;</pre><pre>}</pre><pre>/**</pre><pre>* @return the name</pre><pre>*/</pre><pre>public String getName() {</pre><pre>return name;</pre><pre>}</pre><pre>/**</pre><pre>* @param name the name to set</pre><pre>*/</pre><pre>public void setName(String name) {</pre><pre>this.name = name;</pre><pre>}</pre><pre>}</pre><p>Output —</p><pre>Mercedes1 Object Owner Name : ABC<br>Mercedes2 Object Owner Name : ABC<br>Names after update in owner of first object.<br>Mercedes1 Object Owner Name : Updated Name<br>Mercedes2 Object Owner Name : Updated Name</pre><p><strong>Deep Copy —</strong></p><p>In deep copy, we create a clone which is independent of object and making changes in cloned object should not affect original object.</p><pre>@Override</pre><pre>protected Object clone() throws CloneNotSupportedException {</pre><pre>Mercedes cloned = (Mercedes) super.clone();</pre><pre>cloned.setOwner((Owner) cloned.getOwner().clone());</pre><pre>return cloned;</pre><pre>}</pre><pre><strong>Owner.java Implement Cloneable</strong> </pre><pre>@Override</pre><pre>protected Object clone() throws CloneNotSupportedException {</pre><pre>return super.clone();</pre><pre>}</pre><p>In this way we can achieve deep copy of objects.</p><p>There are third party libraries available which you can use for deep cloning ex- Apache Commons , SerializationUtils</p><blockquote>No constructor is called on the object being cloned.</blockquote><p>Feel free to drop comments if you have any questions on this article.</p><p>Keep Learning!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8fd503e85040" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Serialization and Deserialization in JAVA]]></title>
            <link>https://prashant007.medium.com/serialization-and-deserialization-in-java-ce3fe636da88?source=rss-8cbab4b93379------2</link>
            <guid isPermaLink="false">https://medium.com/p/ce3fe636da88</guid>
            <category><![CDATA[serialization]]></category>
            <category><![CDATA[deserialization]]></category>
            <category><![CDATA[objectorientedprogramming]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Prashant Gangwar]]></dc:creator>
            <pubDate>Fri, 08 Oct 2021 19:20:57 GMT</pubDate>
            <atom:updated>2021-10-08T19:20:57.173Z</atom:updated>
            <content:encoded><![CDATA[<p>Serialization is the way to transform objects into a byte stream. so that it can be store in some persistent storage. Deserialization is the just opposite of what serialization does, convert byte streams to the object. The Serialization process is instance independent. Objects can be serialized on one platform and deserialized on another.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/824/1*K3QCcRJBG4Z29ISwysacLQ.jpeg" /></figure><p>In this picture left side is the showcase of serialization, where an object is converted into byte stream, which can be stored in any persistent storage like- File, Database, or Memory. And the right side is deserialization where a stream of bytes is read from the storage and converted back to the object.</p><p>Classes that are eligible for serialization need to implement a special <strong>marker interface</strong> <strong>Serializable</strong>.<br>When deserializing the object, it does not use the constructor, it creates an empty object and uses reflection to write the whole data to the field.</p><p>While Serializing the object, the <strong>ObjectInputStream</strong> class writeObject(Object o) method will be used to write the object, while in process of deserializing <strong>ObjectOutputStream</strong> readObject() method will be used.</p><p><strong>Advantage of Serialization —</strong></p><p>1- Save/persist the state of the object<br>2- To travel object on the network</p><p><strong>What is the need for SerialVersionUID?</strong></p><p>The JVM associates a version (long) number with each serializable class. It is used to verify that the saved and loaded objects have the same attributes and thus are compatible with serialization.</p><p>This number can be generated automatically by most IDEs and is based on the class name, its attributes, and associated access modifiers. Any changes result in a different number and can cause an <strong>InvalidClassException</strong>.</p><p>If a serializable class doesn’t declare a serialVersionUID, the JVM will generate one automatically at run-time. However, it is highly recommended that each class declares its serialVersionUID as the generated one is compiler dependent and thus may result in unexpected InvalidClassExceptions.</p><p><strong>Important points to note about Serialization-</strong></p><p>1- Static fields in a class don’t serialize.<br>2- <strong>Transient </strong>keyword is used to make field ignore while serializing ( these will take default value).<br>3- When a class implements a Serializable interface, all its subclasses are serializable as well. When an object has a reference to another object, these objects must implement the serializable interface, or else <strong>NotSerializableException </strong>will be thrown.<br>4- If one of the fields in a serializable object consists of an array of objects, then all these objects must be serializable as well, or else a <strong>NotSerializableException </strong>will be thrown.</p><p><strong>Externalizable in JAVA-</strong></p><p>The Externalizable interface provides the facility of writing the state of an object into a byte stream in compressed format. It is not a marker interface.</p><p>The Externalizable interface provides two methods:</p><ul><li>public void writeExternal(ObjectOutput out) throws IOException</li><li>public void readExternal(ObjectInput in) throws IOException</li></ul><p>Reference- <a href="https://docs.oracle.com/javase/8/docs/api/java/io/Serializable.html">https://docs.oracle.com/javase/8/docs/api/java/io/Serializable.html</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ce3fe636da88" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>