Skip to content

Commit fd0f855

Browse files
committed
feat: done implement dao factory
1 parent 50fbd10 commit fd0f855

File tree

15 files changed

+593
-29
lines changed

15 files changed

+593
-29
lines changed

dao-factory/pom.xml

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,4 +17,32 @@
1717
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
1818
</properties>
1919

20+
<dependencies>
21+
<dependency>
22+
<groupId>com.h2database</groupId>
23+
<artifactId>h2</artifactId>
24+
</dependency>
25+
26+
<dependency>
27+
<groupId>org.slf4j</groupId>
28+
<artifactId>slf4j-api</artifactId>
29+
</dependency>
30+
<dependency>
31+
<groupId>ch.qos.logback</groupId>
32+
<artifactId>logback-classic</artifactId>
33+
</dependency>
34+
<dependency>
35+
<groupId>org.mongodb</groupId>
36+
<artifactId>bson</artifactId>
37+
</dependency>
38+
<dependency>
39+
<groupId>org.mongodb</groupId>
40+
<artifactId>mongodb-driver-legacy</artifactId>
41+
</dependency>
42+
<dependency>
43+
<groupId>com.google.code.gson</groupId>
44+
<artifactId>gson</artifactId>
45+
</dependency>
46+
</dependencies>
47+
2048
</project>
Lines changed: 110 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,110 @@
1+
package com.iluwatar.daofactory;
2+
3+
import java.sql.SQLException;
4+
import java.util.List;
5+
import lombok.extern.slf4j.Slf4j;
6+
import org.bson.types.ObjectId;
7+
import org.slf4j.Logger;
8+
import org.slf4j.LoggerFactory;
9+
10+
/**
11+
* Created by: IntelliJ IDEA
12+
* User : dthanh
13+
* Date : 16/04/2025
14+
* Time : 23:08
15+
* Filename : ${NAME}
16+
*/
17+
@Slf4j
18+
public class App {
19+
20+
private static final Logger logger = LoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME);
21+
22+
23+
24+
public static void main(String[] args) throws SQLException {
25+
final var h2DAO = DAOFactory.getDataSource(DataSourceEnum.H2);
26+
final var mongoDAO = DAOFactory.getDataSource(DataSourceEnum.Mongo);
27+
final var flatFileDAO = DAOFactory.getDataSource(DataSourceEnum.FlatFile);
28+
29+
final var h2CustomerDAO = h2DAO.getCustomerDAO();
30+
final var mongoCustomerDAO = mongoDAO.getCustomerDAO();
31+
final var flatFileCustomerDAO = flatFileDAO.getCustomerDAO();
32+
33+
// Perform CRUD H2 Database
34+
Customer<Long> customerInmemory1 = new Customer<>(1L, "Green");
35+
Customer<Long> customerInmemory2 = new Customer<>(2L, "Red");
36+
Customer<Long> customerInmemory3 = new Customer<>(3L, "Blue");
37+
Customer<Long> customerUpdateInmemory = new Customer<>(1L, "Yellow");
38+
39+
LOGGER.debug("H2 - Create customer");
40+
performCreateCustomer(h2CustomerDAO,
41+
List.of(customerInmemory1, customerInmemory2, customerInmemory3));
42+
LOGGER.debug("H2 - Update customer");
43+
performUpdateCustomer(h2CustomerDAO, customerUpdateInmemory);
44+
LOGGER.debug("H2 - Delete customer");
45+
performDeleteCustomer(h2CustomerDAO, 3L);
46+
deleteSchema(h2CustomerDAO);
47+
48+
// Perform CRUD MongoDb
49+
ObjectId idCustomerMongo1 = new ObjectId();
50+
ObjectId idCustomerMongo2 = new ObjectId();
51+
Customer<ObjectId> customer4 = new Customer<>(idCustomerMongo1, "Masca");
52+
Customer<ObjectId> customer5 = new Customer<>(idCustomerMongo2, "Elliot");
53+
Customer<ObjectId> customerUpdateMongo = new Customer<>(idCustomerMongo2, "Henry");
54+
55+
LOGGER.debug("Mongo - Create customer");
56+
performCreateCustomer(mongoCustomerDAO, List.of(customer4, customer5));
57+
LOGGER.debug("Mongo - Update customer");
58+
performUpdateCustomer(mongoCustomerDAO, customerUpdateMongo);
59+
LOGGER.debug("Mongo - Delete customer");
60+
performDeleteCustomer(mongoCustomerDAO, idCustomerMongo2);
61+
deleteSchema(mongoCustomerDAO);
62+
63+
// Perform CRUD Flat file
64+
Customer<Long> customerFlatFile1 = new Customer<>(1L, "Duc");
65+
Customer<Long> customerFlatFile2 = new Customer<>(2L, "Quang");
66+
Customer<Long> customerFlatFile3 = new Customer<>(3L, "Nhat");
67+
Customer<Long> customerUpdateFlatFile = new Customer<>(1L, "Thanh");
68+
LOGGER.debug("Flat file - Create customer");
69+
performCreateCustomer(flatFileCustomerDAO,
70+
List.of(customerFlatFile1, customerFlatFile2, customerFlatFile3));
71+
LOGGER.debug("Flat file - Update customer");
72+
performUpdateCustomer(flatFileCustomerDAO, customerUpdateFlatFile);
73+
LOGGER.debug("Flat file - Delete customer");
74+
performDeleteCustomer(flatFileCustomerDAO, 3L);
75+
deleteSchema(flatFileCustomerDAO);
76+
}
77+
78+
public static void deleteSchema(CustomerDAO<?> customerDAO) {
79+
customerDAO.deleteSchema();
80+
}
81+
82+
public static <ID> void performCreateCustomer(CustomerDAO<ID> customerDAO,
83+
List<Customer<ID>> customerList) {
84+
for (Customer<ID> customer : customerList) {
85+
customerDAO.save(customer);
86+
}
87+
List<Customer<ID>> customers = customerDAO.findAll();
88+
for (Customer<ID> customer : customers) {
89+
LOGGER.debug(customer.toString());
90+
}
91+
}
92+
93+
public static <ID> void performUpdateCustomer(CustomerDAO<ID> customerDAO,
94+
Customer<ID> customerUpdate) {
95+
customerDAO.update(customerUpdate);
96+
List<Customer<ID>> customers = customerDAO.findAll();
97+
for (Customer<ID> customer : customers) {
98+
LOGGER.error(customer.toString());
99+
}
100+
}
101+
102+
public static <ID> void performDeleteCustomer(CustomerDAO<ID> customerDAO,
103+
ID customerId) {
104+
customerDAO.delete(customerId);
105+
List<Customer<ID>> customers = customerDAO.findAll();
106+
for (Customer<ID> customer : customers) {
107+
LOGGER.debug(customer.toString());
108+
}
109+
}
110+
}
Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,25 @@
11
package com.iluwatar.daofactory;
22

