Commit 36e8ef77 by Patryk Czarnik

Więcej metod w RProducts

parent 4cd6cb08
package sklep.rest;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatusCode;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ResponseStatusException;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
@Component
public class PhotoUtil {
private static final String EXT = ".jpg";
@Value("${alx.photo_dir}")
private String dir;
public File getFile(int productId) {
Path path = getPath(productId);
File file = path.toFile();
if(file.exists()) {
return file;
} else {
throw new ResponseStatusException(HttpStatusCode.valueOf(404), "Brak zdjęcia nr " + productId);
}
}
public byte[] readBytes(int productId) {
Path path = getPath(productId);
try {
return Files.readAllBytes(path);
} catch (IOException e) {
throw new ResponseStatusException(HttpStatusCode.valueOf(404), "Brak zdjęcia nr " + productId);
}
}
public void writeStream(int productId, InputStream inputStream) {
try {
Path path = getPath(productId);
Files.copy(inputStream, path, StandardCopyOption.REPLACE_EXISTING);
} catch (Exception e) {
// wypisujemy błąd, ale metoda kończy się normalnie
e.printStackTrace();
}
}
private Path getPath(int productId) {
String fileName = productId + EXT;
return Paths.get(dir, fileName);
}
public void writeBytes(int productId, byte[] bytes) {
try {
Path path = getPath(productId);
Files.write(path, bytes);
} catch (Exception e) {
e.printStackTrace();
}
}
}
package sklep.rest; package sklep.rest;
import jakarta.ws.rs.*; import jakarta.ws.rs.*;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.UriBuilder;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.web.bind.annotation.PutMapping;
import sklep.model.Product; import sklep.model.Product;
import sklep.repository.ProductRepository; import sklep.repository.ProductRepository;
import java.net.URI;
import java.util.List; import java.util.List;
@Path("/products") @Path("/products")
@Produces({"application/json"}) @Produces({"application/json"})
@Consumes({"application/json"})
public class RProducts { public class RProducts {
@Autowired @Autowired
private ProductRepository productRepository; private ProductRepository productRepository;
@Autowired
private PhotoUtil photoUtil;
@GET @GET
public List<Product> getProducts() { public List<Product> getProducts() {
...@@ -24,4 +32,44 @@ public class RProducts { ...@@ -24,4 +32,44 @@ public class RProducts {
return productRepository.findById(id).orElseThrow(() -> new WebApplicationException(404)); return productRepository.findById(id).orElseThrow(() -> new WebApplicationException(404));
} }
@PUT
@Path("/{id}")
public void update(@PathParam("id") Integer productId, Product product) {
product.setId(productId);
productRepository.save(product);
}
@POST
public Response insert(Product product) {
// Aby mieć pewność, że zapytanie tworzy nowy rekord, ustawiam productId na null.
product.setId(null);
productRepository.save(product);
URI uri = UriBuilder.fromResource(RProducts.class).path("{id}").build(product.getId());
return Response.created(uri).build();
// odpowiedź zgodnie z zasadami HTTP informuje o tym, że powstał nowy rekord pod podanym adresem
}
@DELETE
@Path("/{id}")
public void delete(@PathParam("id") Integer productId) {
try {
productRepository.deleteById(productId);
} catch (EmptyResultDataAccessException e) {
throw new WebApplicationException(e, 404);
}
}
@GET
@Path("/{id}/photo")
@Produces("image/jpeg")
public byte[] getPhoto(@PathParam("id") int productId) {
return photoUtil.readBytes(productId);
}
@PUT
@Path("/{id}/photo")
@Consumes("image/jpeg")
public void uploadPhoto(@PathParam("id") int productId, byte[] bytes) {
photoUtil.writeBytes(productId, bytes);
}
} }
...@@ -19,7 +19,8 @@ public class SecurityConfig { ...@@ -19,7 +19,8 @@ public class SecurityConfig {
.authorizeHttpRequests((authz) -> authz .authorizeHttpRequests((authz) -> authz
.anyRequest().permitAll() .anyRequest().permitAll()
) )
.httpBasic(Customizer.withDefaults()); .httpBasic(Customizer.withDefaults())
.csrf(config -> config.disable());
return httpSecurity.build(); return httpSecurity.build();
} }
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment