diff --git a/src/main/java/net/codejava/AppController.java b/src/main/java/net/codejava/AppController.java index 20461cc..7714c66 100755 --- a/src/main/java/net/codejava/AppController.java +++ b/src/main/java/net/codejava/AppController.java @@ -37,8 +37,18 @@ import org.springframework.dao.DuplicateKeyException; import java.util.Date; import javax.servlet.http.HttpSession; -// import java.util.logging.Logger; -// import java.util.logging.Level; +// improt MultipartFile class +import org.springframework.web.multipart.MultipartFile; +// import portMaooing class +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +// bufferedReader +import java.io.BufferedReader; +import java.io.InputStreamReader; +import java.util.ArrayList; +import java.time.format.DateTimeFormatter; +import java.time.LocalDateTime; +import java.time.ZoneId; @EnableJpaRepositories(basePackages = "net.codejava") @Controller @@ -207,5 +217,56 @@ public void exportToCSV(HttpServletResponse response) throws IOException { writer.newLine(); } writer.flush(); -} + } + + @PostMapping("/import") + public String uploadFile(@RequestParam("file") MultipartFile file, RedirectAttributes redirectAttributes) { + try { + // Parse the file + BufferedReader reader = new BufferedReader(new InputStreamReader(file.getInputStream())); + + // Validate the header + String line = reader.readLine(); // Read the first line + if (line == null || !line.equals("Serial Number,Item Name,Amount,Quantity,Date")) { + throw new IllegalArgumentException("Invalid header. Expected 'Serial Number,Item Name,Amount,Quantity,Date'"); + } + + // Validate the rest of the file + while ((line = reader.readLine()) != null) { + String[] fields = line.split(","); + if (fields.length != 5) { + throw new IllegalArgumentException("Invalid line. Each line should contain exactly 5 fields separated by commas."); + } + } + + // If the file format is valid, convert it to a list of Sale objects + List sales = new ArrayList<>(); + reader = new BufferedReader(new InputStreamReader(file.getInputStream())); // Reset the reader + reader.readLine(); // Skip the header + while ((line = reader.readLine()) != null) { + String[] fields = line.split(","); + Sale sale = new Sale(); + sale.setSerialNumber(fields[0].trim()); + sale.setItem(fields[1].trim()); + + // Convert LocalDate to Date + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); + LocalDate date = LocalDate.parse(fields[4].trim(), formatter); + Date sqlDate = Date.from(date.atStartOfDay(ZoneId.systemDefault()).toInstant()); + sale.setDate(sqlDate); + + sale.setAmount((float) Double.parseDouble(fields[2].trim())); + sale.setQuantity(Integer.parseInt(fields[3].trim())); + sales.add(sale); + } + + // If the file format is valid, call the upload method + dao.saveAll(sales); + redirectAttributes.addFlashAttribute("message", "Successfully saved the list of Sale objects to the database"); + System.out.println("Successfully saved the list of Sale objects to the database"); + } catch (Exception e) { + System.out.println("Error calling dao.saveAll(sales): " + e.getMessage()); + } + return "redirect:/"; + } } diff --git a/src/main/java/net/codejava/SalesDAO.java b/src/main/java/net/codejava/SalesDAO.java index 24e1541..c3e6029 100755 --- a/src/main/java/net/codejava/SalesDAO.java +++ b/src/main/java/net/codejava/SalesDAO.java @@ -124,4 +124,23 @@ public List listAll() { List listSale = jdbcTemplate.query(sql, BeanPropertyRowMapper.newInstance(Sale.class)); return listSale; } + + // save all sales in a list + public void saveAll(List sales) { + if (sales == null) { + throw new IllegalArgumentException("List of sales cannot be null"); + } + + if (jdbcTemplate == null) { + throw new IllegalStateException("JdbcTemplate cannot be null"); + } + + SimpleJdbcInsert insertActor = new SimpleJdbcInsert(jdbcTemplate); + insertActor.withTableName("sales").usingColumns("serial_number", "item", "quantity", "amount", "date"); + + for (Sale sale : sales) { + BeanPropertySqlParameterSource param = new BeanPropertySqlParameterSource(sale); + insertActor.execute(param); + } + } } diff --git a/src/main/java/net/codejava/SecurityConfig.java b/src/main/java/net/codejava/SecurityConfig.java index 6f3d10b..b56f388 100644 --- a/src/main/java/net/codejava/SecurityConfig.java +++ b/src/main/java/net/codejava/SecurityConfig.java @@ -10,6 +10,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.http.HttpMethod; @EnableWebSecurity @@ -24,8 +25,10 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http + .csrf().disable() .authorizeRequests() .antMatchers("/login").permitAll() + .antMatchers(HttpMethod.POST, "/import").permitAll() // .anyRequest().permitAll() .anyRequest().authenticated() .and() diff --git a/src/main/resources/templates/index.html b/src/main/resources/templates/index.html index 9dfc0f8..a158776 100755 --- a/src/main/resources/templates/index.html +++ b/src/main/resources/templates/index.html @@ -51,6 +51,51 @@

Inventory Records

Enter New Product Export to CSV + + +
+

@@ -67,7 +112,7 @@

Inventory Records


- +