Upload files to AWS S3 Bucket using Spring Boot and AJAX

Follow below steps to perform this –

Step 1 – Need to add aws-java-sdk maven dependency in pom.xml file

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

Step 2 – Need to add below properties in ConstantUtils.java file

public static final String END_POINT_URL = "https://s3.us-east-1.amazonaws.com";
public static final String ACCESS_KEY = "AKIAJGDFBUUJF3LAQUWQ";
public static final String SECRET_KEY = "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";
public static final String BUCKET_NAME = "almighty-user-images";

Step 3 – Add below code in controller class

@Autowired
private AmazonService amazonService;

@PostMapping("/upload")
public @ResponseBody String fileUpload(@RequestPart(value="file") MultipartFile multipartFile, @RequestParam(value="editUserId") Long editUserId) {
     return amazonService.uploadFile(multipartFile, userService.findOne(editUserId));
}

Step 4 – create new interface called AmazonService.java

package com.mightyjava.service;
import org.springframework.web.multipart.MultipartFile;
import com.mightyjava.model.User;

public interface AmazonService {
     String uploadFile(MultipartFile multipartFile, User user);
}

Step 5 – Need to implement this interface so create a new class called AmazonServiceImpl.java and inside this under uploadFile method once we get the URL we will set this for user profile photo so it can save this as well.

package com.mightyjava.service.impl;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import javax.annotation.PostConstruct;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.CannedAccessControlList;
import com.amazonaws.services.s3.model.PutObjectRequest;
import com.mightyjava.model.User;
import com.mightyjava.service.AmazonService;
import com.mightyjava.service.UserService;
import com.mightyjava.utils.ConstantUtils;

@Service
public class AmazonServiceImpl implements AmazonService {

     private AmazonS3 s3Client;
     @Autowired
     private UserService userService;

     @PostConstruct
     private void initializeAmazon() {
          this.s3Client = new AmazonS3Client(new BasicAWSCredentials(ConstantUtils.ACCESS_KEY, ConstantUtils.SECRET_KEY));
     }

     @Override
     public String uploadFile(MultipartFile multipartFile, User user) {
          String fileUrl = "";
          JSONObject jsonObject = new JSONObject();
          try {
               File file = convertMultipartToFile(multipartFile);
               String fileName = new Date().getTime()+"-"+multipartFile.getOriginalFilename().replace(" ", "_");
               fileUrl = ConstantUtils.END_POINT_URL+"/"+ConstantUtils.BUCKET_NAME+"/"+fileName;
               s3Client.putObject(new PutObjectRequest(ConstantUtils.BUCKET_NAME, fileName, file).withCannedAcl(CannedAccessControlList.PublicRead));
               user.setProfilePhoto(fileUrl);
               userService.addUser(user);
               jsonObject.put("status", "success");
               jsonObject.put("imageUrl", fileUrl);
               jsonObject.put("message", "File Uploaded Successfully.");
          } catch (IOException | JSONException e) {
               e.printStackTrace();
          }
          return jsonObject.toString();
     }

     private File convertMultipartToFile(MultipartFile file) throws IOException {
          File convertFile = new File(file.getOriginalFilename());
          FileOutputStream fos = new FileOutputStream(convertFile);
          fos.write(file.getBytes());
          fos.close();
          return convertFile;
     }
}

Step 6 – Now we will see how to reach request till controller. so add new button called Upload

