Wednesday, August 12, 2020

[Interview Question ][Data Structure] Two Sum Problem -Array

Two sum problem is one of the most asked data structure questions for a java developer interview. There could be one or more ways to solve the problem but i am trying to give the optimized solution to this problem.



Lets first see the Problem Statement.

Problem Statement - Given an array, We need to find all the possible sets of 2 elements whose sum is equal to the target sum.


Solution: Given an array, lets say [10,-2,5,3,1,7,4] and given a target = 8 , We need to find all the possible 2 elements whose sum is equal to the 8.

the possible output will be 

[10,-2] ,[5,3],[1,7]


Pseudo code- 

  • Lets first sort the array.
  • After sorting, take 2 pointers, one is leftmost & second is rightmost.
  • we will start taking each element from left & right then check some of both the element.
  • If the sum is less then the target sum, then move the left pointer by one.
  • if the sum is greater than the target sum, then move the right pointer to left by one.
  • else if it is equal to target then put the elements one result array and move both left & right pointer by one.
Now let see the Java implementations.






public class TwoSumProblem {
	
	public static void main(String[] args) {
		int[] arr = {10,-2,5,3,1,7,4};
		
		twoSumArray(arr,8);
	}
	
	public static void twoSumArray(int[] arr, int i) {
		
//		sort the array using Arrays  sort
		
		Arrays.sort(arr);
		int size = arr.length;
		int left = 0;
		int right =size-1;
		List<Integer> list = new ArrayList<Integer>();
		
		while(left<right) {
			int diff = arr[left]+arr[right];
			if(diff<i) {
				left++;
			}else if(diff>i) {
				right--;
			}else {
				list.add(arr[left]);
				list.add(arr[right]);
				left++;
				right--;
			}
		}
		
		for(Integer it : list) {
			System.out.println(it);
		}
	}


If you run this program you will get the list of sub set whose sume is equal to 8.


Hope this will help you in your datastructre problem solving.

Thanks for reading.

Thursday, June 25, 2020

[Multi threading Interview Question ]Rate Limiter Implementation in java

There was one interesting problem I have encounter while preparing for a multithreading coding interview.


Question: We have an application for which we need to implement RateLimiter, 
Rate Limiter is an interface which will play a role to limit the number of Request client send to Server in a given time.

In the Current Question, it was asked to implement a rate limit who will do 2 things.

1) It will only allow one client to send 100 requests in 1 hrs. ( one client will be identified by the client Id).
2) It will allow a total of 10000 requests to be passed to the server in 1 hrs.

Rate Limiter Interface 
interface RateLimiter{

boolean accept(String clientId);
}

Java Implementation of Rate Limiter 

When we need to Implement such things where there is any restriction of accessing the resource for limited count We always start thinking using Semaphores  
Why Semaphores? 
Because it maintains the multi-access locking on its own with defined number of threads to access the critical section.

MyRateLimiter.java

class MyRateLimiter  {
 
 
    private Semaphore semaphore;
    private int maxPermits;
    private TimeUnit timePeriod;
    private ScheduledExecutorService scheduler;
    
    
 
    public static MyRateLimiter create(int permits, TimeUnit timePeriod) {
    MyRateLimiter limiter = new MyRateLimiter(permits, timePeriod);
        limiter.schedulePermit();
        return limiter;
    }
 
    private MyRateLimiter(int permits, TimeUnit timePeriod) {
        this.semaphore = new Semaphore(permits);
        this.maxPermits = permits;
        this.timePeriod = timePeriod;
    }
 
    public boolean tryAcquire() {
        return semaphore.tryAcquire();
    }
 
    public void stop() {
        scheduler.shutdownNow();
    }
 
