This commit is contained in:
Dell 2026-04-09 09:05:18 +03:00
commit 957338e676
39 changed files with 1424 additions and 0 deletions

73
pom.xml Normal file
View File

@ -0,0 +1,73 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>flight-application</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<maven.compiler.source>25</maven.compiler.source>
<maven.compiler.target>25</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<!-- JSTL API -->
<dependency>
<groupId>jakarta.servlet.jsp.jstl</groupId>
<artifactId>jakarta.servlet.jsp.jstl-api</artifactId>
<version>3.0.0</version>
</dependency>
<!-- JSTL Implementation -->
<dependency>
<groupId>org.glassfish.web</groupId>
<artifactId>jakarta.servlet.jsp.jstl</artifactId>
<version>3.0.1</version>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.7.10</version>
<scope>compile</scope>
</dependency>
<!-- Source: https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.44</version>
<scope>compile</scope>
</dependency>
<!-- Source: https://mvnrepository.com/artifact/org.apache.maven.plugins/maven-war-plugin -->
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.15.0</version>
<configuration>
<annotationProcessorPaths>
<path>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.44</version>
</path>
</annotationProcessorPaths>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,25 @@
package org.example.je.jdbc;
import org.example.je.jdbc.dao.FlightDao;
import org.example.je.jdbc.dao.TicketDao;
import org.example.je.jdbc.dto.TicketFilter;
import org.example.je.jdbc.entity.Ticket;
import utils.ConnectionManager;
import java.math.BigDecimal;
import java.sql.DriverManager;
import java.sql.SQLException;
public class JdbcRunner {
static void main() throws SQLException {
var ticketDao = TicketDao.getInstance();
var filter = new TicketFilter(null, null, 3, 1);
System.out.println(ticketDao.findAll(filter));
// var flightDao = FlightDao.getInstance();
//System.out.println(flightDao.findAll());
}
}

View File

@ -0,0 +1,13 @@
package org.example.je.jdbc.dao;
import java.sql.Connection;
import java.util.List;
import java.util.Optional;
public interface Dao<K, E> {
E save(E e);
boolean update(E e);
boolean delete(K id);
List<E> findAll();
Optional<E> findById(Long id);
}

View File

@ -0,0 +1,112 @@
package org.example.je.jdbc.dao;
import org.example.je.jdbc.entity.Flight;
import org.example.je.jdbc.entity.FlightStatus;
import org.example.je.jdbc.exeption.DaoException;
import utils.ConnectionManager;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
public class FlightDao implements Dao<Long, Flight> {
private final static FlightDao INSTANCE = new FlightDao();
private final static String FIND_ALL_SQL = """
SELECT
id, flight_no, departure_date, departure_airport_code, arrival_date, arrival_airport_code, aircraft_id, status
FROM public.flight
""";
private static final String FIND_BY_ID_SQL = """
SELECT
id, flight_no, departure_date, departure_airport_code, arrival_date, arrival_airport_code, aircraft_id, status
FROM public.flight
WHERE id = ?
""";
@Override
public Flight save(Flight flight) {
return null;
}
@Override
public boolean update(Flight flight) {
return false;
}
@Override
public boolean delete(Long id) {
return false;
}
@Override
public List<Flight> findAll() {
try (var connection = ConnectionManager.get();
var statement = connection.prepareStatement(FIND_ALL_SQL)) {
List<Flight> flights = new ArrayList<Flight>();
var recordSet = statement.executeQuery();
while (recordSet.next()) {
flights.add(
buildFlight(recordSet)
);
}
return flights;
} catch (SQLException e) {
throw new DaoException(e);
}
}
@Override
public Optional<Flight> findById(Long id) {
try (var connection = ConnectionManager.get();) {
return findById(id, connection);
} catch (SQLException e) {
throw new DaoException(e);
}
}
private Flight buildFlight(ResultSet resultSet) throws SQLException {
return new Flight(
resultSet.getLong("id"),
resultSet.getString("flight_no"),
resultSet.getTimestamp("departure_date").toLocalDateTime(),
resultSet.getString("departure_airport_code"),
resultSet.getTimestamp("arrival_date").toLocalDateTime(),
resultSet.getString("arrival_airport_code"),
resultSet.getLong("aircraft_id"),
FlightStatus.valueOf(resultSet.getString("status"))
);
}
public Optional<Flight> findById(Long id, Connection connection) {
try (var statement = connection.prepareStatement(FIND_BY_ID_SQL)) {
Flight flight = null;
statement.setLong(1, id);
var recordSet = statement.executeQuery();
if (recordSet.next()) {
flight = buildFlight(recordSet);
}
return Optional.ofNullable(flight);
} catch (SQLException e) {
throw new DaoException(e);
}
}
public static FlightDao getInstance() {
return INSTANCE;
}
}