&lt;form id=&quot;uploadImage&quot; class=&quot;form-horizontal&quot; action=&quot;&quot; method=&quot;post&quot; enctype=&quot;multipart/form-data&quot;&gt;
	&lt;div class=&quot;modal-header&quot;&gt;
		&lt;button type=&quot;button&quot; class=&quot;close&quot; data-dismiss=&quot;modal&quot;&gt;&amp;times;&lt;/button&gt;
		&lt;h4 class=&quot;modal-title&quot;&gt;Upload User Profile for ${userForm.fullName}&lt;/h4&gt;
	&lt;/div&gt;
	&lt;div class=&quot;modal-body&quot;&gt;
		&lt;div class=&quot;form-group&quot;&gt;
			&lt;input type=&quot;hidden&quot; name=&quot;editUserId&quot; value=&quot;${userForm.id}&quot;&gt;
			&lt;label class=&quot;col-md-3 control-label&quot;&gt;Upload File :&lt;/label&gt;
			&lt;div class=&quot;col-md-6&quot;&gt;
				&lt;input type=&quot;file&quot; name=&quot;file&quot; class=&quot;form-control&quot;&gt;
			&lt;/div&gt;
		&lt;/div&gt;
	&lt;/div&gt;
	&lt;div class=&quot;modal-footer&quot;&gt;
		&lt;button type=&quot;submit&quot; class=&quot;btn btn-default&quot;&gt;Upload&lt;/button&gt;
		&lt;button type=&quot;button&quot; class=&quot;btn btn-default&quot; data-dismiss=&quot;modal&quot;&gt;Close&lt;/button&gt;
	&lt;/div&gt;
&lt;/form&gt;

Step 7 – Now when we click on Upload button, using AJAX we will submit the form and call controller upload method

$("#uploadImage").on("submit", function(e) {
     e.preventDefault();
     var formData = new FormData(this);
     $.ajax({
          type:"POST",
          url:"/mightyjava/user/upload",
          data:formData,
          cache:false,
          dataType:"json",
          contentType:false,
          processData:false,
          success:function(data) {
               var title="Upload Confirmation";
               if(data.status == "success") {
                    toastr.success(data.message, title, {
                         closeButton:true
                    });
                    fetchList("user");
                    $("#uploadModal").modal("hide");
                    $("body").removeClass("modal-open");
                    $(".modal-backdrop").remove();
               } else {
                    toastr.error(data.message, title, {
                         allowHtml:true,
                         closeButton:true
                    });
               }
          }
     });
});

That’s it. Here is the demo

1

when you click on Upload Button pop up will open

2

once file selected and click on upload then upload success message will come like below image

3

 

you can download code from GITHUB

Watch the video, you will get complete understanding.

 

Angular and Grails Integration Part-3

To integrate Grails framework with Angular JS Follow belows steps

Step 1 – Create Grails Project

Step 2 – Delete some default folder like remove all folder from assets, delete main.gsp page and remove everything from index.gsp

Step 3 – You need angular.min.js and angular-ui-router.js file.

After download put js file under web-app/js and for angular create folder “angular” Add below code in index.gsp page

<!DOCTYPE html>
<html ng-app="angModule">
    <head>
        <script type="text/javascript" src="js/angular/angular.min.js"></script>
        <script type="text/javascript" src="js/angular/angular-ui-router.js"></script>
        <script type="text/javascript" src="js/angular/application.js"></script>
        <script type="text/javascript" src="js/angular/controller/UserController.js"></script>
        <script type="text/javascript" src="js/angular/service/UserService.js"></script>
    </head>
    <body>
        <ui-view></ui-view>
    </body>
</html>

Step 4 – Create a js file under “angular” folder and put below code in application.js file

var app = angular.module("angModule", [ "ui.router" ]).config(
    function($stateProvider, $urlRouterProvider) {
        $urlRouterProvider.otherwise("/user");
        $stateProvider
            .state("user", {
                url : "/user",
                templateUrl : "html/user.html",
        });
    }
});

Step 5 – Create a controller folder then under that create UserController.js file and put below code

app.controller("UserController", function($controller, $rootScope, $scope, $location, UserService) {
    $scope.register = function(user) {
        UserService.register(user).then(function(response) {
            alert(response.data.message)
            $location.path("/");
            $scope.userList();
        });
    } 
    $scope.userList = function() {
        UserService.userList().then(function(response) {
            $scope.users = response.data.users;
        });
    }
});

