<?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 LOGESH B on Medium]]></title>
        <description><![CDATA[Stories by LOGESH B on Medium]]></description>
        <link>https://medium.com/@logeshbommannan?source=rss-bd4efd57f101------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*HsR2Wn17F6QyqH3z1LSW6g.jpeg</url>
            <title>Stories by LOGESH B on Medium</title>
            <link>https://medium.com/@logeshbommannan?source=rss-bd4efd57f101------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 23:00:09 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@logeshbommannan/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[Axios: onDownloadProgress and onUploadProgress Events | by LOGESH B]]></title>
            <link>https://medium.com/@logeshbommannan/axios-ondownloadprogress-and-onuploadprogress-events-by-logesh-b-3e089e897e87?source=rss-bd4efd57f101------2</link>
            <guid isPermaLink="false">https://medium.com/p/3e089e897e87</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[axios]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[progress-bar]]></category>
            <category><![CDATA[axios-vs-fetch]]></category>
            <dc:creator><![CDATA[LOGESH B]]></dc:creator>
            <pubDate>Sat, 17 Aug 2024 03:01:42 GMT</pubDate>
            <atom:updated>2024-08-17T03:01:42.391Z</atom:updated>
            <content:encoded><![CDATA[<p>When it comes to making HTTP requests in JavaScript, Axios is a powerful and popular library. It provides several features that make it a go-to choice for many developers. Among those features are the onDownloadProgress and onUploadProgress events, which can be incredibly useful for monitoring the progress of data transfers. In this article, we will explore these events, their attributes, and how to use them effectively to enhance the user experience.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vresn9_Hpqnbo0oqI_18ug.png" /></figure><h3>Introduction to Axios:</h3><p>Axios is a promise-based HTTP client for JavaScript, which can be used in both the browser and Node.js environments. It offers a simple API for making HTTP requests, handling responses, and managing errors.</p><h4>Understanding onDownloadProgress and onUploadProgress:</h4><p>When dealing with large files or slow network connections, it is essential to provide users with feedback on the progress of their downloads or uploads. This is where onDownloadProgress and onUploadProgress come into play.</p><h4>onDownloadProgress</h4><p>The onDownloadProgress event is triggered periodically during the download of content from the server. This allows you to track the progress of a download and provide real-time feedback to users.</p><h4>onUploadProgress</h4><p>The onUploadProgress event is triggered periodically during the upload of content to the server. This allows you to track the progress of an upload and provide real-time feedback to users.</p><h3>AxiosProgressEvent Interface</h3><p>Both onDownloadProgress and onUploadProgress utilize the AxiosProgressEvent interface, which provides detailed information about the progress of the operation. Below is the interface definition:</p><pre>export interface AxiosProgressEvent {<br>  loaded: number;<br>  total?: number;<br>  progress?: number;<br>  bytes: number;<br>  rate?: number;<br>  estimated?: number;<br>  upload?: boolean;<br>  download?: boolean;<br>  event?: BrowserProgressEvent;<br>  lengthComputable: boolean;<br>}</pre><h4>Attributes</h4><ul><li><strong>loaded</strong>: The number of bytes downloaded or uploaded so far.</li><li><strong>total</strong>: The total number of bytes to be downloaded or uploaded (if available).</li><li><strong>progress</strong>: The proportion of the transfer completed, typically a value between 0 and 1.</li><li><strong>bytes</strong>: The number of bytes transferred since the last progress event.</li><li><strong>rate</strong>: The transfer rate in bytes per second.</li><li><strong>estimated</strong>: The estimated time remaining in seconds.</li><li><strong>upload</strong>: A boolean indicating if the event is related to an upload.</li><li><strong>download</strong>: A boolean indicating if the event is related to a download.</li><li><strong>event</strong>: The original ProgressEvent from the browser.</li><li><strong>lengthComputable</strong>: A boolean indicating if the total length of the transfer is known.</li></ul><h4>Important Notes</h4><blockquote><strong>Progress Events Frequency:</strong> Progress events are not triggered for each percent of completion. Instead, events may be triggered at intervals such as 2%, 46%, 73%, and 100%, depending on the file size. The number of events triggered can vary.</blockquote><blockquote><strong>Handling Undefined Progress</strong>: Sometimes, you may encounter cases where progress information is undefined, and lengthComputable is false. This typically occurs when using compression techniques that do not always include the Content-Length header in the response. In such cases, you can try setting the Accept-Encoding header to an empty string, although this is not an ideal solution.</blockquote><pre>axios.get(&#39;https://example.com/file.zip&#39;, {<br>    headers: {<br>        &#39;Accept-Encoding&#39;: &#39;&#39;<br>    },<br>    onDownloadProgress: progressEvent =&gt; {<br>        // Handle progress<br>    }<br>})<br>.then(response =&gt; {<br>    console.log(&#39;File downloaded successfully&#39;);<br>})<br>.catch(error =&gt; {<br>    console.error(&#39;Error downloading file:&#39;, error);<br>});</pre><h3>Usage Examples:</h3><h4>Tracking Download Progress:</h4><pre>axios.get(&#39;https://example.com/file.zip&#39;, {<br>    onDownloadProgress: (progressEvent) =&gt; {<br>        const { loaded, total, progress, bytes, rate, estimated, download } = progressEvent;<br>        const percentage = total ? Math.floor((loaded / total) * 100) : null;<br>        console.log(`Download Progress: ${percentage}%`);<br>        console.log(`Bytes downloaded since last event: ${bytes}`);<br>        console.log(`Download rate: ${rate} bytes/second`);<br>        console.log(`Estimated time remaining: ${estimated} seconds`);<br>    }<br>})<br>.then(response =&gt; {<br>    console.log(&#39;File downloaded successfully&#39;);<br>})<br>.catch(error =&gt; {<br>    console.error(&#39;Error downloading file:&#39;, error);<br>});</pre><h3>Tracking Upload Progress</h3><pre>const formData = new FormData();<br>formData.append(&#39;file&#39;, fileInput.files[0]);<br>axios.post(&#39;https://example.com/upload&#39;, formData, {<br>    onUploadProgress: (progressEvent) =&gt; {<br>        const { loaded, total, progress, bytes, rate, estimated, upload } = progressEvent;<br>        const percentage = total ? Math.floor((loaded / total) * 100) : null;<br>        console.log(`Upload Progress: ${percentage}%`);<br>        console.log(`Bytes uploaded since last event: ${bytes}`);<br>        console.log(`Upload rate: ${rate} bytes/second`);<br>        console.log(`Estimated time remaining: ${estimated} seconds`);<br>    }<br>})<br>.then(response =&gt; {<br>    console.log(&#39;File uploaded successfully&#39;);<br>})<br>.catch(error =&gt; {<br>    console.error(&#39;Error uploading file:&#39;, error);<br>});</pre><blockquote>Progress events can also be achieved using the native Fetch API.</blockquote><h3>Fetch API: Tracking Download Progress:</h3><p>The Fetch API allows you to track download progress. Unlike Axios, there is currently no way for Fetch to track upload progress. For that purpose, please use XMLHttpRequest.</p><p>To track download progress, you can use the response.body property. It&#39;s a ReadableStream – a special object that provides the body chunk-by-chunk, as it comes. Readable streams are described in the Streams API specification.</p><p>Unlike response.text(), response.json(), and other methods, response.body gives full control over the reading process, and you can count how much is consumed at any moment.</p><h4>Example: Tracking Download Progress with Fetch</h4><pre>fetch(&#39;https://example.com/file.zip&#39;)<br>    .then(response =&gt; {<br>        const reader = response.body.getReader();<br>        const contentLength = response.headers.get(&#39;Content-Length&#39;);<br><br>        let receivedLength = 0; // received that many bytes at the moment<br>        let chunks = []; // array of received binary chunks (comprises the body)<br>        <br>        return reader.read().then(function processResult(result) {<br>            if (result.done) {<br>                console.log(&#39;Download complete&#39;);<br>                return;<br>            }<br><br>            const chunk = result.value;<br>            chunks.push(chunk);<br>            receivedLength += chunk.length;<br><br>            if (contentLength) {<br>                console.log(`Received ${((receivedLength / contentLength) * 100).toFixed(2)}%`);<br>            } else {<br>                console.log(`Received ${receivedLength} bytes`);<br>            }<br><br>            return reader.read().then(processResult);<br>        });<br>    })<br>    .catch(error =&gt; {<br>        console.error(&#39;Error downloading file:&#39;, error);<br>    });</pre><blockquote>Both Axios and the Fetch API are excellent choices for making HTTP requests in JavaScript. Your choice will depend on your specific needs and preferences. If you need a more feature-rich and user-friendly library, Axios might be the better choice. If you prefer a minimalistic approach with no additional dependencies, the Fetch API is a great option.</blockquote><h3>Conclusion</h3><p>Incorporating onDownloadProgress and onUploadProgress events in Axios can greatly improve the user experience by providing real-time feedback on the status of file transfers. By understanding their attributes and using them effectively, you can create more responsive and user-friendly applications.</p><blockquote><strong><em>References:</em></strong></blockquote><blockquote><a href="https://axios-http.com/docs/req_config">https://axios-http.com/docs/req_config</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3e089e897e87" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Migrating from Spring Boot 2 to Spring Boot 3: Handling javax.persistence]]></title>
            <link>https://blog.stackademic.com/migrating-from-spring-boot-2-to-spring-boot-3-handling-javax-persistence-by-logesh-b-36be728b82f5?source=rss-bd4efd57f101------2</link>
            <guid isPermaLink="false">https://medium.com/p/36be728b82f5</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-cleaning]]></category>
            <category><![CDATA[spring-framework]]></category>
            <category><![CDATA[spring-boot-3]]></category>
            <dc:creator><![CDATA[LOGESH B]]></dc:creator>
            <pubDate>Sun, 24 Sep 2023 13:33:28 GMT</pubDate>
            <atom:updated>2024-09-25T13:17:59.603Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Migrating from Spring Boot 2 to Spring Boot 3: Handling javax.persistence to jakarta.persistence Changes</strong></h3><h3>Introduction:</h3><p>As Spring Boot continues to evolve, developers must stay up-to-date with the latest changes and updates. One of the significant alterations in <strong>Spring Boot 3</strong> involves the shift from javax.persistence to jakarta.persistence for handling annotations related to entities, IDs, and generated values. In this article, we will explore this migration process and address a common issue that may arise during the transition.</p><p><a href="https://differ.blog/differ-ai">Introducing DifferAI</a></p><h4>The Migration Challenge:</h4><p>In <strong>Spring Boot 2</strong>, when working with <strong>MySQL </strong>or other databases, you may have frequently used annotations provided by javax.persistence.*, such as @Entity, @Id, and @GeneratedValue. However, Spring Boot 3 has made a crucial change - it replaces <strong>javax.persistence</strong> with <strong>jakarta.persistence</strong>. As a result, in Spring Boot 3, you need to import annotations from jakarta.persistence instead of javax.persistence.</p><h4>Common Error and Misconception:</h4><p>When migrating to Spring Boot 3, many developers encounter a perplexing error that is not easily resolved by simply adding a Maven dependency:</p><pre>ERROR 22196 — — [ main] <br>o.s.boot.SpringApplication : Application run failed org.springframework.beans.<br>factory.BeanCreationException: Error creating bean with name &#39;myRepo&#39; defined <br>in com.mysqltest.mysqltest.MyRepo defined in @EnableJpaRepositories declared on JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration: <br>Not a managed type: class com.mysqltest.mysqltest.MyEntity</pre><p><strong>Error:Not a managed type: class com.mysqltest.mysqltest.MyEntity</strong></p><p>This error often leaves developers scratching their heads and scouring the internet for solutions. The common recommendation is to verify the annotations, but this may not always lead to a resolution.</p><h4>The Real Issue:</h4><p>The root of this problem lies in the migration from javax.persistence to jakarta.persistence. While it&#39;s tempting to believe that adding the javax.persistence-api dependency with a version like 2.2 would fix the issue, this approach is not sufficient in Spring Boot 3.</p><h3>The Solution:</h3><p>To resolve this issue, developers must explicitly update their codebase to use the jakarta.persistence annotations. Here&#39;s how you can make the necessary changes:</p><ol><li><strong>Update Imports:</strong> In your Java classes, replace all javax.persistence imports with jakarta.persistence. This includes replacing @Entity, @Id, @GeneratedValue, and any other annotations related to persistence.</li><li><strong>Dependency Management:</strong> Ensure that your project’s build tool (Maven or Gradle) uses the latest versions of libraries that are compatible with Spring Boot 3. Specifically, make sure you are using jakarta.persistence dependencies instead of javax.persistence.</li><li><strong>Check External Libraries:</strong> If your project relies on external libraries that use javax.persistence, consider updating or replacing them with versions that are compatible with Spring Boot 3.</li><li><strong>Testing:</strong> Thoroughly test your application to ensure that all changes have been correctly implemented. Pay special attention to database operations and entity management.</li></ol><blockquote><strong><em>Here’s the Sample Updated Entity Class:</em></strong></blockquote><pre>package com.mysqltest.mysqltest;<br><br><br>//Remove the previous imports from javax.presistence<br><br>// import javax.persistence.Column;<br>// import javax.persistence.Entity;<br>// import javax.persistence.GeneratedValue;<br>// import javax.persistence.Id;<br><br><br>import jakarta.persistence.Entity;<br>import jakarta.persistence.GeneratedValue;<br>import jakarta.persistence.Id;<br><br>import lombok.Data;<br><br><br>@Data //It is used to define getter and setter methods.<br>@Entity<br>public class MyEntity {<br><br> <br> @Id //It acts as a primary key<br> @GeneratedValue //It helps Id as an auto Incremented value<br> private Long id;<br><br> private String name;<br> private int runs;<br> private int wickets;<br> private String team;<br> private String iplTeam;<br>}<br></pre><p>In this updated entity class:</p><ul><li>We have removed the previous javax.persistence imports and replaced them with the corresponding jakarta.persistence imports.</li><li>Annotations such as @Entity, @Id, and @GeneratedValue have been updated to their jakarta.persistence equivalents.</li></ul><p>By making these changes, you ensure that your entity class is compatible with Spring Boot 3, and it will work seamlessly with the new version of the framework. This is a crucial step in the migration process, as it allows your application to continue working as expected while benefiting from the latest Spring Boot features and improvements.</p><h4>Conclusion:</h4><p>Migrating from Spring Boot 2 to Spring Boot 3 can be challenging, especially when dealing with changes like the shift from javax.persistence to jakarta.persistence. By following the steps outlined in this article and staying updated with official migration guides, you can ensure a smooth transition and keep your application running flawlessly in Spring Boot 3.</p><blockquote>For more detailed information on the migration process, you can refer to the official Spring Framework 6.x migration guide<em> </em><a href="https://github.com/spring-projects/spring-framework/wiki/Upgrading-to-Spring-Framework-6.x#data-access-and-transactions"><strong><em>SpringBoot Migration</em></strong></a><em>.</em></blockquote><h3>Stackademic 🎓</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a></li><li>Visit our other platforms: <a href="https://plainenglish.io/"><strong>In Plain English</strong></a> | <a href="https://cofeed.app/"><strong>CoFeed</strong></a> | <a href="https://differ.blog/"><strong>Differ</strong></a></li><li>More content at <a href="https://stackademic.com/"><strong>Stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=36be728b82f5" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/migrating-from-spring-boot-2-to-spring-boot-3-handling-javax-persistence-by-logesh-b-36be728b82f5">Migrating from Spring Boot 2 to Spring Boot 3: Handling javax.persistence</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Uploading Files to Google Drive Using Spring Boot: A Step-by-Step Guide [2023] | by LOGESH B]]></title>
            <link>https://medium.com/@logeshbommannan/uploading-files-to-google-drive-using-spring-boot-a-step-by-step-guide-2023-by-logesh-b-9b191b6c1b27?source=rss-bd4efd57f101------2</link>
            <guid isPermaLink="false">https://medium.com/p/9b191b6c1b27</guid>
            <category><![CDATA[drive-api]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[google-drive-api]]></category>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[LOGESH B]]></dc:creator>
            <pubDate>Fri, 14 Jul 2023 16:38:59 GMT</pubDate>
            <atom:updated>2024-08-16T10:35:47.047Z</atom:updated>
            <content:encoded><![CDATA[<h3>Uploading Files to Google Drive Using Spring Boot: A Step-by-Step Guide [2024] | by LOGESH B</h3><h3><strong>Introduction:</strong></h3><p>Google Drive provides a convenient and reliable cloud storage solution, and integrating it with your Spring Boot application can greatly enhance its functionality. In this article, we will walk through the process of setting up a Spring Boot application to upload files to Google Drive. By following these step-by-step instructions, you will be able to authorize your application, create the necessary credentials, and configure the required scopes. Let’s get started!</p><p><strong>Prerequisites:</strong> Before diving into the setup process, make sure you have the following prerequisites in place:</p><ul><li>A Google account with access to the Google Cloud console</li><li>Basic knowledge of Spring Boot and Java programming</li></ul><h3><strong>Step 1:</strong> Creating a Google Cloud Project</h3><ol><li>Go to the Google Cloud console and navigate to the <strong>IAM &amp; Admin</strong> section.</li><li>Click on <strong>“Create a Project”</strong> and provide a descriptive name for your project.</li><li>Optionally, you can edit the<strong> Project ID</strong> if needed.</li><li>Choose the appropriate location for your project and click “<strong>Create</strong>.”</li></ol><h3><strong>Step 2: </strong>Creating the Application and <strong>Enabling the Google Drive API</strong></h3><ol><li>Open your browser and go to the Google Cloud console <strong>(</strong><a href="https://console.developers.google.com/"><strong>https://console.developers.google.com/</strong></a><strong>).</strong></li><li>Create a new application and give it a suitable name, such as “google-api-upload.”</li><li>Once the application is created, you will be redirected to the <strong>APIs &amp; Services</strong> page.</li><li>Click on <strong>“Enable APIs and Services”</strong> and search for the Google Drive API. Enable it.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jf7Ca22Sa5R8Bc3jLZBc5g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hvOKgYNnumf4A64PzToXKA.png" /></figure><h3><strong>Step 3:</strong> Creating Credentials and Configuring the Consent Screen</h3><ol><li>On the Credentials page, click on <strong>“CREATE CREDENTIALS”</strong> at the top left corner.</li><li>Fill in the required information and click on the “What Credentials Do I Need?” button.</li><li>Configure the consent screen by clicking on the <strong>“CONFIGURE CONSENT SCREEN”</strong> button.</li><li>Select the user type as<strong> “External”</strong> and provide the necessary details.</li><li>Save the consent screen and continue to the scopes configuration screen.</li></ol><blockquote><strong><em>Note: Remember to provide the scopes carefully and correctly, based on your project’s specific requirements and access needs.</em></strong></blockquote><p>6. Add or remove scopes based on your project requirements.</p><p>7. Save and continue to the credentials page.</p><h3><strong>Step 4:</strong> Finalizing Credentials</h3><ol><li>Add test users who will have access to the consent screen and Google Drive.</li><li><strong>Save </strong>and <strong>continue</strong> to the final step.</li><li>On the credentials page, you will find the credentials you created. Keep them handy for your Spring Boot application.</li></ol><h3><strong>Step 5:</strong> Creating Credentials to Authorize Your Spring Boot App</h3><p>Now that you have configured the necessary project settings in the Google Cloud console, it’s time to create credentials for your Spring Boot application to authorize it to access Google Drive. Follow these steps to create the credentials:</p><ol><li>In the Google Cloud console, click on <strong>“Credentials” </strong>in the left panel.</li><li>On the Credentials page, click on the<strong> “Create Credentials” </strong>button at the top.</li><li>Select <strong>“OAuth Client ID”</strong> from the dropdown menu.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8NThCVR-0Pc_gnUdZTz7rw.png" /></figure><ol><li>Provide the necessary details for your OAuth client ID, such as a name for the client ID.</li><li>Add the <strong>redirect URI </strong>correctly. Note that for a Spring Boot application running on the default port (8080), the redirect URI would typically be: “<a href="http://localhost:8080/login/oauth2/code/google">http://localhost:8080/login/oauth2/code/google</a>&quot; (replace “8080” with the port number on which your application is running).</li><li>Add the JavaScript origin.</li><li>Click on the <strong>“Create”</strong> button to generate the credentials.</li><li>Download the credentials file as a JSON file, naming it <strong>“credentials.json”</strong> (or any custom name you prefer).</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/968/1*hDqddm6zQJC1tdGDIHyRqg.png" /></figure><p>You have now successfully created the credentials required to authorize your Spring Boot application. The “credentials.json” file contains the necessary information for your application to authenticate with Google Drive.</p><h3><strong>Step 6:</strong> Setting Up the Spring Boot Project</h3><p>To integrate Google Drive functionality into your Spring Boot application, follow these steps:</p><ol><li>Create a new Spring Boot Maven project with a suitable name. In this example, we’ll use <strong>“AudioBook” </strong>as the project name. Adjust it according to your application’s purpose.</li><li>Include the necessary dependencies in your project’s pom.xml file. Add the following dependencies to enable interaction with the Google Drive API:</li></ol><pre>&lt;!-- Google API client --&gt;<br>&lt;dependency&gt;<br>    &lt;groupId&gt;com.google.api-client&lt;/groupId&gt;<br>    &lt;artifactId&gt;google-api-client&lt;/artifactId&gt;<br>    &lt;version&gt;2.0.0&lt;/version&gt;<br>&lt;/dependency&gt;<br><br>&lt;!-- Google OAuth client (Jetty) --&gt;<br>&lt;dependency&gt;<br>    &lt;groupId&gt;com.google.oauth-client&lt;/groupId&gt;<br>    &lt;artifactId&gt;google-oauth-client-jetty&lt;/artifactId&gt;<br>    &lt;version&gt;1.34.1&lt;/version&gt;<br>&lt;/dependency&gt;<br><br>&lt;!-- Google Drive API --&gt;<br>&lt;dependency&gt;<br>    &lt;groupId&gt;com.google.apis&lt;/groupId&gt;<br>    &lt;artifactId&gt;google-api-services-drive&lt;/artifactId&gt;<br>    &lt;version&gt;v3-rev20220815-2.0.0&lt;/version&gt;<br>&lt;/dependency&gt;</pre><ol><li>Create a new folder named “service” inside the src directory. This folder will contain the service classes for interacting with Google Drive.</li><li>Split your routes and controllers by creating two folders named “routes” and “controller” inside the src directory.</li><li>Move the credentials.json file that you downloaded earlier into the &quot;service&quot; folder. This file will be used to authenticate your application with Google Drive.</li></ol><p>Now, let’s proceed with creating the necessary files within each folder:</p><ol><li>Create a new file named GoogleDriveService.java inside the &quot;service&quot; folder. This file will contain the logic for interacting with the Google Drive API.</li><li>Create a new file named AudioBookController.java inside the &quot;controller&quot; folder. This file will handle incoming HTTP requests and delegate the processing to the appropriate service methods.</li><li>Create a new file named AudioBookRoutes.java inside the &quot;routes&quot; folder. This file will define the routes and endpoints for your application.</li></ol><p>Here’s an example code snippet for the GoogleDriveService.java file that interacts with the Google Drive API:</p><pre>package com.audiobook.audiobook.services;<br><br>import com.google.api.client.auth.oauth2.Credential;<br>import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;<br>import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;<br>import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;<br>import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;<br>import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;<br>import com.google.api.client.http.InputStreamContent;<br>import com.google.api.client.http.javanet.NetHttpTransport;<br>import com.google.api.client.json.JsonFactory;<br>import com.google.api.client.json.gson.GsonFactory;<br>import com.google.api.client.util.store.FileDataStoreFactory;<br>import com.google.api.services.drive.Drive;<br>import com.google.api.services.drive.DriveScopes;<br>import com.google.api.services.drive.model.File;<br>import com.google.api.services.drive.model.FileList;<br><br>import java.io.ByteArrayInputStream;<br>import java.io.FileNotFoundException;<br>import java.io.IOException;<br>import java.io.InputStream;<br>import java.io.InputStreamReader;<br>import java.security.GeneralSecurityException;<br>import java.util.Collections;<br>import java.util.List;<br><br>import org.springframework.stereotype.Component;<br>import org.springframework.web.multipart.MultipartFile;<br><br>/* class to demonstrate use of Drive files list API */<br>@Component<br>public class GoogleDriveService {<br>  /**<br>   * Application name.<br>   */<br>  private static final String APPLICATION_NAME = &quot;AudioBook&quot;;<br>  /**<br>   * Global instance of the JSON factory.<br>   */<br>  private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance();<br>  /**<br>   * Directory to store authorization tokens for this application.<br>   */<br>  private static final String TOKENS_DIRECTORY_PATH = &quot;tokens&quot;;<br><br>  /**<br>   * Global instance of the scopes required by this quickstart.<br>   * If modifying these scopes, delete your previously saved tokens/ folder.<br>   */<br>  private static final List&lt;String&gt; SCOPES =<br>      Collections.singletonList(DriveScopes.DRIVE_FILE);<br>  private static final String CREDENTIALS_FILE_PATH = &quot;./credentials.json&quot;;<br><br>  /**<br>   * Creates an authorized Credential object.<br>   *<br>   * @param HTTP_TRANSPORT The network HTTP Transport.<br>   * @return An authorized Credential object.<br>   * @throws IOException If the credentials.json file cannot be found.<br>   */<br>  private static Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT)<br>      throws IOException {<br>    // Load client secrets.<br>    InputStream in = GoogleDriveService.class.getResourceAsStream(CREDENTIALS_FILE_PATH);<br>    if (in == null) {<br>      throw new FileNotFoundException(&quot;Resource not found: &quot; + CREDENTIALS_FILE_PATH);<br>    }<br>    GoogleClientSecrets clientSecrets =<br>        GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));<br><br>    // Build flow and trigger user authorization request.<br>    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(<br>        HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)<br>        .setDataStoreFactory(new FileDataStoreFactory(new java.io.File(TOKENS_DIRECTORY_PATH)))<br>        .setAccessType(&quot;offline&quot;)<br>        .build();<br>    LocalServerReceiver receiver = new LocalServerReceiver.Builder().setPort(8888).build();<br>    Credential credential = new AuthorizationCodeInstalledApp(flow, receiver).authorize(&quot;user&quot;);<br>    //returns an authorized Credential object.<br>    return credential;<br>  }<br><br>  public Drive getInstance() throws GeneralSecurityException, IOException {<br>      // Build a new authorized API client service.<br>      final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();<br>      Drive service = new Drive.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials(HTTP_TRANSPORT))<br>            .setApplicationName(APPLICATION_NAME)<br>            .build();<br>      return service;<br>   }<br><br>//Code needs to be implemented for the uploding a file to drive<br>//uploading functions are as follows as <br>//Using this code snippet you can do all drive functionality<br>//getfiles()<br>//uploadFile()<br><br><br>}<br></pre><p>Make sure to update the following values in the code:</p><ul><li>APPLICATION_NAME: Replace with the name of your application that you provided in the Google Cloud Console.</li><li>TOKENS_DIRECTORY_PATH: Provide the appropriate path to the directory where you want to store the API auth tokens. Ensure that the directory exists within your project.</li><li>CREDENTIALS_FILE_PATH: Update with the correct path and file name of your credentials.json file.</li></ul><p>Additionally, customize the SCOPES list according to your project&#39;s requirements. These scopes determine the level of access and permissions your application will have when interacting with Google Drive.</p><p><strong>Note:</strong> If you encounter any errors or issues, double-check the correctness of the paths, scopes, and configuration of your Google Drive API project.</p><p>Below is the code for uploading a file and getting a list of files in Google Drive:</p><pre>public  String getfiles() throws IOException, GeneralSecurityException {<br>  <br>    Drive service = getInstance();<br><br>    // Print the names and IDs for up to 10 files.<br>    FileList result = service.files().list()<br>        .setPageSize(10)<br>        .execute();<br>    List&lt;File&gt; files = result.getFiles();<br>    if (files == null || files.isEmpty()) {<br>      System.out.println(&quot;No files found.&quot;);<br>      return &quot;No files found.&quot;;<br>    } else {<br>      return files.toString();<br>    }<br>  }<br><br><br>public String uploadFile(MultipartFile file) {<br>  try {<br>    System.out.println(file.getOriginalFilename());<br><br>     String folderId = &quot;your_folder_id&quot;;<br>     if (null != file) {<br>        File fileMetadata = new File();<br>        fileMetadata.setParents(Collections.singletonList(folderId));<br>        fileMetadata.setName(file.getOriginalFilename());<br>        File uploadFile = getInstance()<br>              .files()<br>              .create(fileMetadata, new InputStreamContent(<br>                    file.getContentType(),<br>                    new ByteArrayInputStream(file.getBytes()))<br>              )<br>              .setFields(&quot;id&quot;).execute();<br>              System.out.println(uploadFile);<br>        return uploadFile.getId();<br>     }<br>  } catch (Exception e) {<br>     System.out.printf(&quot;Error: &quot;+ e);<br>  }<br>  return null;<br>}<br><br></pre><p>In the code snippet above, make sure to update the following values:</p><ul><li>FOLDER_ID: Replace with the ID of the folder in Google Drive where you want to upload the file.</li></ul><p>These methods allow you to upload a file using the uploadFile method and retrieve a list of files in Google Drive using the getFiles method.</p><p>Here’s an code for the AudioBookController.java class:</p><pre>package com.audiobook.audiobook.controller;<br><br>import java.io.IOException;<br>import java.security.GeneralSecurityException;<br><br>import org.springframework.beans.factory.annotation.Autowired;<br>import org.springframework.stereotype.Component;<br>import org.springframework.web.multipart.MultipartFile;<br><br><br>import com.audiobook.audiobook.services.GoogleDriveService;<br><br>@Component<br>public class AudioBookController {<br><br>    @Autowired<br>    private GoogleDriveService service;<br><br>    public String getAllAudio() throws IOException, GeneralSecurityException{<br>        return service.getfiles();<br>    }<br>    public String uploadAudio(MultipartFile file) throws IOException, GeneralSecurityException{<br>        System.out.println(file.getOriginalFilename());<br><br>        return service.uploadFile(file);<br>    }<br>    <br>}</pre><p>In this code snippet, the AudioBookController class is a controller component that handles the business logic for audio book operations.</p><p>The getAllAudio method uses the GoogleDriveService to retrieve the list of files from Google Drive by calling the getFiles method.</p><p>The uploadAudio method uses the GoogleDriveService to upload the provided audio file to Google Drive by calling the uploadFile method.</p><p>Make sure to adjust and customize the code based on your application’s specific requirements and functionality.</p><p>Here’s an code for the AudioBookRoutes.java class:</p><pre>package com.audiobook.audiobook.routes;<br><br><br>import java.io.IOException;<br>import java.security.GeneralSecurityException;<br><br>import org.springframework.beans.factory.annotation.Autowired;<br>import org.springframework.web.bind.annotation.CrossOrigin;<br>import org.springframework.web.bind.annotation.GetMapping;<br>import org.springframework.web.bind.annotation.PostMapping;<br>import org.springframework.web.bind.annotation.RequestParam;<br>import org.springframework.web.bind.annotation.RestController;<br>import org.springframework.web.multipart.MultipartFile;<br><br>import com.audiobook.audiobook.controller.AudioBookController;<br><br><br>@RestController<br>public class AudioBookRoutes {<br><br>    @Autowired<br>    AudioBookController audioBookController;<br><br><br>    @GetMapping(&quot;/&quot;)<br>    public  String sample() throws IOException, GeneralSecurityException{<br>        return audioBookController.getAllAudio();<br>    }<br><br>    @PostMapping(&quot;/newaudio&quot;)<br>    @CrossOrigin(origins = &quot;http://127.0.0.1:5173/&quot;)<br>    public  String upload(@RequestParam(&quot;audio&quot;) MultipartFile file) throws IOException, GeneralSecurityException{<br>        return audioBookController.uploadAudio(file);<br>    }<br>}</pre><p>In this code snippet, the AudioBookRoutes class is a REST controller that handles the HTTP endpoints for the audio book operations. It autowires an instance of AudioBookController to handle the business logic.</p><p>The sample method is an example of a GET request endpoint (&quot;/&quot;) that returns a string response, which you can customize based on your requirements.</p><p>The upload method is an example of a POST request endpoint (&quot;/newaudio&quot;) that accepts a MultipartFile parameter for the uploaded audio file. It calls the uploadAudio method in the AudioBookController to handle the file upload logic.</p><p>Note the usage of @CrossOrigin(origins = &quot;http://127.0.0.1:5173&quot;) annotation, which allows cross-origin requests from the specified origin. Make sure to update the origin value with the appropriate domain or IP address from which you will make the requests.</p><blockquote><strong><em>When you access the routes you defined, such as </em></strong><strong><em>/newaudio for uploading an audio file or </em></strong><strong><em>/ for retrieving the list of files, the application will prompt you to authorize your app with the Google Drive API. Click &quot;Continue&quot; and follow the authorization process to grant the necessary permissions.</em></strong></blockquote><blockquote><em>Remember to adjust and customize the code based on your application’s specific requirements and functionality.</em></blockquote><p>Now that you have completed the setup and implementation of your Spring Boot application for uploading and retrieving files from Google Drive, you can run the application and start interacting with the Google Drive API.</p><p>Once authorized, you will be able to access Google Drive and perform file upload and retrieval operations using the respective routes.</p><blockquote><strong>If you encounter any errors during the authorization process or while accessing Google Drive, double-check the correctness of your redirect URI and other credentials. Ensure that they match the configurations you made in the Google Cloud console and your Spring Boot application.</strong></blockquote><blockquote><strong>Now, you can test your application by uploading audio files, retrieving the list of files, and exploring the functionalities you have implemented. Have fun exploring and using your Spring Boot application integrated with Google Drive!</strong></blockquote><blockquote><strong>References:</strong></blockquote><blockquote><a href="https://developers.google.com/drive/api/quickstart/java">https://developers.google.com/drive/api/quickstart/java</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9b191b6c1b27" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>