    public void schedulePermit() {
        scheduler = Executors.newScheduledThreadPool(1);
        scheduler.scheduleAtFixedRate(() -> {
            semaphore.release(maxPermits - semaphore.availablePermits());
        }, 0, 1, timePeriod);
 
    }

 }

 RateLimiterImpl.java

	class RateLimiterImpl implements RateLimiter{

private static long MINUTE_TIME_LIMIT=1000*60L; // update as per question
private static long REQUEST_ALLOWED_PER_MINUTE=10000; // Update as per question
Queue<Long> q = new LinkedList<>();
private static int minuteLimit=100;

private Map<String, Optional<MyRateLimiter>> limiters = new ConcurrentHashMap<>();
     
@Override
public boolean accept(String clientId) {
if(!hit(System.currentTimeMillis())) {
return false;
}
Optional<MyRateLimiter> rateLimiter = getRateLimiter(clientId);
if(rateLimiter.isPresent()) {
boolean canAcquire= rateLimiter.get().tryAcquire();
if(canAcquire)
return q.add(System.currentTimeMillis());
}
return false;
}
private boolean hit(long timestamp) {
while(!q.isEmpty() && timestamp-q.peek() >= MINUTE_TIME_LIMIT) q.poll();
if(q.size() < REQUEST_ALLOWED_PER_MINUTE)
{
q.offer(timestamp); 
return true;
}
return false;
}
private Optional<MyRateLimiter> getRateLimiter(String clientId) {
        return limiters.computeIfAbsent(clientId, id -> {
            return Optional.of(createRateLimiter(id));
            
        });
    }
private MyRateLimiter createRateLimiter(String clientId) {
        return MyRateLimiter.create(minuteLimit, TimeUnit.MINUTES);
    }

}

Main Class Calling

public class RateLimiterDemo {


public static void main(String[] args) {

RateLimiter limiter = new RateLimiterImpl();
        System.out.println("test1 " + limiter.accept("test1"));
        System.out.println("test1 " +limiter.accept("test1"));
        System.out.println("test1 " +limiter.accept("test1"));
        System.out.println("test1 " +limiter.accept("test1"));
        System.out.println("test2 " +limiter.accept("test2"));
        System.out.println("test2 " +limiter.accept("test2"));
        System.out.println("test2 " +limiter.accept("test2"));
        System.out.println("test2 " +limiter.accept("test2"));
        System.out.println("test1 " +limiter.accept("test1"));


}

}

You can also check the Code from HERE 

Hope this will help you in understanding the Code

Tuesday, June 16, 2020

101 Most Useful Websites on Internet