Step 6 – Create a service folder then under that create UserService.js file and put below code

app.factory('UserService', function($http) {
    var factory = {};
    factory.register = function(user) {
        return $http.post('user/register', user).success(function(data) {
            return data;
        });
    }   
    factory.userList = function() {
        return $http.get("user/userList").success(function(data) {
            return data;
        });
    }   
    return factory;
});

Step 7 – Create a controller under Controller directory and put the below code

package com.angular.grails
class User {
    String userName
    String fullName
    String password
    static constraints = {
        userName nullable: false
        fullName nullable:false
        password nullable:false
    }
    @Override
    public String toString() {
        return "User [userName=" + userName + ", fullName=" + fullName
        + ", password=" + password + "]";
    } 
}

Step 8 – Create a controller under Controller directory and put the below code

package com.angular.grails
import grails.converters.JSON
class UserController { 
    def userService
    def register = {
        def resp = [:]
        User user = new User()
        user.setUserName(request.JSON.userName)
        user.setFullName(request.JSON.fullName)
        user.setPassword(request.JSON.password)
        userService.register(user)
        resp.message = "user added successfully."
        render resp as JSON
    } 
    def userList = {
        def resp = [:]
        resp.users = userService.findAllUser()
        render resp as JSON
    }
}

Step 9 – Create a service under Service directory and put the below code

package com.angular.grails
import grails.transaction.Transactional
@Transactional
class UserService {
    void register(User user) {
        user.save()
    }
    def findAllUser() {
        return User.findAll()
    }
}

Step 10 – Create a html page under “web-app/html” user.html

<div ng-controller="UserController">
    <form ng-submit="register(user)">
        User Name <input type="text" ng-model="user.userName"/> 
        Full Name <input type="text" ng-model="user.fullName"/>
        Password <input type="password" ng-model="user.password"/> 
        <input type="submit" value="Register"/>
    </form>
    <a href="javascript:void(0);" ng-click="userList()">User List</a>
    <div ng-hide="!users.length">
        <table>
            <thead>
                <tr>
                    <th>Full Name</th>
                    <th>User Name</th>
                    <th>Password</th>
                </tr>
            </thead>
            <tbody>
                <tr ng-repeat="user in users"> 
                    <td>{{user.fullName}}</td>
                    <td>{{user.userName}}</td>
                    <td>{{user.password}}</td>
                </tr>
            </tbody>
        </table>
    </div>
</div>

Run the application using “run-app”

To see live demo watch below video

Angular and Grails Integration Part-2

To integrate Grails framework with AngularJs Follow belows steps

Step 1 – Create Grails Project

Step 2 – Delete some default folder like remove all folder from assets, delete main.gsp page and remove everything from index.gsp

Step 3 – You need angular.min.js and angular-ui-router.js file.

After download put js file under web-app/js and for angular create folder “angular” Add below code in index.gsp page

<!DOCTYPE html>
<html ng-app="angModule">
    <head>
        <script type="text/javascript" src="js/angular/angular.min.js"></script>
        <script type="text/javascript" src="js/angular/angular-ui-router.js"></script>
        <script type="text/javascript" src="js/angular/application.js"></script>
        <script type="text/javascript" src="js/angular/controller/UserController.js"></script>
        <script type="text/javascript" src="js/angular/service/UserService.js"></script>
    </head>
    <body>
        <ui-view></ui-view>
    </body>
</html>

Step 4 – Create a js file under “angular” folder and put below code in application.js file

var app = angular.module("angModule", [ "ui.router" ]).config(
    function($stateProvider, $urlRouterProvider) {
        $urlRouterProvider.otherwise("/user");
        $stateProvider
          .state("user", {
             url : "/user",
             templateUrl : "html/user.html",
        });
    }
 });

Step 5 – Create a controller folder then under that create UserController.js file and put below code

