json


controllers

UserController.java
package com.app.blog.controllers;

import java.util.Optional;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.app.blog.dto.LoginDto;
import com.app.blog.dto.RegisterUserDTO;
import com.app.blog.models.Users;
import com.app.blog.repository.UserRepository;
import com.app.blog.util.EntitiyHawk;
import com.app.blog.util.JWTUtils;

/*

  • To change this license header, choose License Headers in Project Properties.
  • To change this template file, choose Tools | Templates
  • and open the template in the editor.
    /
    /
    *
  • @author 1460344
    */
    @RestController
    @RequestMapping("/")
    public class UserController extends EntitiyHawk {

}

GlobalController.java

package com.app.blog.controllers;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.app.blog.dto.PostDTO;
import com.app.blog.dto.UpdatePostDTO;
import com.app.blog.models.Posts;
import com.app.blog.models.Users;
import com.app.blog.repository.PostRepository;
import com.app.blog.util.EntitiyHawk;
import com.app.blog.util.PostMapper;

import io.jsonwebtoken.Claims;

/*

  • To change this license header, choose License Headers in Project Properties.
  • To change this template file, choose Tools | Templates
  • and open the template in the editor.
    /
    /
    *
  • @author 1460344
    */
    @RestController
    @RequestMapping("/api")
    public class GlobalController extends EntitiyHawk {

}

dto
LoginDto.java
/*

  • To change this license header, choose License Headers in Project Properties.
  • To change this template file, choose Tools | Templates
  • and open the template in the editor.
    */
    package com.app.blog.dto;

import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import org.hibernate.validator.constraints.Length;

/**
*

  • @author 1460344
    */
    public class LoginDto {

    @NotBlank(message = "should not be empty")
    @Length(max = 25)
    @Valid
    String email;
    @NotBlank(message = "should not be empty")
    @Length(max = 25)
    @Valid
    String password;

    public String getEmail() {
    return email;
    }

    public void setEmail(String email) {
    this.email = email;
    }

    public String getPassword() {
    return password;
    }

    public void setPassword(String password) {
    this.password = password;
    }
    }

PostDto.java

/*

  • To change this license header, choose License Headers in Project Properties.
  • To change this template file, choose Tools | Templates
  • and open the template in the editor.
    */
    package com.app.blog.dto;

import java.util.Date;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import org.hibernate.validator.constraints.Length;

/**
*

  • @author 1460344
    */
    public class PostDTO {

    @NotBlank(message = "should not be empty")
    @Length(max = 450)
    @Valid
    String title;
    @NotBlank(message = "should not be empty")
    @Length(max = 5000)
    @Valid
    String body;

    public String getTitle() {
    return title;
    }

    public void setTitle(String title) {
    this.title = title;
    }

    public String getBody() {
    return body;
    }

    public void setBody(String body) {
    this.body = body;
    }
    }

RegisterUserDto.java

/*

  • To change this license header, choose License Headers in Project Properties.
  • To change this template file, choose Tools | Templates
  • and open the template in the editor.
    */
    package com.app.blog.dto;

import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import org.hibernate.validator.constraints.Length;

/**
*

  • @author 1460344
    */
    public class RegisterUserDTO {

    @NotBlank(message = "Email cannot be blank")
    @Length(max = 40)
    @Valid
    String email;
    @NotBlank(message = "Name cannot be blank")
    @Length(max = 40)
    @Valid
    String name;
    @NotBlank(message = "password cannot be blank")
    @Length(min = 3, max = 45)
    @Valid
    String password;

    public String getEmail() {
    return email;
    }

    public void setEmail(String email) {
    this.email = email;
    }

    public String getName() {
    return name;
    }

    public void setName(String name) {
    this.name = name;
    }

    public String getPassword() {
    return password;
    }

    public void setPassword(String password) {
    this.password = password;
    }

    @Override
    public String toString() {
    return "RegisterUserDTO [email=" + email + ", name=" + name + ", password=" + password + "]";
    }
    }

UpdatePostDto.java

/*

  • To change this license header, choose License Headers in Project Properties.
  • To change this template file, choose Tools | Templates
  • and open the template in the editor.
    */
    package com.app.blog.dto;

import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import org.hibernate.validator.constraints.Length;

/**
*

  • @author 1460344
    */
    public class UpdatePostDTO {

    @Length(max = 450)
    @Valid
    String title;
    @Length(max = 5000)
    @Valid
    String body;
    @Valid
    Integer post_id;

    public Integer getPost_id() {
    return post_id;
    }

    public void setPost_id(Integer post_id) {
    this.post_id = post_id;
    }

    public String getTitle() {
    return title;
    }

    public void setTitle(String title) {
    this.title = title;
    }

    public String getBody() {
    return body;
    }

    public void setBody(String body) {
    this.body = body;
    }
    }