View File

@ -0,0 +1,238 @@
package org.example.je.jdbc.dao;
import org.example.je.jdbc.dto.TicketFilter;
import org.example.je.jdbc.entity.Ticket;
import org.example.je.jdbc.exeption.DaoException;
import utils.ConnectionManager;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.*;
import java.util.stream.Collectors;
public class TicketDao implements Dao<Long, Ticket>{
private final static FlightDao flightDao = FlightDao.getInstance();
private final static TicketDao INSTANCE = new TicketDao();
private final static String SAVE_SQL = """
INSERT INTO public.ticket(
passport_no, passanger_name, flight_id, seat_no, cost)
VALUES (?, ?, ?, ?, ?);
""";
private final static String UPDATE_SQL = """
UPDATE public.ticket SET
passport_no = ?,
passanger_name = ?,
flight_id = ?,
seat_no = ?,
cost = ?
WHERE id = ?;
""";
private final static String DELETE_SQL = """
DELETE from public.ticket WHERE id = ?;
""";
private final static String FIND_ALL_BY_FLIGHT_ID_SQL = """
SELECT id, passport_no, passanger_name, flight_id, seat_no, cost
FROM public.ticket
WHERE flight_id = ?
""";
private final static String FIND_ALL_SQL = """
SELECT id, passport_no, passanger_name, flight_id, seat_no, cost
FROM public.ticket
""";
private final static String FIND_BY_ID_SQL = """
SELECT id, passport_no, passanger_name, flight_id, seat_no, cost
FROM public.ticket
WHERE id = ?;
""";
public Ticket save(Ticket ticket) {
try (var connection = ConnectionManager.get();
var statement = connection.prepareStatement(SAVE_SQL, Statement.RETURN_GENERATED_KEYS)) {
statement.setString(1, ticket.getPassportNo());
statement.setString(2, ticket.getPassengerName());
statement.setLong(3, ticket.getFlight().getId());
statement.setString(4, ticket.getSeatNo());
statement.setBigDecimal(5, ticket.getCost());
statement.executeUpdate();
var keys = statement.getGeneratedKeys();
if (keys.next()) {
ticket.setId(keys.getLong("id"));
}
return ticket;
} catch (SQLException e) {
throw new DaoException(e);
}
}
public boolean update(Ticket ticket) {
try (var connection = ConnectionManager.get();
var statement = connection.prepareStatement(UPDATE_SQL)) {
statement.setString(1, ticket.getPassportNo());
statement.setString(2, ticket.getPassengerName());
statement.setLong(3, ticket.getFlight().getId());
statement.setString(4, ticket.getSeatNo());
statement.setBigDecimal(5, ticket.getCost());
statement.setLong(6, ticket.getId());
return statement.execute();
} catch (SQLException e) {
throw new DaoException(e);
}
}
public boolean delete(Long id) {
try (var connection = ConnectionManager.get();
var statement = connection.prepareStatement(DELETE_SQL)) {
statement.setLong(1, id);
return statement.execute();
} catch (SQLException e) {
throw new DaoException(e);
}
}
public List<Ticket> findAll() {
try (var connection = ConnectionManager.get();
var statement = connection.prepareStatement(FIND_ALL_SQL)) {
List<Ticket> tickets = new ArrayList<Ticket>();
var recordSet = statement.executeQuery();
while (recordSet.next()) {
tickets.add(buildTicket(recordSet));
}
return tickets;
} catch (SQLException e) {
throw new DaoException(e);
}
}
private Ticket buildTicket(ResultSet recordSet) throws SQLException {
return new Ticket(
recordSet.getLong("id"),
recordSet.getString("passport_no"),
recordSet.getString("passanger_name"),
flightDao.findById(recordSet.getLong("flight_id"), recordSet.getStatement().getConnection()).get(),
recordSet.getString("seat_no"),
recordSet.getBigDecimal("cost")
);
}
public List<Ticket> findAll(TicketFilter filter) {
List<Object> parameters = new ArrayList<Object>();
List<String> whereSql = new ArrayList<>();
if(filter.passangerName()!= null) {
parameters.add(filter.passangerName());
whereSql.add("passanger_name= ?");
}
if(filter.seatNo()!= null) {
parameters.add("%" + filter.seatNo() + "%");
whereSql.add("seat_no like ?");
}
parameters.add(filter.offset());
parameters.add(filter.limit());
var where = whereSql.stream().collect(Collectors.joining(
" AND ",
parameters.size() > 2 ? " WHERE " : "",
" OFFSET ? LIMIT ? "
));
String sql = FIND_ALL_SQL + where;
try (var connection = ConnectionManager.get();
var statement = connection.prepareStatement(sql)) {
for (int i = 0; i < parameters.size(); i++) {
statement.setObject(i+1, parameters.get(i));
}
List<Ticket> tickets = new ArrayList<Ticket>();
var recordSet = statement.executeQuery();
while (recordSet.next()) {
tickets.add(new Ticket(
recordSet.getLong("id"),
recordSet.getString("passport_no"),
recordSet.getString("passanger_name"),
flightDao.findById(recordSet.getLong("flight_id"), recordSet.getStatement().getConnection()).get(),
recordSet.getString("seat_no"),
recordSet.getBigDecimal("cost")
));
}
return tickets;
} catch (SQLException e) {
throw new DaoException(e);
}
}
public List<Ticket> findAllByFlightId(Long id){
try (var connection = ConnectionManager.get();
var statement = connection.prepareStatement(FIND_ALL_BY_FLIGHT_ID_SQL)) {
statement.setLong(1, id);
List<Ticket> tickets = new ArrayList<Ticket>();
var recordSet = statement.executeQuery();
while (recordSet.next()) {
tickets.add(buildTicket(recordSet));
}
return tickets;
} catch (SQLException e) {
throw new DaoException(e);
}
}
public Optional<Ticket> findById(Long id) {
try (var connection = ConnectionManager.get();
var statement = connection.prepareStatement(FIND_BY_ID_SQL)) {
Ticket ticket = null;
statement.setLong(1, id);
var recordSet = statement.executeQuery();
if (recordSet.next()) {
ticket = new Ticket(
recordSet.getLong("id"),
recordSet.getString("passport_no"),
recordSet.getString("passanger_name"),
flightDao.findById(recordSet.getLong("flight_id"), recordSet.getStatement().getConnection()).get(),
recordSet.getString("seat_no"),
recordSet.getBigDecimal("cost"));
}
return Optional.ofNullable(ticket);
} catch (SQLException e) {
throw new DaoException(e);
}
}
public static TicketDao getInstance() {
return INSTANCE;
}
private TicketDao() {
}
}