The Most Useful Websites and Web Apps


  1. archive.is— take a snapshot of any web page and it will exist forever even if the original page is gone.
  2. autodraw.com — create freehand doodles and watch them magically transform into beautiful drawings powered by maching learning.
  3. fast.com  — check the current speed of your Internet connection.
  4. slides.com  — create pixel-perfect slide decks and broadcast your presentations to an audience of any size from anywhere.
  5. screenshot.guru — take high-resolution screenshots of web pages on mobile and desktops.
  6. dictation.io  – accurate and quick voice recognition in your browser itself.
  7. reverse.photos — upload an image and find similar pictures on the web.
  8. copychar.cc – copy special characters and emojis that aren’t on your keyboard.
  9. codeacademy.com  – the best place to learn coding online.
  10. noisli.com  — ambient noises to help you improve focus and boost productivity.
  11. iconfinder.com  – millions of icons for all kinds of projects. Also try icons8.com 39 and laticon.com 36.
  12. jotti.org  – scan any suspicious file or email attachment for viruses.
  13. wolframalpha.com  – gets answers directly without searching – see more wolfram tips.
  14. flightstats.com  – track flight status at airports worldwide.
  15. unsplash.com  – the best place to download images absolutely free.
  16. videos.pexels.com  — an online library of free HD videos you can use everywhere. Also see videvo.net 76.
  17. everytimezone.com  – a less confusing view of the world time zones.
  18. e.ggtimer.com  – a simple online timer for your daily needs.
  19. random.org  – pick random numbers, flip coins, and more.
  20. earn.com  — replace your email with a mailbox that pays when you reply to someone’s email.
  21. myfonts.com/WhatTheFont  – upload an image of any text and quickly determine the font family.
  22. fonts.google.com  – the best collection of open source fonts that you can use anywhere without restrictions.
  23. fontstruct.com  — draw and build your own fonts and use them in any application.
  24. calligraphr.com  — transform your handwriting into a real font.
  25. regex.info – find data hidden in your photographs – see more EXIF tools.
  26. youtube.com/webcam  — broadcast yourself live over the Internet without any complicated setup.
  27. remotedesktop.google.com  — access other computers or allow others to remote access your computer over the Internet.
  28. homestyler.com  – design from scratch or re-model your home in 3D.
  29. pdfescape.com  – lets you quickly edit PDF in the browser without Acrobat.
  30. draw.io  – create diagrams, wireframe and flowcharts in the browser.
  31. web.skype.com  — make voice and video calls in your browser with Skype.
  32. onlineocr.net  – recognize text from scanned PDFs – see other OCR tools.
  33. wetransfer.com  – for sharing really big files online.
  34. file.pizza — peer to peer file transfer over WebRTC without any middleman.
  35. snapdrop.com  — like Apple AirDrop but for the web. Share files directly between devices in the same network without having to upload them to any server first.
  36. hundredzeros.com  – the site lets you download free Kindle books.
  37. app.grammarly.com  — check your writing for spelling, style, andgrammatical errors.
  38. noteflight.com  – print music sheets, write your own music online ( review).
  39. translate.google.com  – translate web pages, PDFs and Office documents.
  40. kleki.com  – create paintings and sketches with a wide variety of brushes.
  41. similarsites.com  – discover new sites that are similar to what you like already.
  42. bubbl.us  – create mind-maps, brainstorm ideas in the browser.
  43. color.adobe.com  – get color ideas, also extract colors from photographs.
  44. canva.com  — make beautiful graphics, presentations, resumes and more with readymade template designs.
  45. lmgtfy.com  – when your friends are too lazy to use Google on their own.
  46. midomi.com  – when you need to find the name of a song.
  47. history.google.com  — see all your past Google searches, also among most important Google RLs
  48. faxzero.com  – send an online fax for free – see more fax services.
  49. tinychat.com  – setup your own private chat room in micro-seconds.
  50. privnote.com  – create text notes that will self-destruct after being read.
  51. domains.google.com  – quickly search domain names for your next big idea!
  52. downforeveryoneorjustme.com  – find if your favorite website is offline or not?
  53. gtmetrix.com  – the perfect tool for measuring your site performance online.
  54. builtwith.com  — find the web hosting company, email provider and everything else about a website.
  55. urbandictionary.com  – find definitions of slangs and informal words.
  56. seatguru.com  – consult this site before choosing a seat for your next flight.
  57. flightstats.com  – Track flight status at airports worldwide.
  58. mymaps.google.com  – create custom Google Maps with scribbles, pins and custom shapes.
  59. snopes.com  – find if that email offer you received is real or just another scam.
  60. typingweb.com  – master touch-typing with these practice sessions.
  61. todo.microsoft.com  — a beautiful todo app and task manager. Also see Trello.
  62. minutes.io  – quickly capture effective notes during meetings.
  63. talltweets.com  — Turn Google Slides in animated GIF presentations.
  64. ifttt.com  – create a connection between all your online accounts.
  65. namechk.com  — search for your desired username across hundreds of social networks and omain names.
  66. gist.github.com  — create anonymous and secret text notes and much more.
  67. flipanim.com — create flipbook animations, includes an onion skin tool to let you see the revious frame as you draw the next one.
  68. powtoon.com  — create engaging whiteboard videos and presentations with your own voiceovers. lso see videoscribe.co
  69. clyp.it — Record your own voice or upload an audio file without creating any account. Also see oundcloud.com
  70. carrd.co  — build one-page fully responsive websites that look good on every screen.
  71. spark.adobe.com  — make stunning video presentations with voice narration and wow everyone.
  72. anchor.fm — the easiest way to record a podcast that you can distribute on iTunes without have to pay for hosting.
  73. duolingo.com  — learn to speak Chinese, French, Spanish or any other language of your choice.
  74. webmakerapp.com  — an offline playground for building web projects in HTML, CSS and javascript.
  75. pixton.com  — create your own comic strips with your own characters and move them into any one.
  76. designer.io  — a full-featured vector drawing tool that works everywhere.
  77. sumopaint.com  – an excellent layer-based online image editor.
  78. vectr.com  — create vector graphics and export them as SVG or PNG files.
  79. twitterbots — create your own Twitter bots that can auto-reply, DM, follow people and more.
  80. headspace.com  — learn the art of meditation and reduct stress, focus more and even sleep better.
  81. class-central.com  — a directory of free online courses offered by universities worldwide.
  82. googleartproject.com  — discover museums, famous paintings and art treasure from all around the world.
  83. instructables.com  — step-by-step guides on how to build anything and everything.
  84. flowgram.com  — make data-driven graphics, charts and infographics. Also see adioma.com 18 and eas.ly.
  85. marvelapp.com  — create interactive wireframes and product mockups.
  86. slide.ly — make marketing videos and branded stories for Instagram, Facebook and YouTube trailers. Also, see animoto.com 13 and biteable.com 11.
  87. gohighbrow.com  — Take bite-sized courses on a variety of topics, chapters are delivered by email every morning.
  88. htmlmail.pro – send rich-text emails with gmail mail merge.
  89. wirecutter.com  — whether you need a vacuum cleaner or an SD card, this is the best product recommendation website on the Internet.
  90. camelcamelcamel.com  — Create Amazon price watches and get email alerts when the prices drop.
  91. mockaroo.com  — download mock data to fill the rows in your Excel spreadsheet.
  92. asciiflow.com  — a WYSIWYG editor to draw ASCII diagrams that you can embed in emails and tweets.
  93. buffer.com  — the easily way to post and schedule updates on Twitter, Instagram, LinkedIn, Google+ and Facebook.
  94. 10minutemail.com  — create disposable email addresses for putting inside sign-up forms.
  95. whereami — find the postal address of your current location on Google maps.
  96. sway.com  — create and share interactive reports, newsletters, presentations, and for storytelling.
  97. apify.com  — the perfect web scraping tool that lets you extract data from nearly any website.
  98. thunkable.com  — build your own apps for Android and iOS by dragging blocks instead of writing code. Also see: glitch.com 36
  99. zerodollarmovies.com  — a huge collection of free movies curated from YouTube.
  100. upwork.com  — find freelancers and subject experts to work on any kind of project.
  101. duckduckgo.com  – a clean alternative to google search that doesn’t track you on the Internet.