models

Posts.java

/*

  • To change this license header, choose License Headers in Project Properties.
  • To change this template file, choose Tools | Templates
  • and open the template in the editor.
    */
    package com.app.blog.models;

import java.io.Serializable;
import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.Lob;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.Size;

/**
*

  • @author 1460344
    */
    @Entity
    @Table(name = "posts")
    @NamedQueries({
    @NamedQuery(name = "Posts.findAll", query = "SELECT p FROM Posts p")})
    public class Posts implements Serializable {

    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "post_id")
    private Integer postId;
    @Size(max = 455)
    @Column(name = "post_title")
    private String postTitle;
    @Lob
    @Size(max = 2147483647)
    @Column(name = "post_body")
    private String postBody;
    @Column(name = "created_on")
    @Temporal(TemporalType.TIMESTAMP)
    private Date createdOn;
    @Column(name = "updated_on")
    @Temporal(TemporalType.TIMESTAMP)
    private Date updatedOn;
    @Column(name = "is_deleted")
    private Boolean isDeleted;
    @JoinColumn(name = "published_by", referencedColumnName = "user_id")
    @ManyToOne
    private Users publishedBy;

    public Posts() {
    }

    public Posts(Integer postId) {
    this.postId = postId;
    }

    public Integer getPostId() {
    return postId;
    }

    public void setPostId(Integer postId) {
    this.postId = postId;
    }

    public String getPostTitle() {
    return postTitle;
    }

    public void setPostTitle(String postTitle) {
    this.postTitle = postTitle;
    }

    public String getPostBody() {
    return postBody;
    }

    public void setPostBody(String postBody) {
    this.postBody = postBody;
    }

    public Date getCreatedOn() {
    return createdOn;
    }

    public void setCreatedOn(Date createdOn) {
    this.createdOn = createdOn;
    }

    public Date getUpdatedOn() {
    return updatedOn;
    }

    public void setUpdatedOn(Date updatedOn) {
    this.updatedOn = updatedOn;
    }

    public Boolean getIsDeleted() {
    return isDeleted;
    }

    public void setIsDeleted(Boolean isDeleted) {
    this.isDeleted = isDeleted;
    }

    public Users getPublishedBy() {
    return publishedBy;
    }

    public void setPublishedBy(Users publishedBy) {
    this.publishedBy = publishedBy;
    }

    @Override
    public int hashCode() {
    int hash = 0;
    hash += (postId != null ? postId.hashCode() : 0);
    return hash;
    }

    @Override
    public boolean equals(Object object) {
    // TODO: Warning - this method won't work in the case the id fields are not set
    if (!(object instanceof Posts)) {
    return false;
    }
    Posts other = (Posts) object;
    if ((this.postId == null && other.postId != null) || (this.postId != null && !this.postId.equals(other.postId))) {
    return false;
    }
    return true;
    }

    @Override
    public String toString() {
    return "com.app.blog.models.Posts[ postId=" + postId + " ]";
    }

}
Users.java

/*

  • To change this license header, choose License Headers in Project Properties.
  • To change this template file, choose Tools | Templates
  • and open the template in the editor.
    */
    package com.app.blog.models;

import java.io.Serializable;
import java.util.List;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.validation.constraints.Size;

/**
*

  • @author 1460344
    */
    @Entity
    @Table(name = "users")
    @NamedQueries({
    @NamedQuery(name = "Users.findAll", query = "SELECT u FROM Users u")})
    public class Users implements Serializable {

    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "user_id")
    private Integer userId;
    @Size(max = 45)
    @Column(name = "user_name")
    private String userName;
    // @Pattern(regexp="[a-z0-9!#%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#%&'+/=?^_`{|}~-]+)@(?:a-z0-9?\.)+a-z0-9?", message="Invalid email")//if the field contains email address consider using this annotation to enforce field validation
    @Size(max = 45)
    @Column(name = "email")
    private String email;
    @Size(max = 45)
    @Column(name = "password")
    private String password;
    @OneToMany(mappedBy = "publishedBy")
    private List<Posts> postsList;

    public Users() {
    }

    public Users(Integer userId) {
    this.userId = userId;
    }

    public Integer getUserId() {
    return userId;
    }

    public void setUserId(Integer userId) {
    this.userId = userId;
    }

    public String getUserName() {
    return userName;
    }

    public void setUserName(String userName) {
    this.userName = userName;
    }

    public String getEmail() {
    return email;
    }

    public void setEmail(String email) {
    this.email = email;
    }

    public String getPassword() {
    return password;
    }

    public void setPassword(String password) {
    this.password = password;
    }

    public List<Posts> getPostsList() {
    return postsList;
    }

    public void setPostsList(List<Posts> postsList) {
    this.postsList = postsList;
    }

    @Override
    public int hashCode() {
    int hash = 0;
    hash += (userId != null ? userId.hashCode() : 0);
    return hash;
    }

    @Override
    public boolean equals(Object object) {
    // TODO: Warning - this method won't work in the case the id fields are not set
    if (!(object instanceof Users)) {
    return false;
    }
    Users other = (Users) object;
    if ((this.userId == null && other.userId != null) || (this.userId != null && !this.userId.equals(other.userId))) {
    return false;
    }
    return true;
    }

    @Override
    public String toString() {
    return "com.app.blog.models.Users[ userId=" + userId + " ]";
    }

}