View File

@ -0,0 +1,70 @@
package org.example.je.jdbc.dao;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.example.je.jdbc.entity.User;
import org.example.je.jdbc.exeption.DaoException;
import utils.ConnectionManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
import java.util.Optional;
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class UserDao implements Dao<Long, User> {
private final static UserDao INSTANCE = new UserDao();
private final static String SAVE_SQL = """
INSERT INTO public.users(
name, birthdate, email, password, role, gender)
VALUES (?, ?, ?, ?, ?, ?);
""";
@Override
public User save(User user) {
try (var connection = ConnectionManager.get();
var statement = connection.prepareStatement(SAVE_SQL, Statement.RETURN_GENERATED_KEYS)) {
statement.setObject(1, user.getName());
statement.setObject(2, user.getBirthdate());
statement.setObject(3, user.getEmail());
statement.setObject(4, user.getPassword());
statement.setObject(5, user.getRole().name());
statement.setObject(6, user.getGender().name());
statement.executeUpdate();
var keys = statement.getGeneratedKeys();
if (keys.next()) {
user.setId(keys.getLong("id"));
}
return user;
} catch (SQLException e) {
throw new DaoException(e);
}
}
@Override
public boolean update(User user) {
return false;
}
@Override
public boolean delete(Long id) {
return false;
}
@Override
public List<User> findAll() {
return List.of();
}
@Override
public Optional<User> findById(Long id) {
return Optional.empty();
}
public static UserDao getInstance() {
return INSTANCE;
}
}

View File

@ -0,0 +1,15 @@
package org.example.je.jdbc.dto;
import lombok.Builder;
import lombok.Value;
@Value
@Builder
public class CreateUserDto {
String name;
String email;
String password;
String role;
String gender;
String birthdate;
}

View File

@ -0,0 +1,4 @@
package org.example.je.jdbc.dto;
public record FlightDto(Long id, String description) {
}

View File

@ -0,0 +1,4 @@
package org.example.je.jdbc.dto;
public record TicketDto(Long id, Long flightId, String seatNo) {
}

View File

@ -0,0 +1,5 @@
package org.example.je.jdbc.dto;
public record TicketFilter(String passangerName, String seatNo, int offset, int limit) {
}

View File

@ -0,0 +1,11 @@
package org.example.je.jdbc.dto;
import lombok.Builder;
import lombok.Data;
@Data
@Builder
public class UserDto {
private Long id;
private String email;
}

View File

@ -0,0 +1,119 @@
package org.example.je.jdbc.entity;
import java.time.LocalDateTime;
import java.util.Objects;
public class Flight {
private Long id;
private String flightNo;
private LocalDateTime departureDate;
private String departureAirportCode;
private LocalDateTime arrivalDate;
private String arrivalAirportCode;
private Long aircraftId;
private FlightStatus status;
public Flight() {
}
@Override
public boolean equals(Object o) {
if (o == null || getClass() != o.getClass()) return false;
Flight flight = (Flight) o;
return Objects.equals(id, flight.id) && Objects.equals(flightNo, flight.flightNo) && Objects.equals(departureDate, flight.departureDate) && Objects.equals(departureAirportCode, flight.departureAirportCode) && Objects.equals(arrivalDate, flight.arrivalDate) && Objects.equals(arrivalAirportCode, flight.arrivalAirportCode) && Objects.equals(aircraftId, flight.aircraftId) && Objects.equals(status, flight.status);
}
@Override
public int hashCode() {
return Objects.hash(id, flightNo, departureDate, departureAirportCode, arrivalDate, arrivalAirportCode, aircraftId, status);
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getFlightNo() {
return flightNo;
}
public void setFlightNo(String flightNo) {
this.flightNo = flightNo;
}
public LocalDateTime getDepartureDate() {
return departureDate;
}
public void setDepartureDate(LocalDateTime departureDate) {
this.departureDate = departureDate;
}
public String getDepartureAirportCode() {
return departureAirportCode;
}
public void setDepartureAirportCode(String departureAirportCode) {
this.departureAirportCode = departureAirportCode;
}
public LocalDateTime getArrivalDate() {
return arrivalDate;
}
public void setArrivalDate(LocalDateTime arrivalDate) {
this.arrivalDate = arrivalDate;
}
public String getArrivalAirportCode() {
return arrivalAirportCode;
}
public void setArrivalAirportCode(String arrivalAirportCode) {
this.arrivalAirportCode = arrivalAirportCode;
}
public Long getAircraftId() {
return aircraftId;
}
public void setAircraftId(Long aircraftId) {
this.aircraftId = aircraftId;
}
public FlightStatus getStatus() {
return status;
}
public void setStatus(FlightStatus status) {
this.status = status;
}
public Flight(Long id, String flightNo, LocalDateTime departureDate, String departureAirportCode, LocalDateTime arrivalDate, String arrivalAirportCode, Long aircraftId, FlightStatus status) {
this.id = id;
this.flightNo = flightNo;
this.departureDate = departureDate;
this.departureAirportCode = departureAirportCode;
this.arrivalDate = arrivalDate;
this.arrivalAirportCode = arrivalAirportCode;
this.aircraftId = aircraftId;
this.status = status;
}
@Override
public String toString() {
return "Flight{" +
"id=" + id +
", flightNo='" + flightNo + '\'' +
", departureDate=" + departureDate +
", departureAirportCode='" + departureAirportCode + '\'' +
", arrivalDate=" + arrivalDate +
", arrivalAirportCode='" + arrivalAirportCode + '\'' +
", aircraftId=" + aircraftId +
", status=" + status +
'}';
}
}

View File

@ -0,0 +1,9 @@
package org.example.je.jdbc.entity;
public enum FlightStatus {
SCHEDULED,
BOARDING,
DEPARTED,
ARRIVED,
CANCELLED
}

View File

@ -0,0 +1,14 @@
package org.example.je.jdbc.entity;
import java.util.Arrays;
import java.util.Optional;
public enum Gender {
MALE, FEMALE;
public static Optional<Gender> find(String gender){
return Arrays.stream(values())
.filter(it -> it.name().equals(gender))
.findFirst();
}
}

View File

@ -0,0 +1,14 @@
package org.example.je.jdbc.entity;
import java.util.Arrays;
import java.util.Optional;
public enum Role {
ADMIN, USER;
public static Optional<Role> find(String role){
return Arrays.stream(values())
.filter(it -> it.name().equals(role))
.findFirst();
}
}

View File

@ -0,0 +1,97 @@
package org.example.je.jdbc.entity;
import java.math.BigDecimal;
import java.util.Objects;
public class Ticket {
private Long id;
private String passportNo;
private String passengerName;
private Flight flight;
private String seatNo;
private BigDecimal cost;
public Ticket() {
}
public Ticket(Long id, String passportNo, String passengerName, Flight flight, String seatNo, BigDecimal cost) {
this.id = id;
this.passportNo = passportNo;
this.passengerName = passengerName;
this.flight = flight;
this.seatNo = seatNo;
this.cost = cost;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getPassportNo() {
return passportNo;
}
public void setPassportNo(String passportNo) {
this.passportNo = passportNo;
}
public String getPassengerName() {
return passengerName;
}
public void setPassengerName(String passengerName) {
this.passengerName = passengerName;
}
public Flight getFlight() {
return flight;
}
public void setFlightId(Flight flight) {
this.flight = flight;
}
public String getSeatNo() {
return seatNo;
}
public void setSeatNo(String seatNo) {
this.seatNo = seatNo;
}
public BigDecimal getCost() {
return cost;
}
public void setCost(BigDecimal cost) {
this.cost = cost;
}
@Override
public String toString() {
return "Ticket{" +
"id=" + id +
", passportNo='" + passportNo + '\'' +
", passengerName='" + passengerName + '\'' +
", flightId=" + flight +
", seatNo='" + seatNo + '\'' +
", cost=" + cost +
'}';
}
@Override
public boolean equals(Object o) {
if (o == null || getClass() != o.getClass()) return false;
Ticket ticket = (Ticket) o;
return Objects.equals(id, ticket.id) && Objects.equals(passportNo, ticket.passportNo) && Objects.equals(passengerName, ticket.passengerName) && Objects.equals(flight, ticket.flight) && Objects.equals(seatNo, ticket.seatNo) && Objects.equals(cost, ticket.cost);
}
@Override
public int hashCode() {
return Objects.hash(id, passportNo, passengerName, flight, seatNo, cost);
}
}

View File

@ -0,0 +1,22 @@
package org.example.je.jdbc.entity;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import java.time.LocalDate;
@Data
@AllArgsConstructor
@Builder
public class User {
private Long id;
private String name;
private String email;
private String password;
private Role role;
private Gender gender;
private LocalDate birthdate;
}

View File

@ -0,0 +1,9 @@
package org.example.je.jdbc.exeption;
import java.sql.SQLException;
public class DaoException extends RuntimeException {
public DaoException(Throwable e) {
super(e);
}
}

View File

@ -0,0 +1,29 @@
package org.example.je.jdbc.mapper;
import org.example.je.jdbc.dto.CreateUserDto;
import org.example.je.jdbc.entity.Gender;
import org.example.je.jdbc.entity.Role;
import org.example.je.jdbc.entity.User;
import utils.LocalDateTimeFormatter;
public class CreateUserMapper implements Mapper<User, CreateUserDto> {
private static final CreateUserMapper INSTANCE = new CreateUserMapper();
public static CreateUserMapper getInstance(){
return INSTANCE;
}
@Override
public User mapFrom(CreateUserDto createUserDto) {
return User.builder()
.name(createUserDto.getName())
.role(Role.valueOf(createUserDto.getRole()))
.gender(Gender.valueOf(createUserDto.getGender()))
.birthdate(LocalDateTimeFormatter.format(createUserDto.getBirthdate()))
.password(createUserDto.getPassword())
.email(createUserDto.getEmail())
.build();
}
}

View File

@ -0,0 +1,5 @@
package org.example.je.jdbc.mapper;
public interface Mapper <T,F>{
T mapFrom(F f);
}

View File

@ -0,0 +1,30 @@
package org.example.je.jdbc.service;
import org.example.je.jdbc.dao.FlightDao;
import org.example.je.jdbc.dto.FlightDto;
import java.util.List;
import java.util.stream.Collectors;
public class FlightService {
private static final FlightService INSTANCE = new FlightService();
private static final FlightDao flightDao = FlightDao.getInstance();
public static FlightService getInstance(){
return INSTANCE;
}
private FlightService() {
}
public List<FlightDto> findAll(){
return flightDao.findAll().stream().map(flight ->
new FlightDto(
flight.getId(),
"%s - %s - %s".formatted(
flight.getDepartureAirportCode(),
flight.getArrivalAirportCode(),
flight.getStatus()
))).collect(Collectors.toList());
}
}

View File

@ -0,0 +1,31 @@
package org.example.je.jdbc.service;
import org.example.je.jdbc.dao.FlightDao;
import org.example.je.jdbc.dao.TicketDao;
import org.example.je.jdbc.dto.FlightDto;
import org.example.je.jdbc.dto.TicketDto;
import java.util.List;
import java.util.stream.Collectors;
public class TicketService {
private static final TicketService INSTANCE = new TicketService();
private static final TicketDao ticketDao = TicketDao.getInstance();
public static TicketService getInstance(){
return INSTANCE;
}
private TicketService() {
}
public List<TicketDto> findAllByFlightId(Long id){
return ticketDao.findAllByFlightId(id).stream().map(ticket ->
new TicketDto(
ticket.getId(),
ticket.getFlight().getId(),
ticket.getSeatNo()
)).collect(Collectors.toList());
}
}

View File

@ -0,0 +1,27 @@
package org.example.je.jdbc.service;
import org.example.je.jdbc.dao.TicketDao;
import org.example.je.jdbc.dao.UserDao;
import org.example.je.jdbc.dto.CreateUserDto;
import org.example.je.jdbc.mapper.CreateUserMapper;
public class UserService {
private static final UserService INSTANCE = new UserService();
private static final UserDao userDao = UserDao.getInstance();
private static final CreateUserMapper createUserMapper = CreateUserMapper.getInstance();
public static UserService getInstance(){
return INSTANCE;
}
public Long create(CreateUserDto createUserDto ){
var user = createUserMapper.mapFrom(createUserDto);
userDao.save(user);
return user.getId();
}
private UserService() {
}
}

View File

@ -0,0 +1,24 @@
package org.example.je.jdbc.servlet;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.example.je.jdbc.service.FlightService;
import utils.JspHelper;
import java.io.IOException;
@WebServlet("/content")
public class ContentServlet extends HttpServlet {
private final static FlightService flightService = FlightService.getInstance();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
var flights = flightService.findAll();
req.setAttribute("flights", flights);
req.getRequestDispatcher(JspHelper.getPath("content")).forward(req, resp);
}
}

View File

@ -0,0 +1,29 @@
package org.example.je.jdbc.servlet;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
@WebServlet("/cookies")
public class CookiesServlet extends HttpServlet {
private final static String UNIQUE_USER="userId";
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
var cookies = req.getCookies();
if(cookies == null || Arrays.stream(cookies).filter(cookie -> UNIQUE_USER.equals(cookie.getName())).findFirst().isEmpty())
{
var cookie = new Cookie(UNIQUE_USER, "1");
cookie.setMaxAge(60 * 60);
cookie.setPath("/cookies");
resp.addCookie(cookie);
}
}
}

View File

@ -0,0 +1,20 @@
package org.example.je.jdbc.servlet;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/dispatcher")
public class DispatcherServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
var dispatcher = req.getRequestDispatcher("/flights");
req.setAttribute("dispatcher", true);
dispatcher.include(req, resp);
}
}

View File

@ -0,0 +1,26 @@
package org.example.je.jdbc.servlet;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.example.je.jdbc.service.FlightService;
import utils.JspHelper;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
@WebServlet("/flights")
public class FlightServlet extends HttpServlet {
private static final FlightService flightService = FlightService.getInstance();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html");
resp.setCharacterEncoding(StandardCharsets.UTF_8.name());
req.setAttribute("flights", flightService.findAll());
req.getRequestDispatcher(JspHelper.getPath("flights")).forward(req, resp);
}
}

View File

@ -0,0 +1,41 @@
package org.example.je.jdbc.servlet;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.example.je.jdbc.dto.CreateUserDto;
import org.example.je.jdbc.mapper.CreateUserMapper;
import org.example.je.jdbc.service.UserService;
import utils.JspHelper;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;
@WebServlet("/registration")
public class RegistrationServlet extends HttpServlet {
private static UserService userService = UserService.getInstance();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setAttribute("roles", List.of("ADMIN","USER"));
req.setAttribute("genders", List.of("MALE","FEMALE"));
req.getRequestDispatcher(JspHelper.getPath("registration")).forward(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
CreateUserDto userDto = CreateUserDto.builder()
.name(req.getParameter("name"))
.email(req.getParameter("email"))
.role(req.getParameter("role"))
.gender(req.getParameter("gender"))
.birthdate(req.getParameter("birthdate"))
.password(req.getParameter("password"))
.build();
userService.create(userDto);
}
}

