├── .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 products = criteria.list(); 96 | if (products != null) { 97 | for (Object[] product : products) { 98 | System.out.println("Retrieved Product using ScrollableResults. Name: " + product[0] + " out of "+totalRecords + " products"); 99 | } 100 | } 101 | 102 | } catch (HibernateException e) { 103 | e.printStackTrace(); 104 | } finally { 105 | session.close(); 106 | } 107 | return totalRecords; 108 | 109 | } 110 | 111 | private static Criteria getCriteria(final Session session) { 112 | Criteria criteria = session.createCriteria(Product.class); 113 | criteria.add(Restrictions.isNotNull("productName")); 114 | criteria.setProjection(Projections.projectionList() 115 | .add(Projections.property("productName")) 116 | .add(Projections.property("id"))); 117 | criteria.addOrder(Order.asc("id")); 118 | return criteria; 119 | } 120 | 121 | public void deleteAllProducts() { 122 | Session session = HibernateUtil.getSessionFactory().openSession(); 123 | Transaction trans = null; 124 | try { 125 | trans = session.beginTransaction(); 126 | String hql = String.format("delete from Product"); 127 | Query query = session.createQuery(hql); 128 | query.executeUpdate(); 129 | trans.commit(); 130 | } catch (HibernateException e) { 131 | trans.rollback(); 132 | e.printStackTrace(); 133 | } finally { 134 | session.close(); 135 | } 136 | System.out.println("Deleted all products"); 137 | 138 | } 139 | } 140 | 141 | 142 | 143 | 144 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/blog/hibernatepagination/domain/Product.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.blog.hibernatepagination.domain; 2 | 3 | import javax.persistence.*; 4 | @Entity 5 | public class Product { 6 | @Id 7 | @GeneratedValue(strategy = GenerationType.AUTO) 8 | private Integer id; 9 | private String productName; 10 | public Integer getId() { 11 | return id; 12 | } 13 | public void setId(Integer id) { 14 | this.id = id; 15 | } 16 | public String getProductName() { 17 | return productName; 18 | } 19 | public void setProductName(String productName) { 20 | this.productName = productName; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/blog/hibernatepagination/util/HibernateUtil.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.blog.hibernatepagination.util; 2 | 3 | 4 | import org.hibernate.SessionFactory; 5 | import org.hibernate.boot.registry.StandardServiceRegistryBuilder; 6 | import org.hibernate.cfg.Configuration; 7 | import org.hibernate.service.ServiceRegistry; 8 | 9 | public class HibernateUtil { 10 | private static final SessionFactory sessionFactory; 11 | private static final ServiceRegistry serviceRegistry; 12 | 13 | static{ 14 | Configuration configuration=new Configuration(); 15 | configuration.configure("hibernate.cfg.xml"); 16 | serviceRegistry = new StandardServiceRegistryBuilder() 17 | .applySettings(configuration.getProperties()).build(); 18 | sessionFactory = configuration 19 | .buildSessionFactory(serviceRegistry); 20 | } 21 | public static SessionFactory getSessionFactory(){ 22 | return sessionFactory; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/blog/interfacesegregationprinciple/Flyable.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.blog.interfacesegregationprinciple; 2 | 3 | public interface Flyable { 4 | void fly(); 5 | } 6 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/blog/interfacesegregationprinciple/Movable.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.blog.interfacesegregationprinciple; 2 | 3 | public interface Movable { 4 | void move(); 5 | } 6 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/blog/interfacesegregationprinciple/Toy.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.blog.interfacesegregationprinciple; 2 | 3 | public interface Toy { 4 | void setPrice(double price); 5 | void setColor(String color); 6 | } 7 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/blog/interfacesegregationprinciple/ToyBuilder.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.blog.interfacesegregationprinciple; 2 | 3 | public class ToyBuilder { 4 | public static ToyHouse buildToyHouse(){ 5 | ToyHouse toyHouse=new ToyHouse(); 6 | toyHouse.setPrice(15.00); 7 | toyHouse.setColor("green"); 8 | return toyHouse; 9 | } 10 | public static ToyCar buildToyCar(){ 11 | ToyCar toyCar=new ToyCar(); 12 | toyCar.setPrice(25.00); 13 | toyCar.setColor("red"); 14 | toyCar.move(); 15 | return toyCar; 16 | } 17 | public static ToyPlane buildToyPlane(){ 18 | ToyPlane toyPlane=new ToyPlane(); 19 | toyPlane.setPrice(125.00); 20 | toyPlane.setColor("white"); 21 | toyPlane.move(); 22 | toyPlane.fly(); 23 | return toyPlane; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/blog/interfacesegregationprinciple/ToyCar.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.blog.interfacesegregationprinciple; 2 | 3 | public class ToyCar implements Toy, Movable { 4 | double price; 5 | String color; 6 | 7 | @Override 8 | public void setPrice(double price) { 9 | 10 | this.price = price; 11 | } 12 | 13 | @Override 14 | public void setColor(String color) { 15 | this.color=color; 16 | } 17 | @Override 18 | public void move(){ 19 | System.out.println("ToyCar: Start moving car."); 20 | } 21 | @Override 22 | public String toString(){ 23 | return "ToyCar: Moveable Toy car- Price: "+price+" Color: "+color; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/blog/interfacesegregationprinciple/ToyHouse.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.blog.interfacesegregationprinciple; 2 | 3 | public class ToyHouse implements Toy { 4 | double price; 5 | String color; 6 | 7 | @Override 8 | public void setPrice(double price) { 9 | 10 | this.price = price; 11 | } 12 | @Override 13 | public void setColor(String color) { 14 | 15 | this.color=color; 16 | } 17 | @Override 18 | public String toString(){ 19 | return "ToyHouse: Toy house- Price: "+price+" Color: "+color; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/blog/interfacesegregationprinciple/ToyPlane.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.blog.interfacesegregationprinciple; 2 | 3 | public class ToyPlane implements Toy, Movable, Flyable { 4 | double price; 5 | String color; 6 | 7 | @Override 8 | public void setPrice(double price) { 9 | this.price = price; 10 | } 11 | 12 | @Override 13 | public void setColor(String color) { 14 | this.color=color; 15 | } 16 | @Override 17 | public void move(){ 18 | 19 | System.out.println("ToyPlane: Start moving plane."); 20 | } 21 | @Override 22 | public void fly(){ 23 | 24 | System.out.println("ToyPlane: Start flying plane."); 25 | } 26 | @Override 27 | public String toString(){ 28 | return "ToyPlane: Moveable and flyable toy plane- Price: "+price+" Color: "+color; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/blog/log4joverview/MyApp.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.blog.log4joverview; 2 | 3 | 4 | import org.apache.logging.log4j.LogManager; 5 | import org.apache.logging.log4j.Logger; 6 | 7 | public class MyApp { 8 | private static Logger logger = LogManager.getLogger("MyApp.class"); 9 | 10 | public void performSomeTask(){ 11 | logger.debug("This is a debug message"); 12 | logger.info("This is an info message"); 13 | logger.warn("This is a warn message"); 14 | logger.error("This is an error message"); 15 | logger.fatal("This is a fatal message"); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/blog/monetarycalculations/BigDecimalCalc.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.blog.monetarycalculations; 2 | 3 | import java.math.BigDecimal; 4 | import java.math.RoundingMode; 5 | 6 | 7 | public class BigDecimalCalc { 8 | 9 | public void calculate(String param1, String param2){ 10 | System.out.println("--------------------calculate-----------------------"); 11 | BigDecimal num1=new BigDecimal(param1); 12 | BigDecimal num2=new BigDecimal(param2); 13 | System.out.println("num1: "+num1+" num2: "+ num2); 14 | System.out.println("BigDecimal Addition: "+num1.add(num2)); 15 | System.out.println("BigDecimal Subtraction: " + num1.subtract(num2)); 16 | System.out.println("BigDecimal Multiplication: "+num1.multiply(num2)); 17 | } 18 | 19 | 20 | public void divideWithScaleRounding(String param1, String param2){ 21 | System.out.println("--------------------divisionWithScaleRounding-----------------------"); 22 | 23 | /*Setting scale and rounding mode for division using overloaded divide(BigDecimal divisor, int scale, RoundingMode roundingMode) */ 24 | BigDecimal num1=new BigDecimal(param1); 25 | BigDecimal num2=new BigDecimal(param2); 26 | System.out.println("num1: "+num1+" num2: "+ num2); 27 | System.out.println("BigDecimal Division with overloaded divide(): " + num1.divide(num2, 4, RoundingMode.HALF_EVEN)); 28 | } 29 | 30 | public void calculateTax(String amount, String tax){ 31 | System.out.println("--------------------calculateTax-----------------------"); 32 | BigDecimal bdAmount = new BigDecimal(amount); 33 | BigDecimal bdTax = new BigDecimal(tax); 34 | BigDecimal taxAmount = bdAmount.multiply(bdTax); 35 | /*Setting scale and rounding mode using setScale() */ 36 | taxAmount = taxAmount.setScale(2, RoundingMode.HALF_UP); 37 | BigDecimal finalAmount = bdAmount.add(taxAmount); 38 | finalAmount = finalAmount.setScale(2, RoundingMode.HALF_UP); 39 | 40 | System.out.println("Amount : " + bdAmount); 41 | System.out.println("Tax : " + taxAmount); 42 | System.out.println("Amount after tax: " + finalAmount); 43 | 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/blog/openclosedprinciple/ClaimApprovalManager.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.blog.openclosedprinciple; 2 | 3 | 4 | public class ClaimApprovalManager { 5 | public void processClaim(InsuranceSurveyor surveyor){ 6 | if(surveyor.isValidClaim()){ 7 | System.out.println("ClaimApprovalManager: Valid claim. Currently processing claim for approval...."); 8 | } 9 | } 10 | 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/blog/openclosedprinciple/HealthInsuranceSurveyor.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.blog.openclosedprinciple; 2 | 3 | 4 | public class HealthInsuranceSurveyor extends InsuranceSurveyor{ 5 | public boolean isValidClaim(){ 6 | System.out.println("HealthInsuranceSurveyor: Validating health insurance claim..."); 7 | /*Logic to validate health insurance claims*/ 8 | return true; 9 | } 10 | 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/blog/openclosedprinciple/InsuranceSurveyor.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.blog.openclosedprinciple; 2 | 3 | 4 | public abstract class InsuranceSurveyor { 5 | public abstract boolean isValidClaim(); 6 | } 7 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/blog/openclosedprinciple/VehicleInsuranceSurveyor.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.blog.openclosedprinciple; 2 | 3 | 4 | public class VehicleInsuranceSurveyor extends InsuranceSurveyor{ 5 | public boolean isValidClaim(){ 6 | System.out.println("VehicleInsuranceSurveyor: Validating vehicle insurance claim..."); 7 | /*Logic to validate vehicle insurance claims*/ 8 | return true; 9 | } 10 | 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/blog/sortarraylist/ascendingdescending/SortArrayListAscendingDescending.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.blog.sortarraylist.ascendingdescending; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Collections; 5 | 6 | public class SortArrayListAscendingDescending { 7 | private ArrayList arrayList; 8 | 9 | public SortArrayListAscendingDescending(ArrayList arrayList) { 10 | this.arrayList = arrayList; 11 | } 12 | 13 | public ArrayList getArrayList() { 14 | return this.arrayList; 15 | } 16 | 17 | public ArrayList sortAscending() { 18 | Collections.sort(this.arrayList); 19 | return this.arrayList; 20 | } 21 | 22 | public ArrayList sortDescending() { 23 | Collections.sort(this.arrayList, Collections.reverseOrder()); 24 | return this.arrayList; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/blog/sortarraylist/comparable/JobCandidate.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.blog.sortarraylist.comparable; 2 | 3 | 4 | public class JobCandidate implements Comparable { 5 | private String name; 6 | private String gender; 7 | private int age; 8 | 9 | public JobCandidate(String name, String gender, int age) { 10 | this.name = name; 11 | this.gender = gender; 12 | this.age = age; 13 | } 14 | 15 | public String getName() { 16 | return name; 17 | } 18 | 19 | public String getGender() { 20 | return gender; 21 | } 22 | 23 | public int getAge() { 24 | return age; 25 | } 26 | 27 | @Override 28 | public int compareTo(JobCandidate candidate) { 29 | return (this.getAge() < candidate.getAge() ? -1 : 30 | (this.getAge() == candidate.getAge() ? 0 : 1)); 31 | } 32 | 33 | @Override 34 | public String toString() { 35 | return " Name: " + this.name + ", Gender: " + this.gender + ", age:" + this.age; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/blog/sortarraylist/comparable/JobCandidateSorter.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.blog.sortarraylist.comparable; 2 | 3 | 4 | import java.util.ArrayList; 5 | import java.util.Collections; 6 | 7 | public class JobCandidateSorter { 8 | ArrayList jobCandidate = new ArrayList<>(); 9 | 10 | public JobCandidateSorter(ArrayList jobCandidate) { 11 | this.jobCandidate = jobCandidate; 12 | } 13 | 14 | public ArrayList getSortedJobCandidateByAge() { 15 | Collections.sort(jobCandidate); 16 | return jobCandidate; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/blog/sortarraylist/comparator/JobCandidate.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.blog.sortarraylist.comparator; 2 | 3 | 4 | import java.util.Comparator; 5 | 6 | public class JobCandidate { 7 | private String name; 8 | private String gender; 9 | private int age; 10 | 11 | public JobCandidate(String name, String gender, int age) { 12 | this.name = name; 13 | this.gender = gender; 14 | this.age = age; 15 | } 16 | 17 | public String getName() { 18 | return name; 19 | } 20 | 21 | public String getGender() { 22 | return gender; 23 | } 24 | 25 | public int getAge() { 26 | return age; 27 | } 28 | 29 | public static Comparator ageComparator = new Comparator() { 30 | @Override 31 | public int compare(JobCandidate jc1, JobCandidate jc2) { 32 | return (jc2.getAge() < jc1.getAge() ? -1 : 33 | (jc2.getAge() == jc1.getAge() ? 0 : 1)); 34 | } 35 | }; 36 | 37 | public static Comparator nameComparator = new Comparator() { 38 | @Override 39 | public int compare(JobCandidate jc1, JobCandidate jc2) { 40 | return (int) (jc1.getName().compareTo(jc2.getName())); 41 | } 42 | }; 43 | 44 | 45 | @Override 46 | public String toString() { 47 | return " Name: " + this.name + ", Gender: " + this.gender + ", age:" + this.age; 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/blog/sortarraylist/comparator/JobCandidateSorter.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.blog.sortarraylist.comparator; 2 | 3 | 4 | import java.util.ArrayList; 5 | import java.util.Collections; 6 | 7 | public class JobCandidateSorter { 8 | ArrayList jobCandidate = new ArrayList<>(); 9 | 10 | public JobCandidateSorter(ArrayList jobCandidate) { 11 | this.jobCandidate = jobCandidate; 12 | } 13 | 14 | public ArrayList getSortedJobCandidateByAge() { 15 | Collections.sort(jobCandidate, JobCandidate.ageComparator); 16 | return jobCandidate; 17 | } 18 | 19 | public ArrayList getSortedJobCandidateByName() { 20 | Collections.sort(jobCandidate, JobCandidate.nameComparator); 21 | return jobCandidate; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/main/resources/application.properties: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/springframeworkguru/blogposts/d98ae1b3e54a7d219738a7bac60c353bf5100478/src/main/resources/application.properties -------------------------------------------------------------------------------- /src/main/resources/hibernate.cfg.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 7 | true 8 | create-drop 9 | org.hibernate.dialect.H2Dialect 10 | org.h2.Driver 11 | jdbc:h2:mem:testdb 12 | sa 13 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /src/test/java/guru/springframework/blog/BlogPostsApplicationTests.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.blog; 2 | 3 | import org.junit.Test; 4 | import org.junit.runner.RunWith; 5 | import org.springframework.boot.test.SpringApplicationConfiguration; 6 | import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; 7 | 8 | @RunWith(SpringJUnit4ClassRunner.class) 9 | @SpringApplicationConfiguration(classes = BlogPostsApplication.class) 10 | public class BlogPostsApplicationTests { 11 | 12 | @Test 13 | public void contextLoads() { 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /src/test/java/guru/springframework/blog/contextrefresh/ContextRefreshedListenerTest.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.blog.contextrefresh; 2 | 3 | import guru.springframework.blog.contextrefresh.config.ContextRefreshConfig; 4 | import org.junit.Test; 5 | import org.junit.runner.RunWith; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.test.context.ContextConfiguration; 8 | import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; 9 | 10 | import static org.junit.Assert.*; 11 | 12 | @RunWith(SpringJUnit4ClassRunner.class) 13 | @ContextConfiguration(classes = {ContextRefreshConfig.class}) 14 | public class ContextRefreshedListenerTest { 15 | 16 | private EventHolderBean eventHolderBean; 17 | 18 | @Autowired 19 | public void setEventHolderBean(EventHolderBean eventHolderBean) { 20 | this.eventHolderBean = eventHolderBean; 21 | } 22 | 23 | @Test 24 | public void testContext(){ 25 | assertTrue(eventHolderBean.getEventFired()); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/test/java/guru/springframework/blog/contextrefresh/config/ContextRefreshConfig.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.blog.contextrefresh.config; 2 | 3 | import org.springframework.context.annotation.ComponentScan; 4 | import org.springframework.context.annotation.Configuration; 5 | 6 | @Configuration 7 | @ComponentScan("guru.springframework.blog.contextrefresh") 8 | public class ContextRefreshConfig { 9 | } 10 | -------------------------------------------------------------------------------- /src/test/java/guru/springframework/blog/currenttime/CurrentTimeDateCalendarTest.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.blog.currenttime; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.junit.Assert.*; 6 | 7 | 8 | public class CurrentTimeDateCalendarTest { 9 | 10 | @Test 11 | public void testGetCurrentTimeUsingDate() throws Exception { 12 | CurrentTimeDateCalendar.getCurrentTimeUsingDate(); 13 | 14 | } 15 | 16 | @Test 17 | public void testGetCurrentTimeUsingCalendar() throws Exception { 18 | CurrentTimeDateCalendar.getCurrentTimeUsingCalendar(); 19 | } 20 | } -------------------------------------------------------------------------------- /src/test/java/guru/springframework/blog/currenttime/CurrentTimeJava8Test.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.blog.currenttime; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.junit.Assert.*; 6 | 7 | public class CurrentTimeJava8Test { 8 | @Test 9 | public void testGetCurrentTime() throws Exception { 10 | CurrentTimeJava8.getCurrentTime(); 11 | } 12 | @Test 13 | public void testGetCurrentTimeWithTimeZone() throws Exception { 14 | CurrentTimeJava8.getCurrentTimeWithTimeZone(); 15 | } 16 | @Test 17 | public void testGetCurrentTimeWithOffset() throws Exception { 18 | CurrentTimeJava8.getCurrentTimeWithOffset(); 19 | } 20 | } -------------------------------------------------------------------------------- /src/test/java/guru/springframework/blog/dependencyinversionprinciple/highlevel/ElectricPowerSwitchTest.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.blog.dependencyinversionprinciple.highlevel; 2 | 3 | import guru.springframework.blog.dependencyinversionprinciple.lowlevel.Fan; 4 | import guru.springframework.blog.dependencyinversionprinciple.lowlevel.LightBulb; 5 | import org.junit.Test; 6 | 7 | public class ElectricPowerSwitchTest { 8 | 9 | @Test 10 | public void testPress() throws Exception { 11 | Switchable switchableBulb=new LightBulb(); 12 | Switch bulbPowerSwitch=new ElectricPowerSwitch(switchableBulb); 13 | bulbPowerSwitch.press(); 14 | bulbPowerSwitch.press(); 15 | 16 | Switchable switchableFan=new Fan(); 17 | Switch fanPowerSwitch=new ElectricPowerSwitch(switchableFan); 18 | fanPowerSwitch.press(); 19 | fanPowerSwitch.press(); 20 | } 21 | } -------------------------------------------------------------------------------- /src/test/java/guru/springframework/blog/hibernatepagination/dao/ProductDaoTest.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.blog.hibernatepagination.dao; 2 | 3 | import org.junit.After; 4 | import org.junit.Before; 5 | import org.junit.Test; 6 | import static org.junit.Assert.*; 7 | 8 | public class ProductDaoTest { 9 | ProductDao productDao; 10 | @Before 11 | public void setUp() throws Exception { 12 | productDao = new ProductDao(); 13 | productDao.saveProducts(); 14 | } 15 | @After 16 | public void cleanUp(){ 17 | productDao.deleteAllProducts(); 18 | } 19 | @Test 20 | public void testListPaginatedProductsUsingQuery() throws Exception { 21 | int count = productDao.listPaginatedProductsUsingQuery(0,10); 22 | assertEquals(10, count); 23 | } 24 | @Test 25 | public void testListPaginatedProductsUsingCriteria() throws Exception { 26 | int count=productDao.listPaginatedProductsUsingCriteria(10, 5); 27 | assertEquals(5,count); 28 | } 29 | @Test 30 | public void testListPaginatedProductsUsingScrollableResultSet() throws Exception { 31 | int totalProducts=productDao.listPaginatedProductsUsingScrollableResults(0, 3); 32 | assertEquals(30,totalProducts); 33 | } 34 | } -------------------------------------------------------------------------------- /src/test/java/guru/springframework/blog/interfacesegregationprinciple/ToyBuilderTest.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.blog.interfacesegregationprinciple; 2 | 3 | import org.junit.Test; 4 | 5 | public class ToyBuilderTest { 6 | 7 | @Test 8 | public void testBuildToyHouse() throws Exception { 9 | ToyHouse toyHouse=ToyBuilder.buildToyHouse(); 10 | System.out.println(toyHouse); 11 | } 12 | 13 | @Test 14 | public void testBuildToyCar() throws Exception { 15 | ToyCar toyCar=ToyBuilder.buildToyCar();; 16 | System.out.println(toyCar); 17 | } 18 | 19 | @Test 20 | public void testBuildToyPlane() throws Exception { 21 | ToyPlane toyPlane=ToyBuilder.buildToyPlane(); 22 | System.out.println(toyPlane); 23 | } 24 | } -------------------------------------------------------------------------------- /src/test/java/guru/springframework/blog/log4joverview/MyAppTest.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.blog.log4joverview; 2 | 3 | import org.junit.Test; 4 | import static org.junit.Assert.*; 5 | 6 | public class MyAppTest { 7 | @Test 8 | public void testPerformSomeTask() throws Exception { 9 | MyApp app=new MyApp(); 10 | app.performSomeTask(); 11 | 12 | } 13 | } -------------------------------------------------------------------------------- /src/test/java/guru/springframework/blog/monetarycalculations/BigDecimalCalcTest.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.blog.monetarycalculations; 2 | 3 | import org.junit.Test; 4 | 5 | 6 | public class BigDecimalCalcTest { 7 | 8 | @Test 9 | public void testCalculate() throws Exception { 10 | new BigDecimalCalc().calculate("4.0", "2.0"); 11 | } 12 | 13 | @Test 14 | public void testDivideWithScaleRounding() throws Exception { 15 | new BigDecimalCalc().divideWithScaleRounding("2.5", "3.5"); 16 | } 17 | 18 | @Test 19 | public void testCalculateTax() throws Exception { 20 | new BigDecimalCalc().calculateTax("10.00", ".0825"); 21 | } 22 | } -------------------------------------------------------------------------------- /src/test/java/guru/springframework/blog/openclosedprinciple/ClaimApprovalManagerTest.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.blog.openclosedprinciple; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.junit.Assert.*; 6 | 7 | 8 | public class ClaimApprovalManagerTest { 9 | 10 | @Test 11 | public void testProcessClaim() throws Exception { 12 | HealthInsuranceSurveyor healthInsuranceSurveyor=new HealthInsuranceSurveyor(); 13 | ClaimApprovalManager claim1=new ClaimApprovalManager(); 14 | claim1.processClaim(healthInsuranceSurveyor); 15 | 16 | VehicleInsuranceSurveyor vehicleInsuranceSurveyor=new VehicleInsuranceSurveyor(); 17 | ClaimApprovalManager claim2=new ClaimApprovalManager(); 18 | claim2.processClaim(vehicleInsuranceSurveyor); 19 | } 20 | } -------------------------------------------------------------------------------- /src/test/java/guru/springframework/blog/sortarraylist/ascendingdescending/SortArrayListAscendingDescendingTest.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.blog.sortarraylist.ascendingdescending; 2 | 3 | import org.junit.Test; 4 | 5 | import java.util.ArrayList; 6 | 7 | import static org.junit.Assert.*; 8 | 9 | 10 | public class SortArrayListAscendingDescendingTest { 11 | 12 | @Test 13 | public void testSortAscendingDescending() throws Exception { 14 | ArrayList countryList = new ArrayList<>(); 15 | countryList.add("France"); 16 | countryList.add("USA"); 17 | countryList.add("India"); 18 | countryList.add("Spain"); 19 | countryList.add("England"); 20 | SortArrayListAscendingDescending sortArrayList = new SortArrayListAscendingDescending(countryList); 21 | ArrayList unsortedArrayList = sortArrayList.getArrayList(); 22 | System.out.println("Unsorted ArrayList: " + unsortedArrayList); 23 | ArrayList sortedArrayListAscending = sortArrayList.sortAscending(); 24 | System.out.println("Sorted ArrayList in Ascending Order : " + sortedArrayListAscending); 25 | ArrayList sortedArrayListDescending = sortArrayList.sortDescending(); 26 | System.out.println("Sorted ArrayList in Descending Order: " + sortedArrayListDescending); 27 | } 28 | } -------------------------------------------------------------------------------- /src/test/java/guru/springframework/blog/sortarraylist/comparable/JobCandidateSorterTest.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.blog.sortarraylist.comparable; 2 | 3 | import org.junit.Test; 4 | 5 | import java.lang.reflect.Array; 6 | import java.util.ArrayList; 7 | 8 | import static org.junit.Assert.*; 9 | 10 | 11 | public class JobCandidateSorterTest { 12 | 13 | @Test 14 | public void testGetSortedJobCandidateByAge() throws Exception { 15 | JobCandidate jobCandidate1 = new JobCandidate("Mark Smith", "Male", 26); 16 | JobCandidate jobCandidate2 = new JobCandidate("Sandy Hunt", "Female", 23); 17 | JobCandidate jobCandidate3 = new JobCandidate("Betty Clark", "Female", 20); 18 | JobCandidate jobCandidate4 = new JobCandidate("Andrew Styne", "Male", 24); 19 | ArrayList jobCandidateList = new ArrayList<>(); 20 | jobCandidateList.add(jobCandidate1); 21 | jobCandidateList.add(jobCandidate2); 22 | jobCandidateList.add(jobCandidate3); 23 | jobCandidateList.add(jobCandidate4); 24 | JobCandidateSorter jobCandidateSorter = new JobCandidateSorter(jobCandidateList); 25 | ArrayList sortedJobCandidate = jobCandidateSorter.getSortedJobCandidateByAge(); 26 | System.out.println("-----Sorted JobCandidate by age: Ascending-----"); 27 | for (JobCandidate jobCandidate : sortedJobCandidate) { 28 | System.out.println(jobCandidate); 29 | } 30 | 31 | } 32 | } -------------------------------------------------------------------------------- /src/test/java/guru/springframework/blog/sortarraylist/comparator/JobCandidateSorterTest.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.blog.sortarraylist.comparator; 2 | 3 | 4 | import guru.springframework.blog.sortarraylist.comparator.JobCandidate; 5 | import guru.springframework.blog.sortarraylist.comparator.JobCandidateSorter; 6 | import org.junit.Before; 7 | import org.junit.Test; 8 | 9 | import java.util.ArrayList; 10 | 11 | import static org.junit.Assert.*; 12 | 13 | public class JobCandidateSorterTest { 14 | JobCandidateSorter jobCandidateSorter; 15 | 16 | @Before 17 | public void setUp() throws Exception { 18 | JobCandidate jobCandidate1 = new JobCandidate("Mark Smith", "Male", 26); 19 | JobCandidate jobCandidate2 = new JobCandidate("Sandy Hunt", "Female", 23); 20 | JobCandidate jobCandidate3 = new JobCandidate("Betty Clark", "Female", 20); 21 | JobCandidate jobCandidate4 = new JobCandidate("Andrew Styne", "Male", 24); 22 | ArrayList jobCandidateList = new ArrayList<>(); 23 | jobCandidateList.add(jobCandidate1); 24 | jobCandidateList.add(jobCandidate2); 25 | jobCandidateList.add(jobCandidate3); 26 | jobCandidateList.add(jobCandidate4); 27 | jobCandidateSorter = new JobCandidateSorter(jobCandidateList); 28 | } 29 | 30 | @Test 31 | public void testGetSortedJobCandidateByAge() throws Exception { 32 | System.out.println("-----Sorted JobCandidate by age: Descending-----"); 33 | ArrayList sortedJobCandidate = jobCandidateSorter.getSortedJobCandidateByAge(); 34 | for (JobCandidate jobCandidate : sortedJobCandidate) { 35 | System.out.println(jobCandidate); 36 | } 37 | } 38 | 39 | @Test 40 | public void testGetSortedJobCandidateByName() throws Exception { 41 | System.out.println("-----Sorted JobCandidate by name: Ascending-----"); 42 | ArrayList sortedJobCandidate = jobCandidateSorter.getSortedJobCandidateByName(); 43 | for (JobCandidate jobCandidate : sortedJobCandidate) { 44 | System.out.println(jobCandidate); 45 | } 46 | 47 | } 48 | } --------------------------------------------------------------------------------