Know any useful website that is missing in the list? Please let me know via comment


Hope you hind these websites useful, 

Thanks for reading 
Noeik


Sunday, July 7, 2019

Stock Buy & Sell Problem


Question: There is a given array of the stock price, each index denotes the price of the stock on that day. You need to find the max profit you will earn if you buy and sell the stock.




Example - Given an array - [10,5,6,8,9,3] where index 0 shows the prices of the stock on day 1 respectively.

Answer   Maxprofit=4
Explanation - first, we purchase at day 2 ( price - 5) and sell at day 5 (price 9 ) profit = 9-5=4


Code - 

package com.vp.learning;

public class StockBuyAndSellProblem {


 public static void main(String[] args) {

  //  given stock data as 
  int[] prices = {10,5,6,8,9,3};
  System.out.println(getMaxProfit(prices));
 }


 static int getMaxProfit(int[] prices) {

  if(prices.length<=1)
   return 0;

  int i = 0 ;
  int peak = prices[0];
  int valley = prices[0];
  int maxProfit = 0;
  while(i<prices.length-1) {
   while(i <prices.length-1 && prices[i]>= prices[i+1])
    i++;
   valley = prices[i];
   while(i <prices.length-1 && prices[i]<= prices[i+1])
    i++;
   peak = prices[i];

   maxProfit+=peak - valley ;

  }
  return maxProfit;
 }

}

Explanation :

 What we are doing here is as below

We are using Peak Valley Approach where are first calculate valley value in array

  • valley means lower value 
  • peak means higher value
Now while(i <prices.length-1 && prices[i]>= prices[i+1])

This is calculating the valley values, means the less value index in the array.

second, while loop is calculating the peak value in the array after this valley index.

if you see prices[i]>= prices[i+1] this means, price at current day is greater then the price at next day , that means the next day is valley or lower value, similarly for the next while as well, the price of current is less than the next day, so the next day will be peak value 

and the differences between peak and valley is actually the max profit we will earn for the day.