View File

@ -0,0 +1,30 @@
package org.example.je.jdbc.servlet;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.example.je.jdbc.dto.UserDto;
import java.io.IOException;
@WebServlet("/session")
public class SessionServlet extends HttpServlet {
private static final String USER = "user";
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
var session = req.getSession();
var user = session.getAttribute(USER);
if(user == null) {
user = UserDto.builder()
.id(5L)
.email("test@mail.com")
.build();
//System.out.println(user.toString());
}
session.setAttribute(USER, user);
}
}

View File

@ -0,0 +1,28 @@
package org.example.je.jdbc.servlet;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.example.je.jdbc.service.TicketService;
import utils.JspHelper;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
@WebServlet("/tickets")
public class TicketServlet extends HttpServlet {
private static final TicketService ticketService= TicketService.getInstance();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Long flightId = Long.valueOf(req.getParameter("flight"));
resp.setContentType("text/html");
resp.setCharacterEncoding(StandardCharsets.UTF_8.name());
req.setAttribute("tickets", ticketService.findAllByFlightId(flightId));
req.getRequestDispatcher(JspHelper.getPath("tickets")).forward(req, resp);
}
}

View File

@ -0,0 +1,70 @@
package utils;
import java.lang.reflect.Proxy;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
public final class ConnectionManager {
private static final String DB_URL_KEY = "db.url";
private static final String DB_USER_KEY = "db.user";
private static final String DB_PASSWORD_KEY = "db.password";
private static final String DB_POOL_SIZE_KEY = "db.pool.size";
private static final int DEFAULT_POOL_SIZE = 10;
private static BlockingQueue<Connection> pool;
static {
loadDriver();
initConnectionPool();
}
private static void loadDriver() {
try {
Class.forName("org.postgresql.Driver");
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
private static void initConnectionPool() {
String poolSize = PropertiesUtil.get(DB_POOL_SIZE_KEY);
int size = poolSize == null ? DEFAULT_POOL_SIZE : Integer.parseInt(poolSize);
pool = new ArrayBlockingQueue<>(size);
for (int i = 0; i < size; i++) {
Connection connection = open();
var proxyConnection = (Connection) Proxy.newProxyInstance(ConnectionManager.class.getClassLoader(),
new Class[]{Connection.class},
(proxy, method, args) -> method.getName().equals("close") ?
pool.add((Connection) proxy) :
method.invoke(connection, args)
);
pool.add(proxyConnection);
}
}
public static Connection get() {
try {
return pool.take();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
private static Connection open() {
try {
return DriverManager.getConnection(PropertiesUtil.get(DB_URL_KEY),
PropertiesUtil.get(DB_USER_KEY),
PropertiesUtil.get(DB_PASSWORD_KEY));
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
private ConnectionManager() {
}
}

View File

@ -0,0 +1,12 @@
package utils;
import lombok.experimental.UtilityClass;
@UtilityClass
public class JspHelper {
private static final String JSP_FORMAT = "WEB-INF/jsp/%s.jsp";
public static String getPath(String jsp){
return JSP_FORMAT.formatted(jsp);
}
}

View File

@ -0,0 +1,30 @@
package utils;
import lombok.experimental.UtilityClass;
import java.time.DateTimeException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Optional;
@UtilityClass
public class LocalDateTimeFormatter {
private static final String PATTERN ="yyyy-MM-dd";
private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern(PATTERN);
public LocalDate format(String date) {
return LocalDate.parse(date, FORMATTER);
}
public boolean isValid(String date){
try {
return Optional.ofNullable(date)
.map(LocalDateTimeFormatter::format)
.isPresent();
}
catch (DateTimeException exception){
return false;
}
}
}

View File

@ -0,0 +1,27 @@
package utils;
import java.io.IOException;
import java.util.Properties;
public class PropertiesUtil {
private static final Properties PROPERTIES= new Properties();
static {
loadProperties();
}
private static void loadProperties() {
try (var inputStream = PropertiesUtil.class.getClassLoader().getResourceAsStream("application.properties")) {
PROPERTIES.load(inputStream);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static String get(String key){
return PROPERTIES.getProperty(key);
}
private PropertiesUtil() {
}
}

View File

@ -0,0 +1,4 @@
db.url=jdbc:postgresql://localhost:5432/postgres
db.user=postgres
db.password=postgres
db.pool.size=5

View File

@ -0,0 +1,18 @@
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>title</title>
</head>
<body>
<h1>Проверка</h1>
<div>
<p>Size: ${requestScope.flights.size()}</p>
<p> id: ${requestScope.flights[1].id()}</p>
<p> description: ${requestScope.flights[1].description()}</p>
<p> JSESSIONID: ${cookie.get("JSESSIONID")}</p>
<p> HEADER id: ${header["cookie"]}</p>
<p> PARAM id: ${param.id}</p>
<p> not empty: ${not empty flights}</p>
</div>
</body>
</html>

View File

@ -0,0 +1,22 @@
<%@ page import="org.example.je.jdbc.service.TicketService"%>
<%@ page import="org.example.je.jdbc.dto.TicketDto"%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="jakarta.tags.core" %>
<%@ taglib prefix="fn" uri="jakarta.tags.functions" %>
<html>
<head>
<title>Полеты</title>
</head>
<body>
<h1>Полеты:</h1>
<ol>
<c:forEach var="flight" items="${requestScope.flights}">
<li><a href ='/tickets?flight=${flight.id()}'>${flight.description()}</a>
</li>
</c:forEach>
</ol>
</body>
</html>

View File

@ -0,0 +1,46 @@
<%@ page import="org.example.je.jdbc.service.TicketService"%>
<%@ page import="org.example.je.jdbc.dto.TicketDto"%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="jakarta.tags.core" %>
<%@ taglib prefix="fn" uri="jakarta.tags.functions" %>
<html>
<head>
<title>Регистрация</title>
</head>
<body>
<h1>Регистрация:</h1>
<form action="/registration" method="POST">
<label for="name">Full Name:</label><br>
<input type="text" id="name" name="name" ><br><br>
<label for="birthdate">Birthdate:</label><br>
<input type="date" id="birthdate" name="birthdate" ><br><br>
<label for="role">Role:</label><br>
<select id="role" name="role" >
<c:forEach var="role" items="${requestScope.roles}">
<option label="${role}">${role}</option>
</c:forEach>
</select><br><br>
<label for="gender">Gender:</label><br>
<c:forEach var="gender" items="${requestScope.genders}">
<input type = "radio" name="gender" value="${gender}">${gender}</input>
</c:forEach>
<br><br>
<label for="email">Email:</label><br>
<input type="email" id="email" name="email" ><br><br>
<label for="password">Password:</label><br>
<input type="password" id="password" name="password"><br><br>
<button type="submit">Send </button>
</form>
</body>
</html>

View File

@ -0,0 +1,21 @@
<%@ page import="org.example.je.jdbc.service.TicketService"%>
<%@ page import="org.example.je.jdbc.dto.TicketDto"%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="jakarta.tags.core" %>
<%@ taglib prefix="fn" uri="jakarta.tags.functions" %>
<html>
<head>
<title>Билеты</title>
</head>
<body>
<h1>Билеты:</h1>
<ol>
<c:forEach var="ticket" items="${requestScope.tickets}">
<li>${ticket.seatNo()}</li>
</c:forEach>
</ol>
</body>
</html>