app.controller("UserController", function($controller, $rootScope, $scope, $location, UserService) {
    $scope.register = function(user) {
        UserService.register(user).then(function(response) {
            alert(response.data.message)
            $location.path("/");
        });
    }
});

Step 6 – Create a service folder then under that create UserService.js file and put below code

app.factory('UserService', function($http) {
    var factory = {};
    factory.register = function(user) {
        return $http.post('user/register', user).success(function(data) {
           return data;
        });
    }
    return factory;
});

Step 7 – Create a controller under Controller directory and put the below code

package com.angular.grails

import grails.converters.JSON

class UserController {
    def register = {
       def resp = [:]
       println request.JSON
       resp.message = "User Register Successfully."
       render resp as JSON
    }
}

Step 8 – Create a html page under “web-app/html” user.html

<div ng-controller="UserController">
    <form ng-submit="register(user)">
        User Name <input type="text" ng-model="user.userName"/> 
        Full Name <input type="text" ng-model="user.fullName"/>
        Password <input type="password" ng-model="user.password"/> 
        <input type="submit" value="Register"/>
    </form>
</div>

To see live demo watch below video

Angular and Grails Integration Part-1

To integrate Grails framework with Angular JS Follow below steps

Step 1 – Create Grails Project

Step 2 – Delete some default folder like remove all folder from assets, delete main.gsp page and remove everything from index.gsp

Step 3 – You need angular.min.js and angular-ui-router.js file.

After download put js file under web-app/js and for angular create folder “angular” Add below code in index.gsp page

<!DOCTYPE html>
<html ng-app="angModule">
 <head>
  <script type="text/javascript" src="js/angular/angular.min.js"></script>
  <script type="text/javascript" src="js/angular/angular-ui-router.js"></script>
  <script type="text/javascript" src="js/angular/application.js"></script>
 </head>
 <body>
  <ui-view></ui-view>
 </body>
</html>

Step 4 – Create a js file under “angular” folder and put below code in application.js file

var app = angular.module("angModule", [ "ui.router" ]).config(
 function($stateProvider, $urlRouterProvider) {
  $urlRouterProvider.otherwise("/user");
  $stateProvider
   .state("user", {
    url : "/user",
    templateUrl : "html/user.html",
   })
 });

Step 5 – Create a HTML page under “web-app/html” user.html put some message like “Hello World”

To see live demo watch below video

Thanks for reading

Facebook Login using Spring Social & Spring Boot

You can download sample application created by Spring developer – gs-accessing-facebook

Here is the code sample which they added to implement Facebook Login

pom.xml – need to add below dependencies

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.social</groupId>
    <artifactId>spring-social-facebook</artifactId>
</dependency>

application.properties

spring.social.facebook.appId=233668646673605
spring.social.facebook.appSecret=33b17e044ee6a4fa383f46ec6e28ea1d

HelloController.java

package hello;

import org.springframework.social.connect.ConnectionRepository;
import org.springframework.social.facebook.api.Facebook;
import org.springframework.social.facebook.api.PagedList;
import org.springframework.social.facebook.api.Post;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/")
public class HelloController {

    private Facebook facebook;
    private ConnectionRepository connectionRepository;

    public HelloController(Facebook facebook, ConnectionRepository connectionRepository) {
        this.facebook = facebook;
        this.connectionRepository = connectionRepository;
    }

    @GetMapping
    public String helloFacebook(Model model) {
        if (connectionRepository.findPrimaryConnection(Facebook.class) == null) {
            return "redirect:/connect/facebook";
        }
        model.addAttribute("facebookProfile", facebook.userOperations().getUserProfile());
        PagedList<Post> feed = facebook.feedOperations().getFeed();
        model.addAttribute("feed", feed);
        return "hello";
    }
}

hello.html

<html>
	<head>
		<title>Hello Facebook</title>
	</head>
	<body>
		<h3>Hello, <span th:text="${facebookProfile.name}">Some User</span>!</h3>
		
		<h4>Here is your feed:</h4>
		
		
