Skip to content
Snippets Groups Projects
Commit d75552a9 authored by BEAUVAIS ANTOINE's avatar BEAUVAIS ANTOINE
Browse files

Merge branch 'feature/use_dependency_injection_for_categories' into 'develop'

:recycle: Use dependency injection for categories controller

See merge request !19
parents cc25d276 1278de9d
Branches
2 merge requests!25Develop,!19:recycle: Use dependency injection for categories controller
Showing
with 371 additions and 285 deletions
......@@ -5,6 +5,10 @@ plugins {
id 'war'
}
tasks {
compileJava.inputs.files(processResources)
}
group = 'fr.unistra.sil'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'
......@@ -24,6 +28,7 @@ dependencies {
testImplementation 'org.springframework.boot:spring-boot-starter-test'
implementation 'org.thymeleaf:thymeleaf-spring5'
annotationProcessor "org.springframework.boot:spring-boot-configuration-processor"
}
javadoc {
......
/*
* CONTRAT DE LICENCE DE LOGICIEL LIBRE CeCILL-B
* https://cecill.info/licences/Licence_CeCILL-B_V1-fr.html
*/
package fr.unistra.sil.erp.back;
import fr.unistra.sil.erp.back.db.DatabaseConnectionException;
import fr.unistra.sil.erp.back.db.DatabaseSQLiteImpl;
import fr.unistra.sil.erp.back.db.IDatabase;
/**
* Manages the database implementation to use.
* @author BEAUVAIS ANTOINE
*/
public class DatabaseSystem {
/**
* The database implementation object.
*/
private static IDatabase instance;
/**
* Returns the database implementation in use.In order to change the
* implementation, simply change this method's implementation construction
* to the desired one.
*
* @return the instance of the database implementation.
* @throws DatabaseConnectionException if the connection to the DB failed.
*/
public static IDatabase getInstance() throws DatabaseConnectionException
{
if(DatabaseSystem.instance == null)
DatabaseSystem.instance = new DatabaseSQLiteImpl();
if(DatabaseSystem.instance == null)
throw new DatabaseConnectionException("Failed to create DB.");
return DatabaseSystem.instance;
}
}
......@@ -5,45 +5,47 @@
package fr.unistra.sil.erp.back;
import fr.unistra.sil.erp.back.interceptor.api.ApiAuthenticationInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.PropertySources;
import org.springframework.context.annotation.*;
import org.springframework.core.env.Environment;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Main configuration file for the application.
*
* @author BEAUVAIS ANTOINE
*/
@Configuration
@PropertySources(
@PropertySource("/apikey.properties")
)
@EnableWebMvc
public class WebMvcConfig implements WebMvcConfigurer {
/**
* Autowired environment for retrieving properties.
*/
@Autowired
private Environment env;
private final Environment env;
/**
* API version.
*/
public static final String API_VERSION = "v1";
/**
* API prefix.
*/
public static final String API_PREFIX = "/api/";
/**
* Prefix for API calls.
*/
public static final String API_FULL_PREFIX = API_PREFIX + API_VERSION;
/**
* API Mapping for retrieving all items.
*/
......@@ -72,29 +74,47 @@ public class WebMvcConfig implements WebMvcConfigurer {
* Web mapping for the login page.
*/
public static final String MAPPING_LOGIN = "/login";
/**
* Web mapping for the items list.
*/
public static final String WEB_MAPPING_ITEMS = "/products";
public WebMvcConfig(Environment env) {
this.env = env;
}
/**
* Adds interceptors to the application.
*
* Interceptors process HTTP requests before they reach their
* <p>
* Interceptors process HTTP requests before they reach their
* attributed methods.
*
* Currently, interceptors are only used for authentication in this
* <p>
* Currently, interceptors are only used for authentication in this
* application.
*
*
* @param registry the Interceptor Registry to use for additions.
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new ApiAuthenticationInterceptor(
this.env.getProperty("api.key")))
.addPathPatterns(API_PREFIX + "**");
registry.addInterceptor(new ApiAuthenticationInterceptor(this.env.getRequiredProperty("api.key"))).addPathPatterns(API_PREFIX + "**");
}
/**
* SQL Connection object.
*/
private Connection conn;
@Bean
public Connection connection() {
if (this.conn == null) {
try {
conn = DriverManager.getConnection(env.getRequiredProperty("spring.datasource.url"));
} catch (SQLException ex) {
Logger.getLogger(this.getClass().getName()).log(
Level.SEVERE, "Failed to connect to SQLite file.", ex);
}
}
return conn;
}
}
......@@ -9,18 +9,19 @@ import org.springframework.web.bind.annotation.RequestParam;
/**
* Interface for designing the retrieval of articles.
*
* @author BEAUVAIS ANTOINE
*/
public interface IRetrieveInfoController {
/**
* Retrieves the list of items.
*
* @param cat the optional category to filter.
* @return the list of items as a JSON response/
* @throws Exception if the request cannot be served.
*/
public ResponseEntity<Object> retrieveInfo(
ResponseEntity<Object> retrieveInfo(
@RequestParam(value = "category", defaultValue = "") String cat
) throws Exception;
) throws Exception;
}
......@@ -5,50 +5,46 @@
package fr.unistra.sil.erp.back.controller.api;
import static fr.unistra.sil.erp.back.WebMvcConfig.MAPPING_GETCATEGORIES;
import fr.unistra.sil.erp.back.DatabaseSystem;
import fr.unistra.sil.erp.back.controller.IRetrieveCategoriesController;
import fr.unistra.sil.erp.back.model.Category;
import fr.unistra.sil.erp.back.db.DatabaseConnectionException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import fr.unistra.sil.erp.back.repository.ICategoriesRepository;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import fr.unistra.sil.erp.back.db.IDatabase;
/**
* REST controller for the category list.
*
* @author BEAUVAIS ANTOINE
*/
@RestController
public class ApiRetrieveCategoriesController
implements IRetrieveCategoriesController {
public class ApiRetrieveCategoriesController implements IRetrieveCategoriesController {
private final ICategoriesRepository repository;
public ApiRetrieveCategoriesController(ICategoriesRepository repository) {
this.repository = repository;
}
/**
* Returns the list of categories in JSON format.
*
* @return the HTTP response.
* @throws ApiServerErrorException Database failure.
*/
@GetMapping(MAPPING_GETCATEGORIES)
@Override
public ResponseEntity<Object> getCategories() throws ApiServerErrorException
{
IDatabase db;
try {
db = DatabaseSystem.getInstance();
} catch (DatabaseConnectionException ex) {
Logger.getLogger(ApiRetrieveCategoriesController.class.getName())
.log(Level.SEVERE, "Failed to connect to database.", ex);
throw new ApiServerErrorException("Database failure.");
}
List<Category> res = db.getCategories();
if(res == null)
public ResponseEntity<Object> getCategories() throws ApiServerErrorException {
List<Category> res = repository.getCategories();
if (res == null)
throw new ApiServerErrorException("Database failure.");
return new ResponseEntity<>(res, HttpStatus.OK);
}
}
......@@ -5,71 +5,64 @@
package fr.unistra.sil.erp.back.controller.api;
import static fr.unistra.sil.erp.back.WebMvcConfig.MAPPING_RETRIEVEALL;
import fr.unistra.sil.erp.back.DatabaseSystem;
import fr.unistra.sil.erp.back.controller.IRetrieveInfoController;
import fr.unistra.sil.erp.back.model.Item;
import fr.unistra.sil.erp.back.db.DatabaseConnectionException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import fr.unistra.sil.erp.back.repository.IItemsRepository;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import fr.unistra.sil.erp.back.db.IDatabase;
/**
* REST controller for the item list.
*
* @author BEAUVAIS ANTOINE
*/
@RestController
public class ApiRetrieveItemsController implements IRetrieveInfoController {
private final IItemsRepository repository;
public ApiRetrieveItemsController(IItemsRepository repository) {
this.repository = repository;
}
/**
* Returns all products as a JSON response.
*
* @param cat an optional category.
* @return a JSON response.
* @throws ApiServerErrorException if the request could not be served.
* @throws ApiBadRequestException if the category parameter is invalid.
* @throws ApiBadRequestException if the category parameter is invalid.
*/
@GetMapping(MAPPING_RETRIEVEALL)
public ResponseEntity<Object> retrieveInfo(
@RequestParam(value = "category", defaultValue = "") String cat
) throws ApiServerErrorException, ApiBadRequestException
{
IDatabase db;
try {
db = DatabaseSystem.getInstance();
} catch (DatabaseConnectionException ex) {
Logger.getLogger(ApiRetrieveItemsController.class.getName()).log(
Level.SEVERE, "Could not connect to database.", ex);
throw new ApiServerErrorException("Database failure.");
}
) throws ApiServerErrorException, ApiBadRequestException {
List<Item> res;
if(cat.equals(""))
res = db.getAllItems();
else
{
if (cat.equals(""))
res = repository.getAllItems();
else {
int category;
try
{
try {
category = Integer.parseInt(cat);
}
catch(NumberFormatException ex)
{
} catch (NumberFormatException ex) {
throw new ApiBadRequestException("Category must be a integer.");
}
res = db.getItemsFromCategory(category);
res = repository.getItemsFromCategory(category);
}
if(res == null)
if (res == null)
throw new ApiServerErrorException("Failed to query info.");
else if(res.isEmpty())
else if (res.isEmpty())
return ResponseEntity.noContent().build();
return new ResponseEntity<>(res, HttpStatus.OK);
}
}
......@@ -5,53 +5,49 @@
package fr.unistra.sil.erp.back.controller.api;
import static fr.unistra.sil.erp.back.WebMvcConfig.MAPPING_GETSTOCKS;
import fr.unistra.sil.erp.back.DatabaseSystem;
import fr.unistra.sil.erp.back.controller.IRetrieveStocks;
import fr.unistra.sil.erp.back.db.DatabaseConnectionException;
import fr.unistra.sil.erp.back.model.Stock;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import fr.unistra.sil.erp.back.repository.IStocksRepository;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import fr.unistra.sil.erp.back.db.IDatabase;
/**
* Retrieves stocks in JSON format.
*
* @author BEAUVAIS ANTOINE
*/
@RestController
public class ApiRetrieveStocks implements IRetrieveStocks {
private final IStocksRepository repository;
public ApiRetrieveStocks(IStocksRepository repository) {
this.repository = repository;
}
/**
* Sends the stocks as JSON format back to the client.
* @param request the HTTP request.
*
* @param request the HTTP request.
* @param response the HTTP response.
* @return the response.
* @return the response.
* @throws ApiServerErrorException if the request could not be served.
*/
@GetMapping(MAPPING_GETSTOCKS)
@Override
public ResponseEntity<Object> retrieveStocks(HttpServletRequest request,
HttpServletResponse response) throws ApiServerErrorException {
IDatabase db;
try {
db = DatabaseSystem.getInstance();
} catch (DatabaseConnectionException ex) {
Logger.getLogger(ApiRetrieveCategoriesController.class.getName())
.log(Level.SEVERE, "Failed to connect to database.", ex);
public ResponseEntity<Object> retrieveStocks(HttpServletRequest request, HttpServletResponse response) throws ApiServerErrorException {
List<Stock> res = repository.getStocks();
if (res == null)
throw new ApiServerErrorException("Database failure.");
}
List<Stock> res = db.getStocks();
if(res == null)
throw new ApiServerErrorException("Database failure.");
return new ResponseEntity<>(res, HttpStatus.OK);
}
}
......@@ -6,51 +6,60 @@ package fr.unistra.sil.erp.back.controller.api;
import com.google.gson.Gson;
import com.google.gson.JsonParseException;
import static fr.unistra.sil.erp.back.WebMvcConfig.MAPPING_SUBTRANSAC;
import fr.unistra.sil.erp.back.DatabaseSystem;
import fr.unistra.sil.erp.back.controller.ISubmitTransactionController;
import fr.unistra.sil.erp.back.db.DatabaseConnectionException;
import fr.unistra.sil.erp.back.db.DatabaseResourceNotFoundException;
import fr.unistra.sil.erp.back.db.DatabaseUpdateException;
import fr.unistra.sil.erp.back.repository.DatabaseConnectionException;
import fr.unistra.sil.erp.back.repository.DatabaseResourceNotFoundException;
import fr.unistra.sil.erp.back.repository.DatabaseUpdateException;
import fr.unistra.sil.erp.back.model.Stock;
import fr.unistra.sil.erp.back.model.Transaction;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import fr.unistra.sil.erp.back.repository.IStocksRepository;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import fr.unistra.sil.erp.back.db.IDatabase;
/**
* REST Controller for submitting transactions.
*
* @author BEAUVAIS ANTOINE
*/
@RestController
public class ApiSubmitTransactionController
implements ISubmitTransactionController {
public class ApiSubmitTransactionController implements ISubmitTransactionController {
private final IStocksRepository repository;
public ApiSubmitTransactionController(IStocksRepository repository) {
this.repository = repository;
}
/**
* Handler for transaction submissions.
* @param request the HTTP Servlet Request provided by Spring.
*
* @param request the HTTP Servlet Request provided by Spring.
* @param response the HTTP Servlet Response provided by Spring.
* @return the response for the user.
* @throws ApiBadRequestException if the query failed.
* @throws ApiServerErrorException Server error.
* @throws ApiBadRequestException if the query failed.
* @throws ApiServerErrorException Server error.
* @throws ApiResourceNotFoundException Stock not found.
*/
@RequestMapping(value=MAPPING_SUBTRANSAC, method = RequestMethod.POST)
@RequestMapping(value = MAPPING_SUBTRANSAC, method = RequestMethod.POST)
@Override
public ResponseEntity<Object> submitTransaction(HttpServletRequest request,
HttpServletResponse response)
HttpServletResponse response)
throws ApiBadRequestException, ApiServerErrorException,
ApiResourceNotFoundException
{
ApiResourceNotFoundException {
Gson gson = new Gson();
String body;
try {
......@@ -61,46 +70,39 @@ public class ApiSubmitTransactionController
.log(Level.SEVERE, "Unparseable body.", ex);
throw new ApiBadRequestException("Unparseable body.");
}
if(body == null)
if (body == null)
throw new ApiBadRequestException("Missing JSON body.");
Transaction t;
try
{
try {
t = gson.fromJson(body, Transaction.class);
}
catch(JsonParseException ex)
{
} catch (JsonParseException ex) {
throw new ApiBadRequestException("Invalid JSON: syntax error.");
}
if(t == null)
if (t == null)
throw new ApiBadRequestException("Missing JSON body.");
if(!t.checkIfValid())
if (!t.checkIfValid())
throw new ApiBadRequestException("Invalid JSON schema.");
IDatabase db;
Stock s;
try {
db = DatabaseSystem.getInstance();
s = db.getStockForItem(t.getItem());
if(s == null)
s = repository.getStockForItem(t.getItem());
if (s == null)
throw new ApiServerErrorException("Database failure.");
int newQuantity = s.getQuantity() + t.getQuantity();
if(newQuantity < 0)
if (newQuantity < 0)
newQuantity = 0;
db.updateStock(s.getId(), newQuantity);
repository.updateStock(s.getId(), newQuantity);
} catch (DatabaseConnectionException ex) {
Logger.getLogger(ApiSubmitTransactionController.class.getName())
.log(Level.SEVERE, ex.getMessage(), ex);
throw new ApiServerErrorException("Database failure.");
} catch (DatabaseResourceNotFoundException ex) {
//Logger.getLogger(ApiSubmitTransactionController.class.getName())
// .log(Level.SEVERE, null, ex);
throw new ApiResourceNotFoundException("No stock found for item " +
throw new ApiResourceNotFoundException("No stock found for item " +
t.getItem());
} catch (DatabaseUpdateException ex) {
Logger.getLogger(ApiSubmitTransactionController.class.getName())
......@@ -110,5 +112,5 @@ public class ApiSubmitTransactionController
return new ResponseEntity<>(t, HttpStatus.CREATED);
}
}
package fr.unistra.sil.erp.back.controller.web;
import fr.unistra.sil.erp.back.DatabaseSystem;
import static fr.unistra.sil.erp.back.WebMvcConfig.WEB_MAPPING_ITEMS;
import fr.unistra.sil.erp.back.db.DatabaseConnectionException;
import fr.unistra.sil.erp.back.model.Item;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import fr.unistra.sil.erp.back.repository.IItemsRepository;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
......@@ -19,26 +18,29 @@ import org.springframework.web.bind.annotation.GetMapping;
/**
* Web Controller for the item list.
*
* @author BEAUVAIS ANTOINE
*/
@Controller
public class WebProductsController {
private final IItemsRepository repository;
public WebProductsController(IItemsRepository repository) {
this.repository = repository;
}
/**
* Handles the item list view.
*
* @param model the view's model.
* @return the template to use.
*/
@GetMapping(WEB_MAPPING_ITEMS)
public String products(Model model)
{
try {
List<Item> li = DatabaseSystem.getInstance().getAllItems();
model.addAttribute("items", li);
} catch (DatabaseConnectionException ex) {
Logger.getLogger(WebProductsController.class.getName()).log(Level.SEVERE, null, ex);
}
public String products(Model model) {
List<Item> li = repository.getAllItems();
model.addAttribute("items", li);
return "items";
}
}
......@@ -4,37 +4,46 @@
*/
package fr.unistra.sil.erp.back.controller.web;
import fr.unistra.sil.erp.back.DatabaseSystem;
import fr.unistra.sil.erp.back.db.DatabaseConnectionException;
import fr.unistra.sil.erp.back.repository.DatabaseConnectionException;
import fr.unistra.sil.erp.back.model.RegistryEntry;
import fr.unistra.sil.erp.back.model.Stock;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import fr.unistra.sil.erp.back.repository.IRegistryRepository;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
/**
* Web controller for the registry display page.
*
* @author antoine.beauvais
*/
@Controller
public class WebRegistryController {
private final IRegistryRepository repository;
public WebRegistryController(IRegistryRepository repository) {
this.repository = repository;
}
/**
* Returns the registry view for the Web interface.
*
* @param model the model to populate the template with.
* @return the view.
*/
@GetMapping("registry")
public String stocks(Model model) {
try {
List<RegistryEntry> lr = DatabaseSystem.getInstance().getRegistry();
List<RegistryEntry> lr = repository.getRegistry();
model.addAttribute("stocks", lr);
} catch (DatabaseConnectionException ex) {
Logger.getLogger(WebRegistryController.class.getName()).log(Level.SEVERE, null, ex);
}
return "registry";
}
}
/*
* CONTRAT DE LICENCE DE LOGICIEL LIBRE CeCILL-B
* https://cecill.info/licences/Licence_CeCILL-B_V1-fr.html
*/
package fr.unistra.sil.erp.back.db;
import fr.unistra.sil.erp.back.model.Category;
import fr.unistra.sil.erp.back.model.Item;
import fr.unistra.sil.erp.back.model.RegistryEntry;
import fr.unistra.sil.erp.back.model.Stock;
import java.util.List;
/**
* Standard interface for database implementations.
*
* This interface allows the application to be able to use different
* database systems (CSV, SQLite, MySQL...) by simply switching
* implementations.
* @author BEAUVAIS ANTOINE
*/
public interface IDatabase {
/**
* Returns the list of all items.
* @return the list of all items, or null if an error occurred.
*/
public List<Item> getAllItems();
/**
* Returns the list of all items for a given category.
* @param category the category's identifier.
* @return the list of items, or null if an error occurred.
*/
public List<Item> getItemsFromCategory(int category);
/**
* Returns the list of all categories.
*
* @return the list of categories, or null if an error occurred.
*/
public List<Category> getCategories();
/**
* Returns the list of all stocks.
*
* @return the list of stocks.
*/
public List<Stock> getStocks();
/**
* Returns the stock entry of an item.
* @param itemId the item's ID.
* @return the stock line.
* @throws DatabaseResourceNotFoundException when the query fails.
*/
public Stock getStockForItem(int itemId)
throws DatabaseResourceNotFoundException;
/**
* Updates the specified stock's quantity.
* @param id the stock entry's ID.
* @param quantity the new quantity.
* @throws DatabaseConnectionException when the database is unreachable.
* @throws DatabaseUpdateException when the query fails.
*/
public void updateStock(int id, int quantity)
throws DatabaseConnectionException, DatabaseUpdateException;
/**
* Returns all registry entries.
*/
public List<RegistryEntry> getRegistry() throws DatabaseConnectionException;
}
......@@ -2,7 +2,7 @@
* CONTRAT DE LICENCE DE LOGICIEL LIBRE CeCILL-B
* https://cecill.info/licences/Licence_CeCILL-B_V1-fr.html
*/
package fr.unistra.sil.erp.back.db;
package fr.unistra.sil.erp.back.repository;
/**
* General database error.
......
......@@ -2,7 +2,7 @@
* CONTRAT DE LICENCE DE LOGICIEL LIBRE CeCILL-B
* https://cecill.info/licences/Licence_CeCILL-B_V1-fr.html
*/
package fr.unistra.sil.erp.back.db;
package fr.unistra.sil.erp.back.repository;
/**
* Exception for non-existent database resources.
......
......@@ -2,7 +2,7 @@
* CONTRAT DE LICENCE DE LOGICIEL LIBRE CeCILL-B
* https://cecill.info/licences/Licence_CeCILL-B_V1-fr.html
*/
package fr.unistra.sil.erp.back.db;
package fr.unistra.sil.erp.back.repository;
/**
* Exception for database update failures.
......
package fr.unistra.sil.erp.back.repository;
import fr.unistra.sil.erp.back.model.Category;
import java.util.List;
public interface ICategoriesRepository {
/**
* Returns the list of all categories.
*
* @return the list of categories, or null if an error occurred.
*/
List<Category> getCategories();
}
package fr.unistra.sil.erp.back.repository;
import fr.unistra.sil.erp.back.model.Item;
import java.util.List;
public interface IItemsRepository {
/**
* Returns the list of all items.
* @return the list of all items, or null if an error occurred.
*/
List<Item> getAllItems();
/**
* Returns the list of all items for a given category.
* @param category the category's identifier.
* @return the list of items, or null if an error occurred.
*/
List<Item> getItemsFromCategory(int category);
}
package fr.unistra.sil.erp.back.repository;
import fr.unistra.sil.erp.back.model.RegistryEntry;
import java.util.List;
public interface IRegistryRepository {
/**
* Returns all registry entries.
*/
List<RegistryEntry> getRegistry() throws DatabaseConnectionException;
}
package fr.unistra.sil.erp.back.repository;
import fr.unistra.sil.erp.back.model.Stock;
import java.util.List;
public interface IStocksRepository {
/**
* Returns the list of all stocks.
*
* @return the list of stocks.
*/
List<Stock> getStocks();
/**
* Returns the stock entry of an item.
*
* @param itemId the item's ID.
* @return the stock line.
* @throws DatabaseResourceNotFoundException when the query fails.
*/
Stock getStockForItem(int itemId)
throws DatabaseResourceNotFoundException;
/**
* Updates the specified stock's quantity.
*
* @param id the stock entry's ID.
* @param quantity the new quantity.
* @throws DatabaseConnectionException when the database is unreachable.
* @throws DatabaseUpdateException when the query fails.
*/
void updateStock(int id, int quantity)
throws DatabaseConnectionException, DatabaseUpdateException;
}
package fr.unistra.sil.erp.back.repository;
import org.springframework.stereotype.Repository;
import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;
@Repository
public class SqliteRepository {
/**
* SQL Connection object.
*/
protected final Connection conn;
/**
* Class constructor.
*/
public SqliteRepository(Connection conn) {
this.conn = conn;
}
/**
* Executes a standard query, without parameters.
*
* @param query the string's query.
* @return the result set for this query.
*/
protected ResultSet query(String query) {
Statement stmt;
ResultSet rs;
try {
stmt = this.conn.createStatement();
rs = stmt.executeQuery(query);
} catch (SQLException ex) {
Logger.getLogger(this.getClass().getName()).log(
Level.SEVERE, "Failed to run query: " + query, ex);
return null;
}
return rs;
}
}
package fr.unistra.sil.erp.back.repository.category;
import fr.unistra.sil.erp.back.model.Category;
import fr.unistra.sil.erp.back.repository.ICategoriesRepository;
import fr.unistra.sil.erp.back.repository.SqliteRepository;
import org.springframework.stereotype.Repository;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
@Repository
public class SqliteCategoryRepository extends SqliteRepository implements ICategoriesRepository {
/**
* Query used to retrieve all categories stored in the database.
*/
private static final String SQL_GETCATEGORIES =
"SELECT id, name FROM categories";
public SqliteCategoryRepository(Connection conn) {
super(conn);
}
@Override
public List<Category> getCategories() {
ResultSet rs = this.query(SQL_GETCATEGORIES);
if (rs == null)
return null;
List<Category> res = new ArrayList<>();
try {
while (rs.next()) {
Category c = new Category(rs.getInt("id"), rs.getString("name"));
res.add(c);
}
} catch (SQLException ex) {
Logger.getLogger(this.getClass().getName()).log(
Level.SEVERE, "Failed to fetch results.", ex);
return null;
}
return res;
}
}
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