Time Complexity 

In this case, the time complexity will be O(n)




Hope this will help you in the interview. If you have any issue, please leave us a comment.



Thanks for reading 
Noeik

Friday, May 17, 2019

Algorithm to find if String contains only Unique characters without using any additional data structure

The string is one of the most asked questions in the Interview of Java developers.


Today we will see one of the most asked questions as to how will you find if String does not contain any duplicate characters.



There are different ways to check them, But we will only discuss the most efficient way to implement this algorithm.

Logic.

We know that characters have only 256 ascii values and there are only 128 values for alphabet characters. 
So what we will do is we will create one array of boolean of size 128 and we will update the index of array as true whenever we find the char value in the string , else if we get the same value in the string , the already true value will make the loop as false.
Also read - Find Longest Common Ancestor(LCA) Program in java

Time Complexity - O(n)
Space Complexity - O(1)

Code -



public class ArraysAndStringDemo {
 
 public static void main(String[] args) {
  
  String str = "programinjava";
  
  System.out.println(isUnique(str));
  
 }
 
 public static boolean isUnique(String str) {
  boolean[] char_set = new boolean[128];
  for(int i =0;i<str.length();i++) {
     int value =str.charAt(i); //getting the ascii value of character
   
     if(char_set[value])     // checking if it is already in the array
   return false;
   
     char_set[value] = true;
  
   
  }
  return true;
 }

}

If you have any issue in understanding the same , Please leave us a comment. Happy to help

Thanks for reading
Noeik

Saturday, March 9, 2019

Real time Logs of AWS Elastic Beanstalk by Command Prompt

Many of us know that one of the most important services of AWS is Elastic beanstalks. We deployed our application on Beanstalk and AWS itself manage most of the thing in it. One of them is Logs of Applications.


People usually were not able to see the tail of the logs of the application what they need to do is to go to the beanstalk and under logs, they ask for the last 100 lines of logs or full logs (which include the of the application along with the other logs ).



Today we will learn how to connect with the beanstalk application through EB CLI and see the logs.


let's follow the below steps.
  1. Install the Python Once installed run below commands
  2. python --version
  3. pip --version
  4. pip install awsebcli --upgrade --user
  5. once ebcli installed successfully, you can check by 
  6. eb --version
  7. define the Python Home in your Environment Variable.
  8. Now Run your command prompt as Administrator  and write 
eb init --interactive
You will see the below image.
  • Now select the region you have deployed your application.
  • After that, you will be asked to Create a new Application 
  • Once your application will be created you will see below screen.
  • You need to select the appropriate platform you have used for your application.
  • Now Once you do it you will be asked to create the SSH 
Select Yes 
  • Then they will ask you to create the keypair 


  • Provide your password  and then you will see the below image 
  • Now you have successfully created your SSH and it is uploaded to your beanstalk as well.
  • you need to attach the SSH with the Application.

Follow below steps 

eb ssh <Application-name> --settings

  • You will get the list of options then it will ask for the keypair which you need to attach.
  • Select the appropraite one.
  • After selecting the one you will be asked to enter the password set earlier.
  • You will then have the Applicaiton connected.
  • Once connected successfully you will be getting below image.
Now go to 
/var/log/tomcat8 ( to see the application logs, if your application is deployed on tomcat)

I Hope you will be able to connect your local machine to EB , If you have any issue  ,Please leave us a comment we will look into it.

Also Read:
  1. Spring Boot and Hibernate Tutorials - Application using Spring Boot
  2. What is Spring boot ?
  3. How to read value from property file in spring boot ?
  4. First Rest API Application - Top Spring Framework Interview Questions
  5. Implementation of Swagger in Spring boot
  6. How to use h2 database in spring boot

Thanks for reading.



Saturday, February 16, 2019

Database Timezone issue -Solution in java

We have at least once in our development has encountered one issue with database and client location is Timezone difference. 



In most of the cases, Our Backend /Application server is in a different timezone and our client server is in a different timezone. So what actually the problem happens is the difference in data time because of Timezone.

Wednesday, November 28, 2018

Thread Pooling In Java Using Executors Class

