Merge pull request #1 from akeshri/feature/MapFirstPair

first pair code
This commit is contained in:
akeshri 2020-09-08 21:10:12 +05:30 committed by GitHub
commit b3c1df2bbc
18 changed files with 182 additions and 499 deletions

View File

@ -0,0 +1,17 @@
/**
*
*/
package com.baeldung.collections.mapfirstpair;
import java.util.Map;
/**
* @author ASHWINI
*
*/
public interface MapFirstPairService {
<K, V> Map.Entry<K, V> getFirstPairUsingIterator(Map<K, V> map);
<K, V> Map.Entry<K, V> getFirstPairUsingStream(Map<K, V> map);
}

View File

@ -0,0 +1,40 @@
/**
*
*/
package com.baeldung.collections.mapfirstpair;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
/**
* @author ASHWINI
*
*/
public class MapFirstPairServiceImpl implements MapFirstPairService {
public <K, V> Map.Entry<K, V> getFirstPairUsingIterator(Map<K, V> map) {
if (map == null || map.size() == 0)
return null;
Iterator<Map.Entry<K, V>> iterator = map.entrySet()
.iterator();
if (iterator.hasNext())
return iterator.next();
return null;
}
public <K, V> Map.Entry<K, V> getFirstPairUsingStream(Map<K, V> map) {
if (map == null || map.size() == 0)
return null;
Set<Map.Entry<K, V>> entrySet = map.entrySet();
return entrySet.stream()
.findFirst()
.get();
}
}

View File

@ -0,0 +1,125 @@
package com.baeldung.collections.mapfirstpair;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import java.util.AbstractMap;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import org.junit.Before;
import org.junit.Test;
public class MapFirstPairServiceUnitTest {
private MapFirstPairService mapFirstPairService;
@Before
public void Setup() {
mapFirstPairService = new MapFirstPairServiceImpl();
}
private void populateMapValues(Map<Integer, String> map) {
if (map != null) {
map.put(5, "A");
map.put(1, "B");
map.put(2, "C");
}
}
@Test
public void whenUsingIteratorForHashMap() {
Map<Integer, String> hashMap = new HashMap<>();
populateMapValues(hashMap);
Map.Entry<Integer, String> actualValue = mapFirstPairService.getFirstPairUsingIterator(hashMap);
Map.Entry<Integer, String> expectedValue = new AbstractMap.SimpleEntry<Integer, String>(1, "B");
Map.Entry<Integer, String> pairInsertedFirst = new AbstractMap.SimpleEntry<Integer, String>(5, "A");
assertEquals(expectedValue, actualValue);
assertNotEquals(pairInsertedFirst, actualValue);
}
@Test
public void whenUsingStreamForHashMap() {
Map<Integer, String> hashMap = new HashMap<>();
populateMapValues(hashMap);
Map.Entry<Integer, String> actualValue = mapFirstPairService.getFirstPairUsingStream(hashMap);
Map.Entry<Integer, String> expectedValue = new AbstractMap.SimpleEntry<Integer, String>(1, "B");
Map.Entry<Integer, String> pairInsertedFirst = new AbstractMap.SimpleEntry<Integer, String>(5, "A");
assertEquals(expectedValue, actualValue);
assertNotEquals(pairInsertedFirst, actualValue);
}
@Test
public void whenUsingIteratorForLinkedHashMap() {
Map<Integer, String> linkedHashMap = new LinkedHashMap<>();
populateMapValues(linkedHashMap);
Map.Entry<Integer, String> actualValue = mapFirstPairService.getFirstPairUsingIterator(linkedHashMap);
Map.Entry<Integer, String> expectedValue = new AbstractMap.SimpleEntry<Integer, String>(5, "A");
assertEquals(expectedValue, actualValue);
}
@Test
public void whenUsingStreamForLinkedHashMap() {
Map<Integer, String> linkedHashMap = new LinkedHashMap<>();
populateMapValues(linkedHashMap);
Map.Entry<Integer, String> actualValue = mapFirstPairService.getFirstPairUsingStream(linkedHashMap);
Map.Entry<Integer, String> expectedValue = new AbstractMap.SimpleEntry<Integer, String>(5, "A");
assertEquals(expectedValue, actualValue);
}
@Test
public void whenAddedAnElementInHashMap_thenFirstPairChangedUsingIterator() {
Map<Integer, String> hashMap = new HashMap<>();
populateMapValues(hashMap);
hashMap.put(0, "D");
Map.Entry<Integer, String> actualValue = mapFirstPairService.getFirstPairUsingIterator(hashMap);
Map.Entry<Integer, String> expectedValue = new AbstractMap.SimpleEntry<Integer, String>(0, "D");
assertEquals(expectedValue, actualValue);
}
@Test
public void whenAddedAnElementInHashMap_thenFirstPairChangedUsingStream() {
Map<Integer, String> hashMap = new HashMap<>();
populateMapValues(hashMap);
hashMap.put(0, "D");
Map.Entry<Integer, String> actualValue = mapFirstPairService.getFirstPairUsingStream(hashMap);
Map.Entry<Integer, String> expectedValue = new AbstractMap.SimpleEntry<Integer, String>(0, "D");
assertEquals(expectedValue, actualValue);
}
@Test
public void whenAddedAnElementInLinkedHashMap_thenFirstPairRemainUnchangedUsingIterator() {
Map<Integer, String> linkedHashMap = new LinkedHashMap<>();
populateMapValues(linkedHashMap);
linkedHashMap.put(0, "D");
Map.Entry<Integer, String> actualValue = mapFirstPairService.getFirstPairUsingIterator(linkedHashMap);
Map.Entry<Integer, String> expectedValue = new AbstractMap.SimpleEntry<Integer, String>(5, "A");
assertEquals(expectedValue, actualValue);
}
@Test
public void whenAddedAnElementInLinkedHashMap_thenFirstPairRemainUnchangedUsingStream() {
Map<Integer, String> linkedHashMap = new LinkedHashMap<>();
populateMapValues(linkedHashMap);
linkedHashMap.put(0, "D");
Map.Entry<Integer, String> actualValue = mapFirstPairService.getFirstPairUsingStream(linkedHashMap);
Map.Entry<Integer, String> expectedValue = new AbstractMap.SimpleEntry<Integer, String>(5, "A");
assertEquals(expectedValue, actualValue);
}
}