repository

package com.app.blog.repository;

import com.app.blog.models.Posts;
import com.app.blog.models.Users;
import java.util.List;
import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;

/*

  • To change this license header, choose License Headers in Project Properties.
  • To change this template file, choose Tools | Templates
  • and open the template in the editor.
    */

/**
*

  • @author 1460344
    */
    public interface PostRepository extends JpaRepository<Posts,Integer> {

}

UserRepository.java

package com.app.blog.repository;

import com.app.blog.models.Users;
import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;

/*

  • To change this license header, choose License Headers in Project Properties.
  • To change this template file, choose Tools | Templates
  • and open the template in the editor.
    */

/**
*

  • @author 1460344
    */
    public interface UserRepository extends JpaRepository<Users,Integer> {

}

util

Constants.java
/*

  • To change this license header, choose License Headers in Project Properties.
  • To change this template file, choose Tools | Templates
  • and open the template in the editor.
    */
    package com.app.blog.util;

/**
*

  • @author 1460344
    */
    public class Constants {

    public static String JWT_SECRET="MY_BLOG_SECRET";
    }

EntityHawk.java
/*

  • To change this license header, choose License Headers in Project Properties.
  • To change this template file, choose Tools | Templates
  • and open the template in the editor.
    */
    package com.app.blog.util;

import java.util.HashMap;
import java.util.Map;
import org.springframework.http.ResponseEntity;

/**
*

  • @author 1460344
    */
    public class EntitiyHawk {
    public ResponseEntity genericSuccess() {
    Map map = new HashMap();
    map.put("status", true);
    return ResponseEntity.ok(map);
    }

    public ResponseEntity genericSuccess(Object data) {
    Map map = new HashMap();
    map.put("status", true);
    map.put("data", data);
    return ResponseEntity.ok(map);
    }

    public ResponseEntity genericError() {
    Map map = new HashMap();
    map.put("status", false);
    return ResponseEntity.ok(map);
    }

    public ResponseEntity genericError(Object data) {
    Map map = new HashMap();
    map.put("status", false);
    map.put("data", data);
    return ResponseEntity.ok(map);
    }

    public ResponseEntity genericResponse(Object data) {
    Map map = new HashMap();
    map.put("data", data);
    return ResponseEntity.ok(map);
    }

    public ResponseEntity genericResponse(boolean status) {
    Map map = new HashMap();
    map.put("status", status);
    return ResponseEntity.ok(map);
    }

    public ResponseEntity genericResponse(boolean status, Object data) {
    Map map = new HashMap();
    map.put("status", status);
    map.put("data", data);
    return ResponseEntity.ok(map);
    }

}

JWTUtils.java

/*

  • To change this license header, choose License Headers in Project Properties.
  • To change this template file, choose Tools | Templates
  • and open the template in the editor.
    */
    package com.app.blog.util;

import com.app.blog.models.Users;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import java.util.Date;

/**
*

  • @author 1460344
    */
    public class JWTUtils {

    public String CreateJWTToken(Users user) {

     Claims claims= Jwts.claims();
     claims.put("name", user.getUserName());
     claims.put("email", user.getEmail());
     claims.put("user_id", user.getUserId());
     claims.setSubject("MY Blog");
     claims.setIssuedAt(new Date());
     
     String token = Jwts.builder()
             .setClaims(claims)
             .signWith(SignatureAlgorithm.HS256, Constants.JWT_SECRET)
             .compact();
     
     return token;
    

    }
    }

PostMapper.java

/*

  • To change this license header, choose License Headers in Project Properties.
  • To change this template file, choose Tools | Templates
  • and open the template in the editor.
    */
    package com.app.blog.util;

import com.app.blog.models.Posts;
import java.util.HashMap;
import java.util.Map;

