Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Upload blog cover #29

Merged
merged 4 commits into from
Apr 9, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package com.example.BloggerApp.common.utils;

import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

public class Base64Converter {

public static byte[] decodeBase64(String base64String) throws UnsupportedEncodingException {
return Base64.getMimeDecoder().decode(base64String.getBytes(StandardCharsets.UTF_8));
}

public static String encodeBase64(byte[] image){
return Base64.getEncoder().encodeToString(image);
}
}
45 changes: 45 additions & 0 deletions src/main/java/com/example/BloggerApp/common/utils/ImageUtils.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package com.example.BloggerApp.common.utils;

import java.io.ByteArrayOutputStream;
import java.util.zip.Deflater;
import java.util.zip.Inflater;

public class ImageUtils {

public static byte[] compressImage(byte[] data) {
Deflater deflater = new Deflater();
deflater.setLevel(Deflater.BEST_COMPRESSION);
deflater.setInput(data);
deflater.finish();

ByteArrayOutputStream outputStream = new ByteArrayOutputStream(data.length);
byte[] tmp = new byte[4*1024];
while (!deflater.finished()) {
int size = deflater.deflate(tmp);
outputStream.write(tmp, 0, size);
}
try {
outputStream.close();
} catch (Exception ignored) {
}
return outputStream.toByteArray();
}



public static byte[] decompressImage(byte[] data) {
Inflater inflater = new Inflater();
inflater.setInput(data);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(data.length);
byte[] tmp = new byte[4*1024];
try {
while (!inflater.finished()) {
int count = inflater.inflate(tmp);
outputStream.write(tmp, 0, count);
}
outputStream.close();
} catch (Exception ignored) {
}
return outputStream.toByteArray();
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.example.BloggerApp.controller;

import com.example.BloggerApp.common.utils.Base64Converter;
import com.example.BloggerApp.http.request.CreateBlogRequest;
import com.example.BloggerApp.http.request.TagRequest;
import com.example.BloggerApp.http.request.UpdateBlogRequest;
Expand All @@ -9,19 +10,26 @@
import com.example.BloggerApp.models.BlogEntity;
import com.example.BloggerApp.models.TagEntity;
import com.example.BloggerApp.service.impl.BlogServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartRequest;

import java.io.UnsupportedEncodingException;
import java.time.LocalDateTime;
import java.util.List;
import java.util.function.Function;
Expand All @@ -39,9 +47,17 @@ public BlogController(BlogServiceImpl blogServiceImpl){
}

@CrossOrigin(origins = "http://localhost:3000",allowedHeaders = "*")
@PostMapping("/create/user/{user_id}/category/{category_id}")
public ResponseEntity<String> createBlog(@RequestBody CreateBlogRequest createBlogRequest,@PathVariable("user_id") long userId,@PathVariable("category_id") long categoryId){
blogServiceImpl.addBlog(fromBlogRequestToBlogModel.apply(createBlogRequest),userId,categoryId);
@PostMapping(value = "/create/user/{user_id}/category/{category_id}",consumes = { MediaType.MULTIPART_FORM_DATA_VALUE })
public ResponseEntity<String> createBlog(@RequestParam("createBlogRequest") String createBlog, @RequestParam("blogCover") MultipartFile blogCover, @PathVariable("user_id") long userId, @PathVariable("category_id") long categoryId) throws Exception {
try {
CreateBlogRequest createBlogRequest = new ObjectMapper().readValue(createBlog, CreateBlogRequest.class);
BlogEntity blogEntity = fromBlogRequestToBlogModel.apply(createBlogRequest);
blogEntity.setImageCover(blogCover.getBytes());
blogServiceImpl.addBlog(blogEntity, userId, categoryId);
}
catch (Exception ex){
throw new Exception("Unable to Fetch Post Data from Request");
}
return new ResponseEntity<>("Blog Created",HttpStatus.CREATED);
}

Expand Down Expand Up @@ -104,7 +120,7 @@ private GetBlogResponse apply(BlogEntity blogEntity){
getBlogResponse.setSubtitle(blogEntity.getSubtitle());
getBlogResponse.setGetTagResponses(blogEntity.getTagEntities().stream().map(fromTagModelToTagResponse).collect(Collectors.toList()));
getBlogResponse.setBody(blogEntity.getBody());
getBlogResponse.setImageCover(blogEntity.getImageCover());
getBlogResponse.setImageCover(Base64Converter.encodeBase64(blogEntity.getImageCover()));
getBlogResponse.setCreatedAt(blogEntity.getCreatedAt());
getBlogResponse.setUserId(blogEntity.getUserEntity().getId());
getBlogResponse.setCategoryId(blogEntity.getCategoryEntity().getId());
Expand Down Expand Up @@ -134,7 +150,6 @@ private BlogEntity apply(CreateBlogRequest createBlogRequest) {
blogEntity.setSubtitle(createBlogRequest.getSubtitle());
blogEntity.setBody(createBlogRequest.getBody());
blogEntity.setTagEntities(createBlogRequest.getTagRequests().stream().map(fromTagRequestToTagModel).collect(Collectors.toList()));
blogEntity.setImageCover(createBlogRequest.getImageCover());
blogEntity.setCreatedAt(LocalDateTime.now());
return blogEntity;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,5 +14,4 @@ public class CreateBlogRequest {

private String body;

private String imageCover;
}
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ public class GetBlogFeedResponse {
private String createdAt;

@JsonProperty("cover")
private String imageCover;
private byte[] imageCover;

@JsonProperty("category")
private String category;
Expand Down
6 changes: 4 additions & 2 deletions src/main/java/com/example/BloggerApp/models/BlogEntity.java
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,10 @@ public class BlogEntity {

private LocalDateTime createdAt;

@NonNull
private String imageCover;

@Lob
@Basic(fetch = FetchType.LAZY)
private byte[] imageCover;

@ManyToOne
private CategoryEntity categoryEntity;
Expand Down
40 changes: 40 additions & 0 deletions src/main/java/com/example/BloggerApp/models/ImageEntity.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package com.example.BloggerApp.models;


import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.OneToOne;

@Entity
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor(force = true)
@Builder
public class ImageEntity {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
@Column(name = "id", nullable = false)
private Long id;

private String name;

private String type;

@Lob
private byte[] imageData;



}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package com.example.BloggerApp.repository;

import com.example.BloggerApp.models.ImageEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface ImageRepository extends JpaRepository<ImageEntity,Long> {
}
11 changes: 11 additions & 0 deletions src/main/java/com/example/BloggerApp/service/ImageService.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package com.example.BloggerApp.service;

import com.example.BloggerApp.models.ImageEntity;
import org.springframework.web.multipart.MultipartFile;

public interface ImageService {

ImageEntity uploadImage(MultipartFile file);

ImageEntity downloadImage(Long imageId);
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.example.BloggerApp.service.impl;

import com.example.BloggerApp.common.utils.Base64Converter;
import com.example.BloggerApp.http.request.TagRequest;
import com.example.BloggerApp.http.request.UpdateBlogRequest;
import com.example.BloggerApp.http.response.GetBlogFeedResponse;
Expand Down Expand Up @@ -74,7 +75,12 @@ public BlogEntity updateBlogEntityId(UpdateBlogRequest updateBlogRequest){
blogEntity.getTagEntities().clear();
blogEntity.setTitle(updateBlogRequest.getTitle());
blogEntity.setBody(updateBlogRequest.getBody());
blogEntity.setImageCover(updateBlogRequest.getImageCover());
try {
blogEntity.setImageCover(Base64Converter.decodeBase64(updateBlogRequest.getImageCover()));
}catch (Exception ex){
System.out.println(ex.getMessage());
}

blogEntity.setSubtitle(updateBlogRequest.getSubtitle());
blogEntity.getTagEntities().addAll(updateBlogRequest.getTagRequests().stream().map(fromTagRequestToTagEntity).collect(Collectors.toList()));
return blogRepository.save(blogEntity);
Expand Down Expand Up @@ -111,7 +117,7 @@ public List<BlogEntity> getBlogEntitiesByUserId(Long userId) {
getBlogFeedResponse.setId(id.longValue());
getBlogFeedResponse.setTitle((String) map.get("title"));
getBlogFeedResponse.setContent((String) map.get("body"));
getBlogFeedResponse.setImageCover((String) map.get("cover"));
getBlogFeedResponse.setImageCover((byte[]) map.get("cover"));
getBlogFeedResponse.setCategory((String) map.get("category"));
getBlogFeedResponse.setAuthorName((String) map.get("username"));
getBlogFeedResponse.setAuthorAvatar((String) map.get("image"));
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package com.example.BloggerApp.service.impl;

import com.example.BloggerApp.common.utils.ImageUtils;
import com.example.BloggerApp.models.ImageEntity;
import com.example.BloggerApp.repository.ImageRepository;
import com.example.BloggerApp.service.ImageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@Service
public class ImageServiceImpl implements ImageService {

@Autowired
private ImageRepository imageRepository;
@Override
public ImageEntity uploadImage(MultipartFile file) {
ImageEntity imageEntity = new ImageEntity();
imageEntity.setName(file.getName());
imageEntity.setType(file.getContentType());
try {
imageEntity.setImageData(ImageUtils.compressImage(file.getBytes()));
}catch (Exception ex){
System.out.println(ex.getMessage());
}

return imageRepository.save(imageEntity);
}

@Override
public ImageEntity downloadImage(Long imageId) {
return imageRepository.findById(imageId).get();
}
}
4 changes: 4 additions & 0 deletions src/main/resources/application.properties
Original file line number Diff line number Diff line change
Expand Up @@ -21,3 +21,7 @@ spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDial

springdoc.api-docs.path=/api-docs
springdoc.swagger-ui.path=/swagger-ui.html


spring.http.multipart.max-file-size=10MB
spring.http.multipart.max-request-size=11MB
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ public void addBlog_ValidInput_Success(){
BlogEntity blogEntity = new BlogEntity();
blogEntity.setSubtitle("Blog-Subtitle");
blogEntity.setBody("This is test blog entity body");
blogEntity.setImageCover("Test image cover");
// blogEntity.setImageCover("Test image cover");
blogEntity.setTitle("DSA");
blogEntity.setCreatedAt(LocalDateTime.now());

Expand All @@ -91,7 +91,7 @@ public void addBlog_ValidInput_Success(){
savedBlogEntity.setId(1L);
savedBlogEntity.setSubtitle("Blog-Subtitle");
savedBlogEntity.setBody("This is test blog entity body");
savedBlogEntity.setImageCover("Test image cover");
// savedBlogEntity.setImageCover("Test image cover");
savedBlogEntity.setTitle("DSA");
savedBlogEntity.setCreatedAt(LocalDateTime.now());

Expand Down Expand Up @@ -135,7 +135,7 @@ public void getBlogById_ValidInput_Success(){
savedBlogEntity.setId(1L);
savedBlogEntity.setSubtitle("Blog-Subtitle");
savedBlogEntity.setBody("This is test blog entity body");
savedBlogEntity.setImageCover("Test image cover");
// savedBlogEntity.setImageCover("Test image cover");
savedBlogEntity.setTitle("DSA");
savedBlogEntity.setCreatedAt(LocalDateTime.now());

Expand Down Expand Up @@ -182,7 +182,7 @@ public void deleteById_ValidInput_Success(){
savedBlogEntity.setId(1L);
savedBlogEntity.setSubtitle("Blog-Subtitle");
savedBlogEntity.setBody("This is test blog entity body");
savedBlogEntity.setImageCover("Test image cover");
// savedBlogEntity.setImageCover("Test image cover");
savedBlogEntity.setTitle("DSA");
savedBlogEntity.setCreatedAt(LocalDateTime.now());

Expand Down
Loading