Most of the Important and most of the developer found one topic in java they perform a task and then they get destroyed. Purpose of multithreading is to perform multiple tasks simultaneously for effective utilization of our resources (time and CPU).


Imagine that there are 10 tasks to perform, so using traditional multithreading mechanism we will need 10 threads. Do you see a drawback in this approach? I see it; creation of a new thread per task will cause resource overhead.

Sunday, September 2, 2018

Remote Debugging of Java Application deployed on AWS Elastic Beanstalk

Most of the time we stuck in the situation where we need to do remote debugging of the application which is running on some server or somewhere other than localhost. We need to debug the code in eclipse. To do that we need to allow the running application to allow remote debugging. 


Generally, we know how to do remote debug in eclipse while the code is running on tomcat. In this post, we will see how to do remote debug when the application is deployed over AWS by elastic beanstalk.



Let's start.

To do Remote debug of AWS deployed the application, we need to follow below steps.

1)We need to Go to AWS Console -> Elastic Beanstalk -> Application -> Configuration

2) Under Configuration you need to go to Software ->Modify ->Container Options 
 Now in Container Options, search for JVM options    In this text box you need to write the below arguments.
-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=5005
Now, these arguments say that - The remote debug will be listening at 5005 port.

3) Now you need to Go to EC2 Instance running from AWS Console -> EC2

4) After that you need to check which security group is defined for that EC2 Instance, you need to allow this port to communicate outside AWS.

5)For that, you need to add the Port in Inbound and Outbound of the Security Group
   Select the Custom Protocol and define the Port as 5005 and then define Anywhere in Ip accessible.

After this, you will be able to communicate the port with the local debugger of the eclipse.

Now you need to configure the Local Eclipse environment for Remote debugging.


Configure Local Eclipse 


For this you need to go to  Run ->Debug Configuration -> Remote debugging 

Under that define the IP of the application ( you need to find the IP of the application at EC2 Instance Properties )

Define the port as 5005 ( as defined above).

Run the application and hurray, are now connected with the AWS application running.

Now you will be able to debug remotely.

Hope you like the post, If so please share it with your friends and family.

Thanks for reading
Noeik

Saturday, August 18, 2018

Upload File on AWS S3 Using Java

Most of us know nowadays that AWS  is used for almost everything because of its cheap price as well its availability.

AWS S3 is an online storage for storing file and images and zip, literally everything you want to put. 

Most of us have some use cases where we want to upload the image to aws s3 so that it can we used anywhere we want.

#Usercase we need to get the file or Image from UI and need to upload it to AWS S3 using java.

#Approach To Achieve it 
  • first, need to add the AWS SDK for Java 
  • Then we need to Get the client of AWS which is basically creating a connection with AWS 
  • After successfully getting the connection we will use s3 API to put the image as an object in AWS.

We first need to Add the dependency of AWS SDK in our project ( maven dependency as below )

  <dependency>
   <groupId>com.amazonaws</groupId>
   <artifactId>aws-java-sdk</artifactId>
   <version>1.11.388</version>
 </dependency>

After this, we need to have the AWS Account Access key and access_id
you can get it from https://console.aws.amazon.com/iam/home?#/security_credential

Access key file will look like below

[default]
aws_access_key_id=<Your-Access-key_id>
aws_secret_access_key=<Your Secret_access_key>
Note change <Your-Access-key_id> and <Your Secret_access_key> values with your access key.

Now you need to save the access key file at a location below.

~/.aws/credentials on Linux, macOS, or Unix
C:\Users\USERNAME \.aws\credentials on Windows

Now let see the Code for the Uploading of Image /File on AWS.  (Ref : here )
 we will create one jsp file where we create upload file and call the spring controller , under the controller, you can see the file and it will store to the aws s3.




Thyemleaf Html Code

<!DOCTYPE html>
<html xmlns:th="http://thymeleaf.org">
<head>
<title>File Upload Example</title>
<link href="webjars/bootstrap/3.3.7/css/bootstrap.min.css"
 rel="stylesheet" />
<script type="text/javascript" src="webjars/jquery/3.3.1/jquery.min.js"></script>
<script src="webjars/bootstrap/3.3.7/js/bootstrap.min.js"></script>