/**
*

  • @author 1460344
    */
    public class PostMapper {

    public Map postDetailsToMap(Posts post) {
    Map map = new HashMap();
    map.put("post_id", post.getPostId().toString());
    map.put("title", post.getPostTitle());
    map.put("body", post.getPostBody());
    map.put("created_on",post.getCreatedOn());
    map.put("created_by", post.getPublishedBy().getUserName());
    map.put("last_updated", post.getUpdatedOn());
    return map;
    }
    }

BlogApplication.java

package com.app.blog;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
public class BlogApplication {

public static void main(String[] args) {
    SpringApplication.run(BlogApplication.class, args);
}

}

JwtFilter.java

/*

  • To change this license header, choose License Headers in Project Properties.
  • To change this template file, choose Tools | Templates
  • and open the template in the editor.
    */
    package com.app.blog;

import com.app.blog.util.Constants;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureException;
import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.filter.GenericFilterBean;

/**
*

  • @author 1460344
    */
    public class JwtFilter extends GenericFilterBean {
    @Override
    public void doFilter(ServletRequest sr, ServletResponse sr1, FilterChain fc) throws IOException, ServletException {
    throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

}

SwaggerConfig.java

/*

  • To change this license header, choose License Headers in Project Properties.
  • To change this template file, choose Tools | Templates
  • and open the template in the editor.
    */
    package com.app.blog;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiKey;
import springfox.documentation.service.AuthorizationScope;
import springfox.documentation.service.SecurityReference;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

/**
*

  • @author 1460344
    */
    @Configuration
    @EnableSwagger2
    public class SwaggerConfig {

    public static final String AUTHORIZATION_HEADER = "Authorization";

    @Bean
    public Docket api() {
    return new Docket(DocumentationType.SWAGGER_2)
    .select()
    .apis(RequestHandlerSelectors.basePackage("com.app.blog"))
    .paths(PathSelectors.any())
    .build().securitySchemes(Arrays.asList(apiKey()))
    .securityContexts(Collections.singletonList(securityContext()));

    }

    private SecurityContext securityContext() {
    return SecurityContext.builder().securityReferences(defaultAuth()).forPaths(PathSelectors.regex("/.*")).build();
    }

    private List<SecurityReference> defaultAuth() {
    final AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
    final AuthorizationScope[] authorizationScopes = new AuthorizationScope[]{authorizationScope};
    return Collections.singletonList(new SecurityReference("Bearer", authorizationScopes));
    }

    private ApiKey apiKey() {
    return new ApiKey("Bearer", "Authorization", "header");
    }
    }

resources

schema.sql

DROP TABLE IF EXISTS posts;

DROP TABLE IF EXISTS users;

CREATE TABLE users (
user_id int(11) NOT NULL AUTO_INCREMENT,
user_name varchar(45) DEFAULT NULL,
email varchar(45) DEFAULT NULL,
password varchar(45) DEFAULT NULL,
PRIMARY KEY (user_id)
);

LOCK TABLES users WRITE;

INSERT INTO users VALUES (1,'Himalaya','[email protected]','12345'),(2,'Test User','[email protected]','12345'),(3,'qwerty','[email protected]','12345');

UNLOCK TABLES;

CREATE TABLE posts (
post_id int(11) NOT NULL AUTO_INCREMENT,
post_title varchar(455) DEFAULT NULL,
post_body longtext,
published_by int(11) DEFAULT NULL,
created_on datetime DEFAULT NULL,
updated_on datetime DEFAULT NULL,
is_deleted tinyint(1) DEFAULT NULL,
PRIMARY KEY (post_id),
KEY userdId_idx (published_by),
CONSTRAINT userdId FOREIGN KEY (published_by) REFERENCES users (user_id) ON DELETE CASCADE
);

LOCK TABLES posts WRITE;

INSERT INTO posts VALUES (1,'Post First Updated','Post body Updated',1,'2020-04-14 21:04:06','2020-04-17 15:04:46',0),(2,'This is be body of my second blog post','My Second Post',1,'2020-04-16 11:55:48','2020-04-16 11:55:48',1),(3,'titlee','bodydyyy',1,'2020-04-16 11:56:11','2020-04-17 15:31:56',0),(4,'Title 34','Thhis is my 4th Blog body',1,'2020-04-17 15:01:36','2020-04-17 15:01:36',1),(5,'This is blog title 5','This is blog body 5',1,'2020-04-17 15:29:53','2020-04-17 15:29:53',1),(6,'Thats it','I am updated',2,'2020-04-17 16:26:10','2020-04-17 16:26:54',1),(7,'title demo updated','demo body updated',1,'2020-04-17 17:27:05','2020-04-17 17:28:34',0);

UNLOCK TABLES;

application.yml

YAML Template.


spring:
datasource:
driverClassName: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/blog
username: root
password: mysql

application.properties

spring.jpa.hibernate.ddl-auto=none
spring.datasource.initialization-mode=always