3+
import java.io.Serializable;
4+
import lombok.AllArgsConstructor;
5+
import lombok.Getter;
6+
import lombok.NoArgsConstructor;
7+
import lombok.Setter;
8+
import lombok.ToString;
9+
310
/**
411
* Created by: IntelliJ IDEA
512
* User : dthanh
613
* Date : 16/04/2025
714
* Time : 23:22
815
* Filename : Customer
9-
*/public class Customer {
16+
*/
17+
@Getter
18+
@Setter
19+
@NoArgsConstructor
20+
@AllArgsConstructor
21+
@ToString
22+
public class Customer<T> implements Serializable {
23+
private T id;
24+
private String name;
1025
}
Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,25 @@
11
package com.iluwatar.daofactory;
22

3+
import java.util.List;
4+
import java.util.Optional;
5+
36
/**
47
* Created by: IntelliJ IDEA
58
* User : dthanh
69
* Date : 16/04/2025
710
* Time : 23:16
811
* Filename : CustomerDAO
9-
*/public interface CustomerDAO {
12+
*/
13+
public interface CustomerDAO<ID> {
14+
void save(Customer<ID> customer);
15+
16+
void update(Customer<ID> customer);
17+
18+
void delete(ID id);
19+
20+
List<Customer<ID>> findAll();
21+
22+
Optional<Customer<ID>> findById(ID id);
23+
24+
void deleteSchema();
1025
}

dao-factory/src/main/java/com/iluwatar/daofactory/DAOFactory.java

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,5 +6,15 @@
66
* Date : 16/04/2025
77
* Time : 23:16
88
* Filename : DAOFactory
9-
*/public interface DAOFactory {
9+
*/
10+
public abstract class DAOFactory {
11+
public static DAOFactory getDataSource(DataSourceEnum dataSourceEnum) {
12+
return switch (dataSourceEnum) {
13+
case H2 -> new H2DataSourceFactory();
14+
case Mongo -> new MongoDataSourceFactory();
15+
case FlatFile -> new FlatFileDataSourceFactory();
16+
};
17+
}
18+
19+
public abstract CustomerDAO getCustomerDAO();
1020
}

dao-factory/src/main/java/com/iluwatar/daofactory/DataSourceEnum.java

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,5 +7,8 @@
77
* Time : 00:21
88
* Filename : DataSourceEnum
99
*/
10-
public class DataSourceEnum {
10+
public enum DataSourceEnum {
11+
H2,
12+
Mongo,
13+
FlatFile
1114
}
Lines changed: 123 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,133 @@
11
package com.iluwatar.daofactory;
22

3+
import com.google.gson.Gson;
4+
import com.google.gson.GsonBuilder;
5+
import com.google.gson.reflect.TypeToken;
6+
import java.io.FileReader;
7+
import java.io.FileWriter;
8+
import java.io.IOException;
9+
import java.io.Reader;
10+
import java.io.Writer;
11+
import java.lang.reflect.Type;
12+
import java.nio.file.Path;
13+
import java.nio.file.Paths;
14+
import java.util.LinkedList;
15+
import java.util.List;
16+
import java.util.Optional;
17+
import lombok.extern.slf4j.Slf4j;
18+
319
/**
420
* Created by: IntelliJ IDEA
521
* User : dthanh
622
* Date : 16/04/2025
723
* Time : 23:25
824
* Filename : FlatFileCustomerDAO
925
*/
10-
public class FlatFileCustomerDAO {
26+
@Slf4j
27+
public class FlatFileCustomerDAO implements CustomerDAO<Long> {
28+
Path filePath = Paths.get(System.getProperty("user.home"), "Desktop", "customer.json");
29+
Gson gson = new GsonBuilder()
30+
.setPrettyPrinting()
31+
.serializeNulls()
32+
.create();
33+
Type customerListType = new TypeToken<List<Customer<Long>>>() {
34+
}.getType();
35+
36+
@Override
37+
public void save(Customer<Long> customer) {
38+
List<Customer<Long>> customers = new LinkedList<>();
39+
if (filePath.toFile().exists() && filePath.toFile().length() > 0) {
40+
try (Reader reader = new FileReader(filePath.toFile())) {
41+
customers = gson.fromJson(reader, customerListType);
42+
} catch (IOException ex) {
43+
LOGGER.error("Error while reading JSON: {}", ex.getMessage(), ex);
44+
}
45+
}
46+
customers.add(customer);
47+
try (Writer writer = new FileWriter(filePath.toFile())) {
48+
gson.toJson(customers, writer);
49+
} catch (IOException ex) {
50+
LOGGER.error("Error writing JSON: {}", ex.getMessage(), ex);
51+
}
52+
}
53+
54+
@Override
55+
public void update(Customer<Long> customer) {
56+
if (!filePath.toFile().exists()) {
57+
throw new RuntimeException("File not found");
58+
}
59+
List<Customer<Long>> customers = new LinkedList<>();
60+
try (Reader reader = new FileReader(filePath.toFile())) {
61+
customers = gson.fromJson(reader, customerListType);
62+
} catch (IOException ex) {
63+
LOGGER.error("Error while reading JSON: {}", ex.getMessage(), ex);
64+
}
65+
customers.stream()
66+
.filter(c -> c.getId()
67+
.equals(customer.getId()))
68+
.findFirst()
69+
.ifPresentOrElse(
70+
c -> c.setName(customer.getName()),
71+
() -> {
72+
throw new RuntimeException("Customer not found with id: " + customer.getId());
73+
}
74+
);
75+
}
76+
77+
@Override
78+
public void delete(Long id) {
79+
if (!filePath.toFile().exists()) {
80+
throw new RuntimeException("File not found");
81+
}
82+
List<Customer<Long>> customers = new LinkedList<>();
83+
try (Reader reader = new FileReader(filePath.toFile())) {
84+
customers = gson.fromJson(reader, customerListType);
85+
} catch (IOException ex) {
86+
LOGGER.error("Error while reading JSON: {}", ex.getMessage(), ex);
87+
}
88+
Customer<Long> customerToRemove = customers.stream().filter(c -> c.getId().equals(id))
89+
.findFirst()
90+
.orElseThrow(() -> new RuntimeException("Customer not found with id: " + id));
91+
customers.remove(customerToRemove);
92+
}
93+
94+
@Override
95+
public List<Customer<Long>> findAll() {
96+
if (!filePath.toFile().exists()) {
97+
throw new RuntimeException("File not found");
98+
}
99+
List<Customer<Long>> customers = null;
100+
try (Reader reader = new FileReader(filePath.toFile())) {
101+
customers = gson.fromJson(reader, customerListType);
102+
103+
} catch (IOException ex) {
104+
LOGGER.error("Error while reading JSON: {}", ex.getMessage(), ex);
105+
}
106+
return customers;
107+
}
108+
109+
@Override
110+
public Optional<Customer<Long>> findById(Long id) {
111+
if (!filePath.toFile().exists()) {
112+
throw new RuntimeException("File not found");
113+
}
114+
List<Customer<Long>> customers = null;
115+
try (Reader reader = new FileReader(filePath.toFile())) {
116+
customers = gson.fromJson(reader, customerListType);
117+
118+
} catch (IOException ex) {
119+
LOGGER.error("Error while reading JSON: {}", ex.getMessage(), ex);
120+
}
121+
return customers.stream()
122+
.filter(c -> c.getId()
123+
.equals(id))
124+
.findFirst();
125+
}
126+
127+
@Override
128+
public void deleteSchema() {
129+
if (filePath.toFile().exists()) {
130+
filePath.toFile().delete();
131+
}
132+
}
11133
}

dao-factory/src/main/java/com/iluwatar/daofactory/FlatFileDataSourceFactory.java

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,5 +6,10 @@
66
* Date : 16/04/2025
77
* Time : 23:19
88
* Filename : FlatFileDataSourceFactory
9-
*/public class FlatFileDataSourceFactory {
9+
*/
10+
public class FlatFileDataSourceFactory extends DAOFactory {
11+
@Override
12+
public CustomerDAO getCustomerDAO() {
13+
return new FlatFileCustomerDAO();
14+
}
1015
}

0 commit comments

Comments
 (0)