</head>
<script th:inline="javascript">
 /*<![CDATA[*/
 var _validFileExtensions = [ ".csv", ".zip" ,".png" ];
 function Validate(oForm) {
  var arrInputs = oForm.getElementsByTagName("input");
  for (var i = 0; i < arrInputs.length; i++) {
   var oInput = arrInputs[i];
   if (oInput.type == "file") {
    var sFileName = oInput.value;
    if (sFileName.length == 0) {

     alert("Please select a file to upload");
     return false;
    }
    if (sFileName.length > 0) {
     var blnValid = false;
     for (var j = 0; j < _validFileExtensions.length; j++) {
      var sCurExtension = _validFileExtensions[j];
      if (sFileName.substr(
        sFileName.length - sCurExtension.length,
        sCurExtension.length).toLowerCase() == sCurExtension
        .toLowerCase()) {
       blnValid = true;
       break;
      }
     }

     if (!blnValid) {
      alert("Invalid File Extension");
      return false;
     }
    }
   }
  }

  return true;
 }
  
 /*]]>*/
</script>

<body>

 <div class="container-fluid padding-0">
  <div class="row padding-0">
   
   <div class="col-md-4">
    <h2>File Upload Example</h2>
   </div>
   <div class="col-md-4" align="right"></div>
  </div>
 </div>
 <nav role="navigation" id="trainingset-container-id"
  class="navbar navbar-default">
  <div class="row" style="margin-top: 10px;">
   <div class="col-md-2">
    <B>Upload File</B>
   </div>
   <div class="col-md-6">
    <form method="POST" action="/upload"
     onsubmit="return Validate(this);" enctype="multipart/form-data">
     <div class="col-sm-6">

      <input type="file" name="file"  />
     </div>
     <div class="col-sm-6">
      <input type="submit" class="btn btn-success btn-sm" value="Upload data" />
     </div>
    </form>
   </div>
   
  </div>
 </nav>
  <div id="messageboxid">
   <div id="uploadstatus" th:if="${message}">
    <B>Status Of Uploaded File</B>
    <h6 th:text="${message}" />
   </div>
  </div>
  
</body>
</html>
This will see like this

Now we will see the Upload Controller Code.

Upload Controller.java

package com.programinjava.learn.controller;

import java.io.InputStream;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.amazonaws.auth.profile.ProfileCredentialsProvider;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.CannedAccessControlList;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.amazonaws.services.s3.model.PutObjectRequest;

@Controller
public class UploadController {
 
 @PostMapping("/upload")
 public String singleFileUpload(@RequestParam("file") MultipartFile file, RedirectAttributes redirectAttributes) {


  if (file.isEmpty()) {
   redirectAttributes.addFlashAttribute("message", "Please select a file to upload");
   return "redirect:uploadStatus";
  }
//  bucket name 
  String bucketName ="atserve-photos";
//  get it from user or change it 
  String nameOffile ="myPhoto";
//  getting aws access 
  AmazonS3 s3Client = AmazonS3ClientBuilder.standard()
                .withRegion(Regions.AP_SOUTH_1)
                .withCredentials(new ProfileCredentialsProvider())
                .build();
  boolean isBucketExist =s3Client.doesBucketExist(bucketName);
  if(!isBucketExist) {
   s3Client.createBucket(bucketName);
  }
  try {
   InputStream is = file.getInputStream();
   s3Client.putObject(new PutObjectRequest(bucketName,nameOffile,is,new ObjectMetadata()).withCannedAcl(CannedAccessControlList.PublicRead));
   redirectAttributes.addFlashAttribute("message", "SuccessFully Uploaded On AWS S3");
  }catch(Exception e) {
   e.printStackTrace();
  }
  return "redirect:/uploadStatus";
 }
 
 @GetMapping("/uploadStatus")
 public String uploadStatus(ModelMap m) {
  return "Homepage";
 }
 
 @GetMapping("/upload")  
 public String displayHomePageForAlarm() {
  return "Homepage";
 }

}

Let see what we get on AWS S3

So this is how we can see the myPhoto is now uploaded on AWS S3.

DOWNOAD THE CODE :


Also, learn