from wrote:

message text


</body> </html>

To see live demo watch below video –

Thanks for reading 🙂

Please Subscribe our you tube channel Almighty Java

Annotations in Java

Why annotation is required, we can use comment also to give information about data like metadata ?

  • If you use comment in class, field, constructor or method level then it can reach max to max source file only, means when compiler compile .java file to .class file. It exclude comment section so it won’t be available.
  • Before Java 5 to achieve such kind of functionality used xml based configuration like in hibernate needs a .hbm file or for servlet needs to add configuration in web.xml file.

What is Annotation in java ?

  • In the Java computer programming language, an annotation is a form of syntactic metadata (a set of data that describes and gives information about other data) that can be added to Java source code.
  • Classes, methods, variables, parameters and packages may be annotated. Unlike Javadoc tags, Java annotations can be reflective in that they can be embedded in class files generated by the compiler and may be retained by the Java VM to be made retrievable at run-time. It is possible to create meta-annotations out of the existing ones in Java.
  • Annotations are the part of java from Java 5 before that there is not concept like annotations. So we should use xml based configuration.

Type of Annotations

  • Marker Annotation – @Override, @WebListener
  • Single Valued Annotation – @SuppressedWarning(“unchecked”) or @SuppressedWarning(value = “unchecked”)
  • Multi valued Annotation – @WebServlet(name = “login”, urlPatterns = “/login”)

Why are Annotations better then xml ?

XML – Servlet configuration in web.xml before Servlet 2.X like below code

<web-app>
     <servlet>
        <servlet-name>helloworld</servlet-name>
        <servlet-class>HelloWorld</servlet-class>
     </servlet>
     <servlet-mapping>
        <servlet-name>HelloWorld</servlet-name>
        <url-pattern>/helloworld</url-pattern>
     </servlet-mapping>
</web-app>

Annotation – after Servlet 3.X

 @WebServlet(name = “helloworld“, urlPatterns = “/helloworld”)

See the difference so before java 5, need to write a code in xml file.

Ex – Servlet – like above, Hibernate – domain.hbm.xml, Spring – Need to create bean in applicatonContext xml file

XML v/s Annotation

XML Annotation
up to jdk1.4 jdk 5.0
JDBC 3.X JDBC 4.0
Servlet 2.5 Servlet 3.X
Struts 1.X Struts 2.X
JSF 1.X JSF 2.X
Hibernate 3.2.4 Hibernate 3.2.5
Spring 2.X Spring 3.X
EJB 2.X EJB 3.X

General purpose annotations

  • @Override – annotation informs the compiler that the element is meant to override an element declared in a superclass. Overriding methods will be discussed in Interfaces and Inheritance. While it is not required to use this annotation when overriding a method, it helps to prevent errors.
  • @SuppressWarnings – annotation is used to suppress compiler warnings for the annotated element. Specifically, the unchecked category allows suppression of compiler warnings generated as a result of unchecked type casts.
  • @Deprecated – Starting with J2SE 5.0, you deprecate a class, method, or field by using the @Deprecated annotation. Additionally, you can use the @deprecated Javadoc tag tell developers what to use instead. Using the annotation causes the Java compiler to generate warnings when the deprecated class, method, or field is used.
  • @FunctionalInterface – An informative annotation type used to indicate that an interface type declaration is intended to be a functional interface as defined by the Java Language Specification. Conceptually, a functional interface has exactly one abstract method.

Meta annotations

  • @Documented – to ensure that classes using your annotation show this in their generated JavaDoc also.
  • @Inherited – It means that subclasses of annotated classes are considered having the same annotation as their superclass.
  • @Target – it defined that where you can put your annotation based on type like class, method, constructor, field, localvariable.
  • @Retention – based on Retention Policy can use that like Source, Class or at Runtime.

For more detail, Please watch below video –