View File

@ -1,17 +0,0 @@
# Hexagonal Architecture
A quick and practical example of Hexagonal Architecture using Spring boot.
This application is using h2 database,which can be accessible http:/localhost:8080/h2
Main Application schema : hexagonal
Test Application Schema : hexagonal_test
1. Rest Api : execute [App](https://github.com/akeshri/tutorials/blob/master/hexagonal-architecture/src/main/java/com/baeldung/hexagonal/architecture/App.java)
- Get All products : http://localhost:8080/api/v1/product/all
- Get product by id : http://localhost:8080/api/v1/product/{productId}
- Add a product : http://localhost:8080/api/v1/product/add
For more detail refer [ProductController](https://github.com/akeshri/tutorials/blob/master/hexagonal-architecture/src/main/java/com/baeldung/hexagonal/architecture/controller/ProductController.java)
2. Batch processing : We need to configure active profile as batch i.e. -Dspring.profiles.active=batch and execute [ConsoleApp](https://github.com/akeshri/tutorials/blob/master/hexagonal-architecture/src/main/java/com/baeldung/hexagonal/architecture/ConsoleApp.java)
3. Test case : [ProductServiceTest](https://github.com/akeshri/tutorials/blob/master/hexagonal-architecture/src/test/java/com/baeldung/hexagonal/architecture/service/ProductServiceTest.java)

View File

@ -1,48 +0,0 @@
<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>com.article</groupId>
<artifactId>hexagonal-architecture</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.1.RELEASE</version>
</parent>
<name>hexagonal-architecture</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.target>1.8</maven.compiler.target>
<maven.compiler.source>1.8</maven.compiler.source>
</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-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-csv</artifactId>
</dependency>
</dependencies>
</project>

View File

@ -1,16 +0,0 @@
package com.baeldung.hexagonal.architecture;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* @author AshwiniKeshri
*
*/
@SpringBootApplication
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}

View File

@ -1,50 +0,0 @@
package com.baeldung.hexagonal.architecture;
import java.io.File;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoConfiguration;
import org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration;
import com.baeldung.hexagonal.architecture.model.Product;
import com.baeldung.hexagonal.architecture.service.ProductService;
import com.fasterxml.jackson.dataformat.csv.CsvMapper;
import com.fasterxml.jackson.dataformat.csv.CsvSchema;
/**
* @author AshwiniKeshri
*
*/
@SpringBootApplication(exclude = { EmbeddedServletContainerAutoConfiguration.class, WebMvcAutoConfiguration.class })
public class ConsoleApp implements CommandLineRunner {
@Autowired
private ProductService productService;
public static void main(String[] args) {
SpringApplication.run(ConsoleApp.class, args);
}
@Override
public void run(String... args) throws Exception {
String filePath = "";
if (args != null && args.length == 2 && "Product".equalsIgnoreCase(args[0]) && (filePath = args[1]).length() > 0) {
File sourceFile = new File(filePath);
if (sourceFile.exists()) {
CsvMapper mapper = new CsvMapper();
List<Product> products = mapper.readerFor(Product.class)
.with(CsvSchema.emptySchema()
.withHeader())
.<Product> readValues(sourceFile)
.readAll();
productService.saveAll(products);
}
}
}
}

View File

@ -1,55 +0,0 @@
package com.baeldung.hexagonal.architecture.controller;
import java.util.List;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.baeldung.hexagonal.architecture.dtos.ProductDto;
import com.baeldung.hexagonal.architecture.model.Product;
import com.baeldung.hexagonal.architecture.service.ProductService;
/**
* @author AshwiniKeshri
*
*/
@RestController
@RequestMapping("api/v1/product")
public class ProductController {
@Autowired
private ProductService productService;
@RequestMapping(value = "/all", method = RequestMethod.GET)
public List<ProductDto> list() {
return productService.findAll()
.stream()
.map(p -> new ProductDto(p))
.collect(Collectors.toList());
}
@RequestMapping(value = "/{productId}", method = RequestMethod.GET)
public ProductDto get(@PathVariable long productId) {
Product p = productService.findById(productId);
return p != null ? new ProductDto(p) : null;
}
@RequestMapping(value = "/add", method = RequestMethod.POST)
public ProductDto create(@RequestBody ProductDto product) {
Product p = new Product();
p.setDescription(product.getDescription());
p.setName(product.getName());
p.setPrice(product.getPrice());
p.setQuantity(product.getQuantity());
Long id = productService.create(p);
product.setId(id);
return product;
}
}

View File

@ -1,72 +0,0 @@
package com.baeldung.hexagonal.architecture.dtos;
import com.baeldung.hexagonal.architecture.model.Product;
/**
* @author AshwiniKeshri
*
*/
public class ProductDto {
private Long id;
private String name;
private Long quantity;
private Double price;
private String description;
public ProductDto() {
}
public ProductDto(Product product) {
this.description = product.getDescription();
this.id = product.getId();
this.name = product.getName();
this.price = product.getPrice();
this.quantity = product.getQuantity();
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Long getQuantity() {
return quantity;
}
public void setQuantity(Long quantity) {
this.quantity = quantity;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}

View File

@ -1,85 +0,0 @@
/**
*
*/
package com.baeldung.hexagonal.architecture.model;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* @author AshwiniKeshri
*
*/
@Entity
@Table(name = "PRODUCT")
public class Product implements Serializable {
/**
*
*/
private static final long serialVersionUID = 4000353732860709995L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(name = "NAME")
private String name;
@Column(name = "QUANTITY")
private Long quantity;
@Column(name = "PRICE")
private Double price;
@Column(name = "DESCRIPTION")
private String description;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Long getQuantity() {
return quantity;
}
public void setQuantity(Long quantity) {
this.quantity = quantity > 0 ? quantity : 0;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price == null ? 0.0 : price;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}

View File

@ -1,14 +0,0 @@
package com.baeldung.hexagonal.architecture.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import com.baeldung.hexagonal.architecture.model.Product;
/**
* @author AshwiniKeshri
*
*/
public interface ProductRepository extends JpaRepository<Product, Long> {
}

View File

@ -1,21 +0,0 @@
package com.baeldung.hexagonal.architecture.service;
import java.util.List;
import com.baeldung.hexagonal.architecture.model.Product;
/**
* @author AshwiniKeshri
*
*/
public interface ProductService {
List<Product> findAll();
Product findById(long id);
Long create(Product product);
void saveAll(List<Product> products);
}

View File

@ -1,44 +0,0 @@
package com.baeldung.hexagonal.architecture.service;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baeldung.hexagonal.architecture.model.Product;
import com.baeldung.hexagonal.architecture.repository.ProductRepository;
/**
* @author AshwiniKeshri
*
*/
@Service
public class ProductServiceImpl implements ProductService {
private Logger logger = LoggerFactory.getLogger(ProductServiceImpl.class);
@Autowired
private ProductRepository productRepository;
public List<Product> findAll() {
return productRepository.findAll();
}
public Product findById(long id) {
return productRepository.findOne(id);
}
public Long create(Product product) {
product = productRepository.saveAndFlush(product);
return product.getId();
}
@Override
public void saveAll(List<Product> products) {
productRepository.save(products);
}
}

View File

@ -1,9 +0,0 @@
spring.main.web-environment=false
spring.jpa.hibernate.ddl-auto=false;
spring.h2.console.enabled=true
spring.h2.console.path=/h2
spring.datasource.url=jdbc:h2:file:~/hexagonal
spring.datasource.username=sa
spring.datasource.password=
spring.datasource.driver-class-name=org.h2.Driver

View File

@ -1,8 +0,0 @@
spring.jpa.hibernate.ddl-auto=false;
spring.h2.console.enabled=true
spring.h2.console.path=/h2
spring.datasource.url=jdbc:h2:file:~/hexagonal_test
spring.datasource.username=sa
spring.datasource.password=
spring.datasource.driver-class-name=org.h2.Driver

View File

@ -1,8 +0,0 @@
spring.jpa.hibernate.ddl-auto=false;
spring.h2.console.enabled=true
spring.h2.console.path=/h2
spring.datasource.url=jdbc:h2:file:~/hexagonal
spring.datasource.username=sa
spring.datasource.password=
spring.datasource.driver-class-name=org.h2.Driver

View File

@ -1,9 +0,0 @@
CREATE TABLE PRODUCT(
ID INT AUTO_INCREMENT,
NAME VARCHAR(255),
QUANTITY INTEGER,
PRICE DOUBLE,
DESCRIPTION VARCHAR(1000),
);
INSERT INTO PRODUCT(NAME,QUANTITY,PRICE,DESCRIPTION) VALUES ('iPhone 11 Pro',10,300,'First triple camera system');

View File

@ -1,43 +0,0 @@
/**
*
*/
package com.baeldung.hexagonal.architecture.service;
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.SpringApplicationConfiguration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.PropertySources;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.baeldung.hexagonal.architecture.App;
import com.baeldung.hexagonal.architecture.model.Product;
import com.baeldung.hexagonal.architecture.service.ProductService;
/**
* @author AshwiniKeshri
*
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(App.class)
@ActiveProfiles(value = "test")
public class ProductServiceTest {
@Autowired
private ProductService productService;
@Test
public void testCreateProduct() {
Product product = new Product();
product.setDescription("test product");
product.setName("Product1");
product.setPrice(10.0);
product.setQuantity(100l);
Long id = productService.create(product);
Assert.assertTrue(id > 0);
}
}