1 | package com.example.salonbella.service;
|
---|
2 |
|
---|
3 | import com.example.salonbella.entity.ProductEntity;
|
---|
4 | import com.example.salonbella.repository.ProductRepository;
|
---|
5 | import org.springframework.beans.factory.annotation.Autowired;
|
---|
6 | import org.springframework.stereotype.Service;
|
---|
7 | import org.springframework.web.multipart.MultipartFile;
|
---|
8 |
|
---|
9 | import javax.transaction.Transactional;
|
---|
10 | import java.io.ByteArrayOutputStream;
|
---|
11 | import java.io.IOException;
|
---|
12 | import java.util.Base64;
|
---|
13 | import java.util.List;
|
---|
14 | import java.util.Optional;
|
---|
15 | import java.util.zip.DataFormatException;
|
---|
16 | import java.util.zip.Inflater;
|
---|
17 |
|
---|
18 | @Service
|
---|
19 | public class ProductService {
|
---|
20 |
|
---|
21 | private final ProductRepository productRepository;
|
---|
22 |
|
---|
23 | @Autowired
|
---|
24 | public ProductService(ProductRepository productRepository) {
|
---|
25 | this.productRepository = productRepository;
|
---|
26 | }
|
---|
27 |
|
---|
28 | public void addProduct(String name, String category, String price, String description, MultipartFile multipartFile) throws IOException {
|
---|
29 | ProductEntity productEntity = new ProductEntity();
|
---|
30 | productEntity.setName(name);
|
---|
31 | productEntity.setContent(multipartFile.getBytes());
|
---|
32 | productEntity.setDescription(description);
|
---|
33 | productEntity.setCategory(category);
|
---|
34 | productEntity.setPrice(Double.parseDouble(price));
|
---|
35 | productRepository.save(productEntity);
|
---|
36 | }
|
---|
37 |
|
---|
38 | public List<ProductEntity> getProducts() {
|
---|
39 | List<ProductEntity> productEntities = productRepository.findAll();
|
---|
40 | for (ProductEntity p : productEntities) {
|
---|
41 | p.setBase64(Base64.getEncoder().encodeToString(p.getContent()));
|
---|
42 | }
|
---|
43 | return productEntities;
|
---|
44 | }
|
---|
45 |
|
---|
46 | public byte[] decompressBytes(byte[] data) {
|
---|
47 | Inflater inflater = new Inflater();
|
---|
48 | inflater.setInput(data);
|
---|
49 | ByteArrayOutputStream outputStream = new ByteArrayOutputStream(data.length);
|
---|
50 | byte[] buffer = new byte[1024];
|
---|
51 | try {
|
---|
52 | while (!inflater.finished()) {
|
---|
53 | int count = inflater.inflate(buffer);
|
---|
54 | outputStream.write(buffer, 0, count);
|
---|
55 | }
|
---|
56 | outputStream.close();
|
---|
57 | } catch (IOException ioe) {
|
---|
58 | } catch (DataFormatException e) {
|
---|
59 | }
|
---|
60 | return outputStream.toByteArray();
|
---|
61 | }
|
---|
62 |
|
---|
63 | @Transactional
|
---|
64 | public void removeProduct(Long id) {
|
---|
65 | Optional<ProductEntity> product = productRepository.findById(id);
|
---|
66 | product.ifPresent(productRepository::delete);
|
---|
67 | }
|
---|
68 | }
|
---|