├── .gitignore
├── README.md
├── pom.xml
└── src
├── main
├── java
│ └── guru
│ │ └── springframework
│ │ └── blog
│ │ ├── BlogPostsApplication.java
│ │ ├── contextrefresh
│ │ ├── ContextRefresehedApplication.java
│ │ ├── ContextRefreshedListener.java
│ │ └── EventHolderBean.java
│ │ ├── currenttime
│ │ ├── CurrentTimeDateCalendar.java
│ │ └── CurrentTimeJava8.java
│ │ ├── dependencyinversionprinciple
│ │ ├── highlevel
│ │ │ ├── ElectricPowerSwitch.java
│ │ │ ├── Switch.java
│ │ │ └── Switchable.java
│ │ └── lowlevel
│ │ │ ├── Fan.java
│ │ │ └── LightBulb.java
│ │ ├── hibernatepagination
│ │ ├── dao
│ │ │ └── ProductDao.java
│ │ ├── domain
│ │ │ └── Product.java
│ │ └── util
│ │ │ └── HibernateUtil.java
│ │ ├── interfacesegregationprinciple
│ │ ├── Flyable.java
│ │ ├── Movable.java
│ │ ├── Toy.java
│ │ ├── ToyBuilder.java
│ │ ├── ToyCar.java
│ │ ├── ToyHouse.java
│ │ └── ToyPlane.java
│ │ ├── log4joverview
│ │ └── MyApp.java
│ │ ├── monetarycalculations
│ │ └── BigDecimalCalc.java
│ │ ├── openclosedprinciple
│ │ ├── ClaimApprovalManager.java
│ │ ├── HealthInsuranceSurveyor.java
│ │ ├── InsuranceSurveyor.java
│ │ └── VehicleInsuranceSurveyor.java
│ │ └── sortarraylist
│ │ ├── ascendingdescending
│ │ └── SortArrayListAscendingDescending.java
│ │ ├── comparable
│ │ ├── JobCandidate.java
│ │ └── JobCandidateSorter.java
│ │ └── comparator
│ │ ├── JobCandidate.java
│ │ └── JobCandidateSorter.java
└── resources
│ ├── application.properties
│ └── hibernate.cfg.xml
└── test
└── java
└── guru
└── springframework
└── blog
├── BlogPostsApplicationTests.java
├── contextrefresh
├── ContextRefreshedListenerTest.java
└── config
│ └── ContextRefreshConfig.java
├── currenttime
├── CurrentTimeDateCalendarTest.java
└── CurrentTimeJava8Test.java
├── dependencyinversionprinciple
└── highlevel
│ └── ElectricPowerSwitchTest.java
├── hibernatepagination
└── dao
│ └── ProductDaoTest.java
├── interfacesegregationprinciple
└── ToyBuilderTest.java
├── log4joverview
└── MyAppTest.java
├── monetarycalculations
└── BigDecimalCalcTest.java
├── openclosedprinciple
└── ClaimApprovalManagerTest.java
└── sortarraylist
├── ascendingdescending
└── SortArrayListAscendingDescendingTest.java
├── comparable
└── JobCandidateSorterTest.java
└── comparator
└── JobCandidateSorterTest.java
/.gitignore:
--------------------------------------------------------------------------------
1 | # Compiled source #
2 | ###################
3 | *.com
4 | *.class
5 | *.dll
6 | *.exe
7 | *.o
8 | *.so
9 |
10 | # Packages #
11 | ############
12 | # it's better to unpack these files and commit the raw source
13 | # git has its own built in compression methods
14 | *.7z
15 | *.dmg
16 | *.gz
17 | *.iso
18 | *.rar
19 | *.tar
20 | *.zip
21 |
22 | # Logs and databases #
23 | ######################
24 | *.log
25 | *.sqlite
26 |
27 | # OS generated files #
28 | ######################
29 | .DS_Store
30 | .DS_Store?
31 | ._*
32 | .Spotlight-V100
33 | .Trashes
34 | ehthumbs.db
35 | Thumbs.db
36 |
37 | .project
38 | .classpath
39 | .idea
40 | *.iml
41 | atlassian-ide-plugin.xml
42 | target
43 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Blog Posts
2 | This repository holds code examples supporting blog posts on [Spring Framework Guru](http://springframework.guru)
3 |
4 | * [Monetary Calculation Pitfalls in Java](https://springframework.guru/monetary-calculation-pitfalls/)
5 | * [Open Closed Principle in Java](https://springframework.guru/open-closed-principle/)
6 | * [Dependency Inversion Principle](https://springframework.guru/dependency-inversion-principle/)
7 | * [Interface Segregation Principle](https://springframework.guru/interface-segregation-principle/)
8 | * [Running code via Spring Events in Spring Boot](https://springframework.guru/running-code-on-spring-boot-startup/)
9 | * [Sorting Java ArrayList](https://springframework.guru/sorting-java-arraylist/)
10 | * [Getting Current Date Time in Java](https://springframework.guru/getting-current-date-time-in-java/)
11 | * [Introducing Log4J 2 – Enterprise Class Logging](https://springframework.guru/introducing-log4j-enterprise-class-logging/)
12 | * [Hibernate Pagination – How To](https://springframework.guru/hibernate-pagination/)
13 |
--------------------------------------------------------------------------------
/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 | 4.0.0
5 |
6 | guru.springframework
7 | blogposts
8 | 0.0.1-SNAPSHOT
9 | jar
10 |
11 | Blog Posts
12 | Misc Blog Posts
13 |
14 |
15 | org.springframework.boot
16 | spring-boot-starter-parent
17 | 1.2.3.RELEASE
18 |
19 |
20 |
21 |
22 | UTF-8
23 | guru.springframework.blog.BlogPostsApplication
24 | 1.8
25 |
26 |
27 |
28 |
29 | org.springframework.boot
30 | spring-boot-starter
31 |
32 |
33 | org.springframework.boot
34 | spring-boot-starter-logging
35 |
36 |
37 |
38 |
39 |
40 | org.springframework.boot
41 | spring-boot-starter-test
42 | test
43 |
44 |
45 | org.apache.logging.log4j
46 | log4j-api
47 | 2.5
48 |
49 |
50 | org.apache.logging.log4j
51 | log4j-core
52 | 2.5
53 |
54 |
55 | com.h2database
56 | h2
57 | runtime
58 |
59 |
60 | org.hibernate
61 | hibernate-core
62 | 4.3.10.Final
63 |
64 |
65 |
66 |
67 |
68 | org.springframework.boot
69 | spring-boot-maven-plugin
70 |
71 |
72 |
73 |
74 |
75 |
--------------------------------------------------------------------------------
/src/main/java/guru/springframework/blog/BlogPostsApplication.java:
--------------------------------------------------------------------------------
1 | package guru.springframework.blog;
2 |
3 | import org.springframework.boot.SpringApplication;
4 | import org.springframework.boot.autoconfigure.SpringBootApplication;
5 |
6 | @SpringBootApplication
7 | public class BlogPostsApplication {
8 |
9 | public static void main(String[] args) {
10 | SpringApplication.run(BlogPostsApplication.class, args);
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/src/main/java/guru/springframework/blog/contextrefresh/ContextRefresehedApplication.java:
--------------------------------------------------------------------------------
1 | package guru.springframework.blog.contextrefresh;
2 |
3 | import org.springframework.boot.SpringApplication;
4 | import org.springframework.boot.autoconfigure.SpringBootApplication;
5 | import org.springframework.context.ConfigurableApplicationContext;
6 |
7 | @SpringBootApplication
8 | public class ContextRefresehedApplication {
9 | public static void main(String[] args) {
10 | ConfigurableApplicationContext ctx = SpringApplication.run(ContextRefresehedApplication.class, args);
11 | EventHolderBean bean = ctx.getBean(EventHolderBean.class);
12 | System.out.println("Event Processed?? - " + bean.getEventFired());
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/src/main/java/guru/springframework/blog/contextrefresh/ContextRefreshedListener.java:
--------------------------------------------------------------------------------
1 | package guru.springframework.blog.contextrefresh;
2 |
3 | import org.springframework.beans.factory.annotation.Autowired;
4 | import org.springframework.context.ApplicationListener;
5 | import org.springframework.context.event.ContextRefreshedEvent;
6 | import org.springframework.stereotype.Component;
7 |
8 | @Component
9 | public class ContextRefreshedListener implements ApplicationListener{
10 |
11 | private EventHolderBean eventHolderBean;
12 |
13 | @Autowired
14 | public void setEventHolderBean(EventHolderBean eventHolderBean) {
15 | this.eventHolderBean = eventHolderBean;
16 | }
17 |
18 | @Override
19 | public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
20 | System.out.println("Context Event Received");
21 | eventHolderBean.setEventFired(true);
22 | }
23 | }
--------------------------------------------------------------------------------
/src/main/java/guru/springframework/blog/contextrefresh/EventHolderBean.java:
--------------------------------------------------------------------------------
1 | package guru.springframework.blog.contextrefresh;
2 |
3 | import org.springframework.stereotype.Component;
4 |
5 | @Component
6 | public class EventHolderBean {
7 | private Boolean eventFired = false;
8 |
9 | public Boolean getEventFired() {
10 | return eventFired;
11 | }
12 |
13 | public void setEventFired(Boolean eventFired) {
14 | this.eventFired = eventFired;
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/src/main/java/guru/springframework/blog/currenttime/CurrentTimeDateCalendar.java:
--------------------------------------------------------------------------------
1 | package guru.springframework.blog.currenttime;
2 |
3 | import java.text.DateFormat;
4 | import java.text.SimpleDateFormat;
5 | import java.util.Calendar;
6 | import java.util.Date;
7 |
8 | public class CurrentTimeDateCalendar {
9 | public static void getCurrentTimeUsingDate() {
10 | Date date = new Date();
11 | String strDateFormat = "hh:mm:ss a";
12 | DateFormat dateFormat = new SimpleDateFormat(strDateFormat);
13 | String formattedDate= dateFormat.format(date);
14 | System.out.println("Current time of the day using Date - 12 hour format: " + formattedDate);
15 | }
16 | public static void getCurrentTimeUsingCalendar() {
17 | Calendar cal = Calendar.getInstance();
18 | Date date=cal.getTime();
19 | DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
20 | String formattedDate=dateFormat.format(date);
21 | System.out.println("Current time of the day using Calendar - 24 hour format: "+ formattedDate);
22 | }
23 | }
--------------------------------------------------------------------------------
/src/main/java/guru/springframework/blog/currenttime/CurrentTimeJava8.java:
--------------------------------------------------------------------------------
1 | package guru.springframework.blog.currenttime;
2 |
3 | import java.time.*;
4 | import java.time.format.DateTimeFormatter;
5 | public class CurrentTimeJava8 {
6 | public static void getCurrentTime(){
7 | System.out.println("-----Current time of your time zone-----");
8 | LocalTime time = LocalTime.now();
9 | System.out.println("Current time of the day: " + time);
10 | }
11 | public static void getCurrentTimeWithTimeZone(){
12 | System.out.println("-----Current time of a different time zone using LocalTime-----");
13 | ZoneId zoneId = ZoneId.of("America/Los_Angeles");
14 | LocalTime localTime=LocalTime.now(zoneId);
15 | DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss");
16 | String formattedTime=localTime.format(formatter);
17 | System.out.println("Current time of the day in Los Angeles: " + formattedTime);
18 |
19 | }
20 | public static void getCurrentTimeWithOffset(){
21 | System.out.println("-----Current time of different offset-----");
22 | ZoneOffset zoneOffset = ZoneOffset.of("-08:00");
23 | ZoneId zoneId=ZoneId.ofOffset("UTC", zoneOffset);
24 | LocalTime offsetTime = LocalTime.now(zoneId);
25 | DateTimeFormatter formatter = DateTimeFormatter.ofPattern("hh:mm a");
26 | String formattedTime=offsetTime.format(formatter);
27 | System.out.println("Current time of the day with offset -08:00: " + formattedTime);
28 |
29 | }
30 | }
31 |
32 |
--------------------------------------------------------------------------------
/src/main/java/guru/springframework/blog/dependencyinversionprinciple/highlevel/ElectricPowerSwitch.java:
--------------------------------------------------------------------------------
1 | package guru.springframework.blog.dependencyinversionprinciple.highlevel;
2 |
3 |
4 | public class ElectricPowerSwitch implements Switch {
5 | public Switchable client;
6 | public boolean on;
7 | public ElectricPowerSwitch(Switchable client) {
8 | this.client = client;
9 | this.on = false;
10 | }
11 | public boolean isOn() {
12 | return this.on;
13 | }
14 | public void press(){
15 | boolean checkOn = isOn();
16 | if (checkOn) {
17 | client.turnOff();
18 | this.on = false;
19 | } else {
20 | client.turnOn();
21 | this.on = true;
22 | }
23 |
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/src/main/java/guru/springframework/blog/dependencyinversionprinciple/highlevel/Switch.java:
--------------------------------------------------------------------------------
1 | package guru.springframework.blog.dependencyinversionprinciple.highlevel;
2 |
3 | public interface Switch {
4 | boolean isOn();
5 | void press();
6 | }
7 |
--------------------------------------------------------------------------------
/src/main/java/guru/springframework/blog/dependencyinversionprinciple/highlevel/Switchable.java:
--------------------------------------------------------------------------------
1 | package guru.springframework.blog.dependencyinversionprinciple.highlevel;
2 |
3 | public interface Switchable {
4 | void turnOn();
5 | void turnOff();
6 | }
7 |
--------------------------------------------------------------------------------
/src/main/java/guru/springframework/blog/dependencyinversionprinciple/lowlevel/Fan.java:
--------------------------------------------------------------------------------
1 | package guru.springframework.blog.dependencyinversionprinciple.lowlevel;
2 |
3 | import guru.springframework.blog.dependencyinversionprinciple.highlevel.Switchable;
4 |
5 | public class Fan implements Switchable {
6 | @Override
7 | public void turnOn() {
8 | System.out.println("Fan: Fan turned on...");
9 | }
10 |
11 | @Override
12 | public void turnOff() {
13 | System.out.println("Fan: Fan turned off...");
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/src/main/java/guru/springframework/blog/dependencyinversionprinciple/lowlevel/LightBulb.java:
--------------------------------------------------------------------------------
1 | package guru.springframework.blog.dependencyinversionprinciple.lowlevel;
2 |
3 | import guru.springframework.blog.dependencyinversionprinciple.highlevel.Switchable;
4 |
5 | public class LightBulb implements Switchable {
6 | @Override
7 | public void turnOn() {
8 | System.out.println("LightBulb: Bulb turned on...");
9 | }
10 |
11 | @Override
12 | public void turnOff() {
13 | System.out.println("LightBulb: Bulb turned off...");
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/src/main/java/guru/springframework/blog/hibernatepagination/dao/ProductDao.java:
--------------------------------------------------------------------------------
1 | package guru.springframework.blog.hibernatepagination.dao;
2 |
3 | import guru.springframework.blog.hibernatepagination.domain.Product;
4 | import guru.springframework.blog.hibernatepagination.util.HibernateUtil;
5 | import org.hibernate.*;
6 | import org.hibernate.criterion.Order;
7 | import org.hibernate.criterion.Projections;
8 | import org.hibernate.criterion.Restrictions;
9 |
10 | import java.util.List;
11 |
12 | public class ProductDao {
13 | public void saveProducts() {
14 | Session session = HibernateUtil.getSessionFactory().openSession();
15 | Transaction trans = null;
16 | try {
17 | trans = session.beginTransaction();
18 | for (int i = 0; i < 30; i++) {
19 | Product product = new Product();
20 | product.setProductName("Product_" + i);
21 | session.save(product);
22 | }
23 | trans.commit();
24 | } catch (HibernateException e) {
25 | trans.rollback();
26 | e.printStackTrace();
27 | } finally {
28 | session.close();
29 | }
30 | System.out.println("Saved 30 products");
31 | }
32 |
33 | public int listPaginatedProductsUsingQuery(int firstResult, int maxResults) {
34 | int paginatedCount = 0;
35 | Session session = HibernateUtil.getSessionFactory().openSession();
36 | try {
37 | Query query = session.createQuery("From Product");
38 | query.setFirstResult(firstResult);
39 | query.setMaxResults(maxResults);
40 | List products = (List) query.list();
41 | if (products != null) {
42 | paginatedCount = products.size();
43 | System.out.println("Total Results: " + paginatedCount);
44 | for (Product product : products) {
45 | System.out.println("Retrieved Product using Query. Name: " + product.getProductName());
46 | }
47 | }
48 |
49 | } catch (HibernateException e) {
50 | e.printStackTrace();
51 |
52 | } finally {
53 | session.close();
54 | }
55 | return paginatedCount;
56 | }
57 |
58 |
59 | public int listPaginatedProductsUsingCriteria(int firstResult, int maxResults) {
60 | int paginatedCount = 0;
61 | Session session = HibernateUtil.getSessionFactory().openSession();
62 | try {
63 | Criteria criteria = session.createCriteria(Product.class);
64 | criteria.setFirstResult(firstResult);
65 | criteria.setMaxResults(maxResults);
66 | List products = (List) criteria.list();
67 | if (products != null) {
68 | paginatedCount = products.size();
69 | System.out.println("Total Results: " + paginatedCount);
70 | for (Product product : products) {
71 | System.out.println("Retrieved Product using Criteria. Name: " + product.getProductName());
72 | }
73 | }
74 |
75 | } catch (HibernateException e) {
76 | e.printStackTrace();
77 | } finally {
78 | session.close();
79 | }
80 | return paginatedCount;
81 | }
82 |
83 | public int listPaginatedProductsUsingScrollableResults(int firstResult, int maxResults ) {
84 | int totalRecords=0;
85 | final Session session = HibernateUtil.getSessionFactory().openSession();
86 | try {
87 |
88 | ScrollableResults scrollableResults = getCriteria(session).scroll();
89 | scrollableResults.last();
90 | totalRecords=scrollableResults.getRowNumber()+1;
91 | scrollableResults.close();
92 | Criteria criteria = getCriteria(session);
93 | criteria.setFirstResult(firstResult);
94 | criteria.setMaxResults(maxResults);
95 | List