Merge pull request #2208 from hmantri05/master

Moving Address into Customer
This commit is contained in:
slavisa-baeldung 2017-07-05 15:41:49 +02:00 committed by GitHub
commit 8746b525d5
32 changed files with 1114 additions and 0 deletions

8
.gitignore vendored
View File

@ -33,3 +33,11 @@ spring-openid/src/main/resources/application.properties
spring-security-openid/src/main/resources/application.properties
spring-all/*.log
*.jar
SpringDataInjectionDemo/.mvn/wrapper/maven-wrapper.properties
spring-call-getters-using-reflection/.mvn/wrapper/maven-wrapper.properties
spring-check-if-a-property-is-null/.mvn/wrapper/maven-wrapper.properties

24
SpringDataInjectionDemo/.gitignore vendored Normal file
View File

@ -0,0 +1,24 @@
target/
!.mvn/wrapper/maven-wrapper.jar
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
nbproject/private/
build/
nbbuild/
dist/
nbdist/
.nb-gradle/

View File

@ -0,0 +1,49 @@
<?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>baeldung</groupId>
<artifactId>springdatainjectiondemo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>SpringDataInjectionDemo</name>
<description>Spring Data Injection Demp</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.3.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,12 @@
package com.baeldung;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringDataInjectionDemoApplication {
public static void main(String[] args) {
SpringApplication.run(SpringDataInjectionDemoApplication.class, args);
}
}

View File

@ -0,0 +1,46 @@
package com.baeldung.didemo.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.baeldung.didemo.model.Order;
import com.baeldung.didemo.service.CustomerServiceConstructorDI;
import com.baeldung.didemo.service.CustomerServiceConstructorWithoutSpringDI;
import com.baeldung.didemo.service.CustomerServiceFieldDI;
import com.baeldung.didemo.service.CustomerServiceSetterDI;
import com.baeldung.didemo.service.OrderService;
@RestController
@RequestMapping(value = "/orders")
public class OrderController {
@Autowired
CustomerServiceConstructorDI constructorDI;
@Autowired
CustomerServiceFieldDI fieldDI;
@Autowired
CustomerServiceSetterDI setterDI;
@RequestMapping(method = RequestMethod.GET)
public List<Order> getOrdersFieldDI(@RequestParam(required = false) String dIMethod) {
if ("setter".equals(dIMethod)) {
return setterDI.getCustomerOrders(1l);
} else if ("constructor".equals(dIMethod)) {
return constructorDI.getCustomerOrders(1l);
} else if ("field".equals(dIMethod)) {
return fieldDI.getCustomerOrders(1l);
} else {
OrderService orderSvc = new OrderService();
CustomerServiceConstructorWithoutSpringDI customerSvc = new CustomerServiceConstructorWithoutSpringDI(orderSvc);
return customerSvc.getCustomerOrders(1l);
}
}
}

View File

@ -0,0 +1,26 @@
package com.baeldung.didemo.model;
public class Order {
private Integer id;
private String item;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getItem() {
return item;
}
public void setItem(String item) {
this.item = item;
}
// other order properties..
}

View File

@ -0,0 +1,25 @@
package com.baeldung.didemo.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baeldung.didemo.model.Order;
@Service
public class CustomerServiceConstructorDI {
OrderService orderService;
@Autowired
public CustomerServiceConstructorDI(OrderService orderService) {
super();
this.orderService = orderService;
}
public List<Order> getCustomerOrders(Long customerId) {
return orderService.getOrdersForCustomer(customerId);
}
}

View File

@ -0,0 +1,20 @@
package com.baeldung.didemo.service;
import java.util.List;
import com.baeldung.didemo.model.Order;
public class CustomerServiceConstructorWithoutSpringDI {
OrderService orderService;
public CustomerServiceConstructorWithoutSpringDI(OrderService orderService) {
super();
this.orderService = orderService;
}
public List<Order> getCustomerOrders(Long customerId) {
return orderService.getOrdersForCustomer(customerId);
}
}

View File

@ -0,0 +1,19 @@
package com.baeldung.didemo.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baeldung.didemo.model.Order;
@Service
public class CustomerServiceFieldDI {
@Autowired
OrderService orderService;
public List<Order> getCustomerOrders(Long customerId) {
return orderService.getOrdersForCustomer(customerId);
}
}

View File

@ -0,0 +1,24 @@
package com.baeldung.didemo.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baeldung.didemo.model.Order;
@Service
public class CustomerServiceSetterDI {
OrderService orderService;
public List<Order> getCustomerOrders(Long customerId) {
return orderService.getOrdersForCustomer(customerId);
}
@Autowired
public void setOrderService(OrderService orderService) {
this.orderService = orderService;
}
}

View File

@ -0,0 +1,30 @@
package com.baeldung.didemo.service;
import java.util.ArrayList;
import java.util.List;
import org.springframework.stereotype.Service;
import com.baeldung.didemo.model.Order;
@Service
public class OrderService {
public List<Order> getOrdersForCustomer(Long id) {
List<Order> orders = new ArrayList<Order>();
Order order1 = new Order();
order1.setId(1);
order1.setItem("Pizza");
Order order2 = new Order();
order2.setId(1);
order2.setItem("Garlic Bread");
orders.add(order1);
orders.add(order2);
return orders;
}
}

View File

@ -0,0 +1,65 @@
package com.baeldung.didemo;
import java.util.List;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import com.baeldung.didemo.model.Order;
import com.baeldung.didemo.service.CustomerServiceConstructorDI;
import com.baeldung.didemo.service.CustomerServiceFieldDI;
import com.baeldung.didemo.service.CustomerServiceSetterDI;
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringDataInjectionDemoApplicationTests {
@Autowired
CustomerServiceConstructorDI constructorDI;
@Autowired
CustomerServiceFieldDI fieldDI;
@Autowired
CustomerServiceSetterDI setterDI;
@Test
public void givenConstructorDI_whenNumberOfOrdersIsTwo_thenCorrect() {
List<Order> orders = constructorDI.getCustomerOrders(1l);
Assert.assertNotNull(orders);
Assert.assertTrue(orders.size() == 2);
}
@Test
public void givenFieldDI_whenNumberOfOrdersIsTwo_thenCorrect() {
List<Order> orders = fieldDI.getCustomerOrders(1l);
Assert.assertNotNull(orders);
Assert.assertTrue(orders.size() == 2);
}
@Test
public void givenSetterDI_whenNumberOfOrdersIsTwo_thenCorrect() {
List<Order> orders = setterDI.getCustomerOrders(1l);
Assert.assertNotNull(orders);
Assert.assertTrue(orders.size() == 2);
}
@Test
public void givenAllThreeTypesOfDI_whenNumberOfOrdersIsEqualInAll_thenCorrect() {
List<Order> ordersSetter = setterDI.getCustomerOrders(1l);
List<Order> ordersConstructor = constructorDI.getCustomerOrders(1l);
List<Order> ordersField = fieldDI.getCustomerOrders(1l);
Assert.assertNotNull(ordersSetter);
Assert.assertNotNull(ordersConstructor);
Assert.assertNotNull(ordersField);
Assert.assertTrue(ordersSetter.size() == 2 && ordersConstructor.size() == ordersSetter.size() && ordersField.size() == ordersSetter.size());
}
}

24
call-all-getters/.gitignore vendored Normal file
View File

@ -0,0 +1,24 @@
target/
!.mvn/wrapper/maven-wrapper.jar
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
nbproject/private/
build/
nbbuild/
dist/
nbdist/
.nb-gradle/

50
call-all-getters/pom.xml Normal file
View File

@ -0,0 +1,50 @@
<?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>baeldung</groupId>
<artifactId>call-all-getters</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>call-all-getters</name>
<description>Calling all getters using Introspector</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,18 @@
package com.baeldung;
import java.util.List;
import com.baeldung.reflection.model.Customer;
import com.baeldung.reflection.util.Utils;
public class CallAllGettersApplication {
public static void main(String[] args) throws Exception {
Customer customer = new Customer(1, "Himanshu", null, null);
List<String> nullProps = Utils.getNullPropertiesList(customer);
System.out.println(nullProps);
}
}

View File

@ -0,0 +1,63 @@
package com.baeldung.reflection.model;
/**
*
* @author himanshumantri
*
*/
public class Customer {
private Integer id;
private String name;
private String emailId;
private Long phoneNumber;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmailId() {
return emailId;
}
public void setEmailId(String emailId) {
this.emailId = emailId;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("Customer [id=").append(id).append(", name=").append(name).append(", emailId=").append(emailId).append(", phoneNumber=")
.append(phoneNumber).append("]");
return builder.toString();
}
public Customer(Integer id, String name, String emailId, Long phoneNumber) {
super();
this.id = id;
this.name = name;
this.emailId = emailId;
this.phoneNumber = phoneNumber;
}
public Long getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(Long phoneNumber) {
this.phoneNumber = phoneNumber;
}
}

View File

@ -0,0 +1,43 @@
package com.baeldung.reflection.util;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import com.baeldung.reflection.model.Customer;
public class Utils {
public static List<String> getNullPropertiesList(Customer customer) throws Exception {
PropertyDescriptor[] propDescArr = Introspector.getBeanInfo(Customer.class, Object.class).getPropertyDescriptors();
List<PropertyDescriptor> propDescList = Arrays.asList(propDescArr);
List<String> nullProps = propDescList.stream()
.filter(nulls(customer))
.map(PropertyDescriptor::getName)
.collect(Collectors.toList());
return nullProps;
}
private static Predicate<PropertyDescriptor> nulls(Customer customer) {
Predicate<PropertyDescriptor> isNull = new Predicate<PropertyDescriptor>() {
@Override
public boolean test(PropertyDescriptor pd) {
Method getterMethod = pd.getReadMethod();
boolean result = false;
try {
result = (getterMethod != null && getterMethod.invoke(customer) == null);
} catch (Exception e) {
// Handle the exception
e.printStackTrace();
}
return result;
}
};
return isNull;
}
}

View File

@ -0,0 +1,26 @@
package com.baeldung;
import java.util.Arrays;
import java.util.List;
import org.junit.Assert;
import org.junit.Test;
import com.baeldung.reflection.model.Customer;
import com.baeldung.reflection.util.Utils;
public class CallAllGettersApplicationTests {
@Test
public void givenCustomer_whenAFieldIsNull_thenFieldNameInResult() throws Exception {
Customer customer = new Customer(1, "Himanshu", null, null);
List<String> result = Utils.getNullPropertiesList(customer);
List<String> expectedFieldNames = Arrays.asList("emailId","phoneNumber");
Assert.assertTrue(result.size() == expectedFieldNames.size());
Assert.assertTrue(result.containsAll(expectedFieldNames));
}
}

33
collectionutils/pom.xml Normal file
View File

@ -0,0 +1,33 @@
<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>baeldung</groupId>
<artifactId>collectionutils</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>collectionutils-guide</name>
<description>A guide to Apache Commons CollectionUtils</description>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-collections4 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/junit/junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,37 @@
package com.baeldung.collectionutilsguide.model;
public class Address {
String locality;
String city;
public String getLocality() {
return locality;
}
public void setLocality(String locality) {
this.locality = locality;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("Address [locality=").append(locality).append(", city=").append(city).append("]");
return builder.toString();
}
public Address(String locality, String city) {
super();
this.locality = locality;
this.city = city;
}
}

View File

@ -0,0 +1,81 @@
package com.baeldung.collectionutilsguide.model;
public class Customer implements Comparable<Customer> {
Integer id;
String name;
Address address;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public Customer(Integer id, String name, String locality, String city) {
super();
this.id = id;
this.name = name;
this.address = new Address(locality, city);
}
public Customer(String name) {
super();
this.name = name;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Customer other = (Customer) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
public int compareTo(Customer o) {
return this.name.compareTo(o.getName());
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("Customer [id=").append(id).append(", name=").append(name).append("]");
return builder.toString();
}
}

View File

@ -0,0 +1,33 @@
<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>baeldung</groupId>
<artifactId>collectionutils</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>collectionutils-guide</name>
<description>A guide to Apache Commons CollectionUtils</description>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-collections4 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/junit/junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,135 @@
package collectionutils;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import org.apache.commons.collections4.Closure;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.Predicate;
import org.apache.commons.collections4.Transformer;
import org.junit.Test;
import com.baeldung.collectionutilsguide.model.Address;
import com.baeldung.collectionutilsguide.model.Customer;
public class CollectionUtilsGuideTest {
Customer customer1 = new Customer(1, "Daniel", "locality1", "city1");
Customer customer2 = new Customer(2, "Fredrik", "locality2", "city2");
Customer customer3 = new Customer(3, "Kyle", "locality3", "city3");
Customer customer4 = new Customer(4, "Bob", "locality4", "city4");
Customer customer5 = new Customer(5, "Cat", "locality5", "city5");
Customer customer6 = new Customer(6, "John", "locality6", "city6");
List<Customer> list1 = Arrays.asList(customer1, customer2, customer3);
List<Customer> list2 = Arrays.asList(customer4, customer5, customer6);
List<Customer> list3 = Arrays.asList(customer1, customer2);
List<Customer> linkedList1 = new LinkedList<Customer>(list1);
@Test
public void givenList_WhenAddIgnoreNull_thenNoNullAdded() {
CollectionUtils.addIgnoreNull(list1, null);
assertFalse(list1.contains(null));
}
@Test
public void givenTwoSortedLists_WhenCollated_thenSorted() {
List<Customer> sortedList = CollectionUtils.collate(list1, list2);
assertTrue(sortedList.get(0).getName().equals("Bob"));
assertTrue(sortedList.get(2).getName().equals("Daniel"));
}
@Test
public void givenListOfCustomers_whenTransformed_thenListOfAddress() {
Collection<Address> addressCol = CollectionUtils.collect(list1, new Transformer<Customer, Address>() {
public Address transform(Customer customer) {
return customer.getAddress();
}
});
List<Address> addressList = new ArrayList<Address>(addressCol);
assertTrue(addressList.size() == 3);
assertTrue(addressList.get(0).getLocality().equals("locality1"));
}
@Test
public void givenCustomerList_WhenCountMatches_thenCorrect() {
int result = CollectionUtils.countMatches(list1, new Predicate<Customer>() {
public boolean evaluate(Customer customer) {
return Arrays.asList("Daniel","Kyle").contains(customer.getName());
}
});
assertTrue(result == 2);
}
@Test
public void givenCustomerList_WhenFiltered_thenCorrectSize() {
boolean isModified = CollectionUtils.filter(linkedList1, new Predicate<Customer>() {
public boolean evaluate(Customer customer) {
return Arrays.asList("Daniel","Kyle").contains(customer.getName());
}
});
//filterInverse does the opposite. It removes the element from the list if the Predicate returns true
//select and selectRejected work the same way except that they do not remove elements from the given collection and return a new collection
assertTrue(isModified && linkedList1.size() == 2);
}
@Test
public void givenCustomerList_WhenForAllDoSetNameNull_thenNameNull() {
CollectionUtils.forAllDo(list1, new Closure<Customer>() {
public void execute(Customer customer) {
customer.setName(null);
}
});
// forAllButLast does the same except for the last element in the collection
assertTrue(list1.get(0).getName() == null);
}
@Test
public void givenNonEmptyList_WhenCheckedIsNotEmpty_thenTrue() {
List<Customer> emptyList = new ArrayList<Customer>();
List<Customer> nullList = null;
//Very handy at times where we want to check if a collection is not null and not empty too.
//isNotEmpty does the opposite. Handy because using ! operator on isEmpty makes it missable while reading
assertTrue(CollectionUtils.isNotEmpty(list1));
assertTrue(CollectionUtils.isEmpty(nullList));
assertTrue(CollectionUtils.isEmpty(emptyList));
}
@Test
public void givenCustomerListAndASubcollection_WhenChecked_thenTrue() {
assertTrue(CollectionUtils.isSubCollection(list3, list1));
}
@Test
public void givenTwoLists_WhenIntersected_thenCheckSize() {
Collection<Customer> intersection = CollectionUtils.intersection(list1, list3);
assertTrue(intersection.size() == 2);
}
@Test
public void givenTwoLists_WhenSubtracted_thenCheckElementNotPresentInA() {
Collection<Customer> result = CollectionUtils.subtract(list1, list3);
assertFalse(result.contains(customer1));
}
@Test
public void givenTwoLists_WhenUnioned_thenCheckElementPresentInResult() {
Collection<Customer> union = CollectionUtils.union(list1, list2);
assertTrue(union.contains(customer1));
assertTrue(union.contains(customer4));
}
}

View File

@ -0,0 +1,24 @@
target/
!.mvn/wrapper/maven-wrapper.jar
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
nbproject/private/
build/
nbbuild/
dist/
nbdist/
.nb-gradle/

View File

@ -0,0 +1,50 @@
<?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>baeldung</groupId>
<artifactId>spring-check-null</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>spring-check-if-a-property-is-null</name>
<description>Calling getters using Introspector</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,21 @@
package com.baeldung;
import java.util.List;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import com.baeldung.reflection.model.Customer;
import com.baeldung.reflection.util.Utils;
@SpringBootApplication
public class SpringCheckIfAPropertyIsNullApplication {
public static void main(String[] args) throws Exception {
Customer customer = new Customer(1, "Himanshu", null, null);
List<String> nullProps = Utils.getNullPropertiesList(customer);
System.out.println(nullProps);
}
}

View File

@ -0,0 +1,63 @@
package com.baeldung.reflection.model;
/**
*
* @author himanshumantri
*
*/
public class Customer {
private Integer id;
private String name;
private String emailId;
private Long phoneNumber;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmailId() {
return emailId;
}
public void setEmailId(String emailId) {
this.emailId = emailId;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("Customer [id=").append(id).append(", name=").append(name).append(", emailId=").append(emailId).append(", phoneNumber=")
.append(phoneNumber).append("]");
return builder.toString();
}
public Customer(Integer id, String name, String emailId, Long phoneNumber) {
super();
this.id = id;
this.name = name;
this.emailId = emailId;
this.phoneNumber = phoneNumber;
}
public Long getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(Long phoneNumber) {
this.phoneNumber = phoneNumber;
}
}

View File

@ -0,0 +1,34 @@
package com.baeldung.reflection.util;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import com.baeldung.reflection.model.Customer;
public class Utils {
public static List<String> getNullPropertiesList(Customer customer) throws Exception {
PropertyDescriptor[] propDescArr = Introspector.getBeanInfo(Customer.class, Object.class).getPropertyDescriptors();
List<PropertyDescriptor> propDescList = Arrays.asList(propDescArr);
List<String> nullProps = new ArrayList<String>();
propDescList.stream().forEach(p -> {
Method getterMethod = p.getReadMethod();
try {
if (getterMethod != null && getterMethod.invoke(customer) == null) {
// If the value if null for that field
nullProps.add(p.getName());
}
} catch (Exception e) {
// Handle the exception
e.printStackTrace();
}
});
return nullProps;
}
}

View File

@ -0,0 +1,31 @@
package com.baeldung;
import java.util.Arrays;
import java.util.List;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import com.baeldung.reflection.model.Customer;
import com.baeldung.reflection.util.Utils;
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringCheckIfAPropertyIsNullApplicationTests {
@Test
public void givenCustomer_whenAFieldIsNull_thenFieldNameInResult() throws Exception {
Customer customer = new Customer(1, "Himanshu", null, null);
List<String> result = Utils.getNullPropertiesList(customer);
List<String> expectedFieldNames = Arrays.asList("emailId","phoneNumber");
Assert.assertTrue(result.size() == expectedFieldNames.size());
Assert.assertTrue(result.containsAll(expectedFieldNames));
}
}